KMMainViewController.swift 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343
  1. //
  2. // KMMainViewController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Cocoa
  8. @objcMembers class KMMainViewController: KMBaseViewController, NSTextFieldDelegate {
  9. @IBOutlet var PDFContendView: NSView!
  10. @IBOutlet var centerContentView: NSView!
  11. @IBOutlet var listView: CPDFListView!
  12. @IBOutlet var secondaryPdfView: KMSecondaryPDFView?
  13. @IBOutlet weak var readContentView: NSView!
  14. @IBOutlet weak var tipCurrentPageBox: KMBox!
  15. @IBOutlet weak var rightView: NSView!
  16. @IBOutlet weak var leftView: NSView!
  17. @IBOutlet weak var mianSplitView: KMSplitView!
  18. @IBOutlet weak var pdfSplitView: KMSplitView!
  19. @IBOutlet weak var newPDFSplitView: KMSplitView!
  20. @IBOutlet weak var pdfContentView: NSView!
  21. @IBOutlet weak var pdfSplitSecondView: NSBox!
  22. @IBOutlet weak var locationPageView: NSView!
  23. @IBOutlet weak var tipLabel: NSTextField!
  24. @IBOutlet weak var toplayoutConstraint: NSLayoutConstraint!
  25. @IBOutlet var childToolbarController: KMToolbarViewController!
  26. @IBOutlet var toolbarController: KMToolbarController!
  27. @IBOutlet weak var toolbarBox: NSBox!
  28. @IBOutlet weak var heightOffset: NSLayoutConstraint!
  29. //阅读模式界面
  30. @IBOutlet weak var readModelView: KMReadModelView!
  31. @IBOutlet weak var bottomAreaView: KMBox!
  32. @IBOutlet weak var readModelViewWidthConstraint: NSLayoutConstraint!
  33. //页码显示器
  34. @IBOutlet weak var pageNumberDisplayView: KMPageNumberDisplayView!
  35. @IBOutlet weak var tipCurrentPageBoxWidthConstraint: NSLayoutConstraint!
  36. @IBOutlet weak var topTipBox: NSBox!
  37. @IBOutlet weak var exitFullButton: NSButton!
  38. var model = KMMainModel()
  39. var isReadMode: Bool = false
  40. var readAlertView: CustomAlertView?
  41. var readLeftMethodType: BotaType = .None
  42. var readLeftPanelOpen = false
  43. var readLastLeftPanWidth = 0.0
  44. var readLeftViewShowPanel = false
  45. var readRightPanelOpen = false
  46. var readToolbarType: KMToolbarViewType = .None
  47. var readToolbarItemIdentifier: String = ""
  48. var readToolMode: CToolMode = .textToolMode
  49. var readAnnotationType: CAnnotationType = .unkown
  50. var readSubViewType: RightSubViewType = .None
  51. //自动滚动
  52. var autoFlowOptionsSheetController: KMAutoFlowOptionsSheetController?
  53. //Search
  54. var searchIndex: Int = 0
  55. //Form
  56. var formAlertView: KMFormAlertView?
  57. //Secure
  58. var secureAlertView: KMSecureAlertView?
  59. //对比
  60. var isCompareModel: Bool = false {
  61. didSet {
  62. self.toolbarController.updataItemVisible()
  63. }
  64. }
  65. //合并
  66. var mergeWindowController: KMMergeWindowController?
  67. //水印
  68. var watermarkWindowController: KMWatermarkWindowController?
  69. //密码弹窗
  70. var passwordWindow: KMPasswordInputWindow?
  71. //对比
  72. var compressWIndowControllerNew: KMCompressWIndowControllerNew?
  73. //
  74. var securityWindowController: KMSecurityWindowController?
  75. //引导
  76. var guideInfoWindowController: KMGuideInfoWindowController?
  77. //春季活动
  78. var recommondPopWindowVC: KMRecommondPopWindow?
  79. private var _needSave = false
  80. var needSave: Bool {
  81. set {
  82. _needSave = newValue
  83. if (_needSave == false) {
  84. self.clearIsPDFDocumentEdited()
  85. }
  86. }
  87. get {
  88. return _needSave
  89. }
  90. }
  91. var isPDFDocumentEdited: Bool {
  92. get {
  93. return self.model.isPDFDocumentEdited
  94. }
  95. }
  96. var leftSideViewController: KMLeftSideViewController = KMLeftSideViewController.init(type: KMLeftMethodMode())
  97. var rightSideViewController: KMRightSideViewController!
  98. var searchResults: [KMSearchMode] = []
  99. var mwcFlags: MwcFlags = MwcFlags()
  100. var document: CPDFDocument?
  101. var myDocument: NSDocument?
  102. weak var browserWindowController: KMBrowserWindowController?
  103. var cropSettingWindowController: KMCropSettingWindowController!
  104. var currentWindowController: NSWindowController!
  105. var savedNormalSetup: NSMutableDictionary = NSMutableDictionary()
  106. //数字签名
  107. var digitalSignController: KMPDFDigitalSignViewController?
  108. var redactController: KMPDFRedactViewController!
  109. let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  110. let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
  111. var extract: KMExtractImageWindowController?
  112. var functionWidth: Double {
  113. get {
  114. if self.isReadMode {
  115. if !self.model.isShowBOTA {
  116. return 0
  117. }
  118. }
  119. return 48-4
  120. }
  121. }
  122. var pageNumber: UInt?
  123. var openSecondaryPdfView: KMSecondaryViewController?
  124. var secondaryPdfContentView: NSView?
  125. var lastSplitPDFHeight: Float = 0.0
  126. var pdfEditController: KMPDFEditViewController? {
  127. get {
  128. return self.getPDFEditController()
  129. }
  130. }
  131. var autoSaveTimer: Timer?
  132. private var _documentFirstLoad: Bool = true
  133. var eventMonitor: Any?
  134. var keyEventMonitor: Any?
  135. var mouseRightMenuEvent: NSEvent?
  136. var aiTranslationWindow: KMAITranslationWindowController?
  137. var aiTranslationConfirWC: KMAITranslationConfirmWindowController?
  138. lazy private var homeVC: KMHomeViewController? = {
  139. let vc = KMHomeViewController()
  140. return vc
  141. }()
  142. private var background_mask: NSView?
  143. fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
  144. var secureOptions: [CPDFDocumentWriteOption : Any]? {
  145. get {
  146. return self._secureOptions
  147. }
  148. }
  149. var documentAttribute: [CPDFDocumentAttribute : Any]?
  150. fileprivate var _removeSecureFlag = false
  151. var removeSecureFlag: Bool {
  152. get {
  153. return self._removeSecureFlag
  154. }
  155. }
  156. fileprivate var _saveWatermarkFlag = false
  157. var saveWatermarkFlag: Bool {
  158. get {
  159. return self._saveWatermarkFlag
  160. }
  161. }
  162. private var mainWindow_: NSWindow?
  163. var mainWindow: NSWindow? {
  164. get {
  165. return self.mainWindow_
  166. }
  167. set {
  168. self.mainWindow_ = newValue
  169. }
  170. }
  171. deinit {
  172. NotificationCenter.default.removeObserver(self)
  173. self.removeEventMonitor()
  174. self.removeKeyEventMonitor()
  175. }
  176. override func awakeFromNib() {
  177. super.awakeFromNib()
  178. self.addBackgroundMaskView()
  179. self.PDFContendView.backgroundColor(NSColor.km_init(hex: "FFFFFF"))
  180. listView.delegate = self
  181. listView.pdfListViewDelegate = self
  182. // listView.editingConfig().isSupportMultipleSelectEditingArea = true
  183. if (document != nil) {
  184. // if (self.document!.isLocked) {
  185. //
  186. // } else {
  187. listView.document = document
  188. // }
  189. listView.document.delegate = self
  190. let autoScale = listView.autoScales
  191. if !autoScale {
  192. listView.scaleFactor = 1.0
  193. }
  194. }
  195. self.initPDFLeftViewVC()
  196. self.initRightSideView()
  197. self.toolbarController.listView = self.listView
  198. self.toolbarController.mainViewController = self
  199. self.leftSideViewController.mainViewController = self
  200. self.newPDFSplitView.delegate = self
  201. }
  202. override func viewDidAppear() {
  203. super.viewDidAppear()
  204. //春季活动
  205. if ((KMAdvertisementManager.manager.info.popWindowContent) != nil) {
  206. if KMAdvertisementManager.manager.info.popWindowContent!.content!.count > 0 {
  207. let info = KMAdvertisementManager.manager.info.popWindowContent!.content?.first
  208. if KMAdvertisementManager.checkAdvertisementValid(info!) {
  209. self.loadRecommondPopWindow()
  210. }
  211. }
  212. }
  213. //刷新前一页后一页按钮
  214. self.updateNextAndPreViousButtonState()
  215. KMLightMemberManager.manager.canShowAdvancedView = false
  216. // Task { @MainActor in
  217. // await KMLightMemberManager.manager.canUseAdvanced(needNetworking: true)
  218. // }
  219. // self.addEventMonitor()
  220. self.view.window?.makeFirstResponder(self.listView)
  221. // 更新属性页面的信息
  222. NotificationCenter.default.post(name: KMInfoWindowC.windowDidBecomeMainNotification, object: self.myDocument)
  223. self.interfaceThemeDidChanged(self.view.window?.appearance?.name ?? (NSApp.appearance?.name ?? .aqua))
  224. if (self.document == nil) {
  225. return
  226. }
  227. if (self.document == nil || self.document!.isLocked == false) {
  228. self.loadFunctionGuide()
  229. }
  230. if (self.document?.isLocked == false) {
  231. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  232. self.showConvertNotesProgress()
  233. }
  234. return
  235. }
  236. if (self.view.window == nil) {
  237. return
  238. }
  239. if (self.model.password != nil) {
  240. if self.listView.document.unlock(withPassword: self.model.password) {
  241. self.model.isSaveKeyChain = false
  242. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  243. self.showConvertNotesProgress()
  244. }
  245. return
  246. }
  247. }
  248. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
  249. if self.passwordWindow == nil && self.view.window != nil && self.tabViewIsDragging() == false {
  250. self.passwordWindow = KMPasswordInputWindow.openWindow(window: self.view.window!, url: self.document!.documentURL) { [unowned self] result , password in
  251. self.passwordWindow = nil
  252. if (result == .cancel) {
  253. // self.browserWindowController?.browser?.closeTab()
  254. (self.myDocument as? KMMainDocument)?.browser.closeTab()
  255. return
  256. }
  257. self.model.isSaveKeyChain = true
  258. self.listView.document = self.document
  259. self.document?.unlock(withPassword: password)
  260. }
  261. } else {
  262. self.passwordWindow = nil
  263. if self.model.needConvertNotes && self.tabViewIsDragging() == false {
  264. self.showConvertNotesProgress()
  265. }
  266. }
  267. }
  268. }
  269. override func viewWillDisappear() {
  270. super.viewWillDisappear()
  271. self.removeEventMonitor()
  272. }
  273. override func viewWillLayout() {
  274. super.viewWillLayout()
  275. if (KMTools.isFullScreen(self.view.window ?? NSWindow())) { // 全屏
  276. self.exitFullButton.isHidden = false
  277. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundFullScreenColor
  278. } else {
  279. self.exitFullButton.isHidden = true
  280. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
  281. }
  282. if let guideWC = self.guideInfoWindowController{
  283. var rect = self.view.window!.frame
  284. rect.size.height -= 20
  285. guideWC.window?.setFrame(rect, display: false)
  286. guideWC.window?.minSize = rect.size
  287. guideWC.window?.maxSize = rect.size
  288. guideWC.show()
  289. }
  290. }
  291. override func viewDidLoad() {
  292. super.viewDidLoad()
  293. mwcFlags.settingUpWindow = 1
  294. toolbarController.delegate = self
  295. //TODO: 先让项目运行,看后面怎么调整这段逻辑,目前最外层是 KMBrowserWindowController
  296. toolbarBox.contentView = toolbarController.view
  297. if (UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) != nil) {
  298. UserDefaults.standard.set(256, forKey: CPDFOfficeLeftSidePaneWidthKey)
  299. UserDefaults.standard.synchronize()
  300. }
  301. if (UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) != nil) {
  302. UserDefaults.standard.set(256, forKey: CPDFOfficeRightSidePaneWidthKey)
  303. UserDefaults.standard.synchronize()
  304. }
  305. let position = mianSplitView.maxPossiblePositionOfDivider(at: 1)
  306. mianSplitView.setPosition(position, ofDividerAt: 0)
  307. mianSplitView.setPosition(mianSplitView.minPossiblePositionOfDivider(at: 0), ofDividerAt: 0)
  308. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0)
  309. self.locationPageView.wantsLayer = true;
  310. self.locationPageView.layer?.backgroundColor = NSColor(red: 189.0/255.0, green: 223.0/255.0, blue: 253.0/255.0, alpha: 1).cgColor
  311. self.tipLabel.stringValue = NSLocalizedString("Please use the scroll bar, thumbnail tool to locate the target page, click or box the area to select the target range.", comment: "")
  312. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  313. if (self.listView.document != nil) {
  314. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  315. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  316. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  317. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  318. if (pageScale != nil) {
  319. self.listView.scaleFactor = CGFloat(pageScale!)
  320. }
  321. self.listView.go(toPageIndex: pageNumber!, animated: false)
  322. }
  323. } else {
  324. self._goToFirstPageForFristAppear()
  325. }
  326. }
  327. } else {
  328. self._goToFirstPageForFristAppear()
  329. }
  330. //阅读页面
  331. readModelView.delegate = self
  332. pageNumberDisplayView.delegate = self
  333. tipCurrentPageBox.moveCallback = { [unowned self] mouseEntered, mouseBox in
  334. if !isReadMode {
  335. if mouseEntered {
  336. self.pageNumberDisplayView.hover = true
  337. } else {
  338. self.pageNumberDisplayView.hover = false
  339. }
  340. }
  341. }
  342. NotificationCenter.default.addObserver(self, selector: #selector(rename(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerRename"), object: nil)
  343. NotificationCenter.default.addObserver(self, selector: #selector(closeTab(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerCloseTabs"), object: nil)
  344. NotificationCenter.default.addObserver(self, selector: #selector(showInFinder(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerShowInFinder"), object: nil)
  345. NotificationCenter.default.addObserver(self, selector: #selector(preferenceDidChangeNotification), name: KMPreferenceManager.didChangeNotification, object: nil)
  346. NotificationCenter.default.addObserver(self, selector: #selector(documentDidUnlockNotification), name: Notification.Name("CPDFDocumentDidUnlockNotification"), object: nil)
  347. NotificationCenter.default.addObserver(self, selector: #selector(annotationsAttributeHasChange), name: NSNotification.Name.CPDFListViewAnnotationsAttributeHasChange, object:nil)
  348. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminateNotification), name: NSApplication.willTerminateNotification, object: nil)
  349. NotificationCenter.default.addObserver(self, selector: #selector(KMPDFViewCurrentPageDidChangedNotification), name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: nil)
  350. NotificationCenter.default.addObserver(self, selector: #selector(CPDFDocumentPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "CPDFDocumentPageCountChangedNotification"), object: nil)
  351. NotificationCenter.default.addObserver(self, selector: #selector(CEditPDFToolModeChangeStateUnkownNotification), name: Notification.Name.init("CEditPDFToolModeChangeStateUnkown"), object: nil)
  352. NotificationCenter.default.addObserver(self, selector: #selector(handlePageChangedNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.listView)
  353. NotificationCenter.default.addObserver(self, selector: #selector(handleDisplayBoxChangedNotification), name: NSNotification.Name.CPDFViewDisplayBoxChanged, object: self.listView)
  354. // 互动模式
  355. NotificationCenter.default.addObserver(self, selector: #selector(willEnterInteractionModeNotification), name: NSWindow.willEnterInteractionModeNotification, object: nil)
  356. NotificationCenter.default.addObserver(self, selector: #selector(didEnterInteractionModeNotification), name: NSWindow.didEnterInteractionModeNotification, object: nil)
  357. NotificationCenter.default.addObserver(self, selector: #selector(willShowFullScreenNotification), name: NSWindow.willShowFullScreenNotification, object: nil)
  358. NotificationCenter.default.addObserver(self, selector: #selector(didShowFullScreenNotification), name: NSWindow.didShowFullScreenNotification, object: nil)
  359. NotificationCenter.default.addObserver(self, selector: #selector(didAddContentViewNotification), name: NSWindow.didAddContentViewNotification, object: nil)
  360. NotificationCenter.default.addObserver(self, selector: #selector(addAutoSaveEvent), name: AutoSaveManager.kTimeValueChangedNotificationName, object: nil)
  361. Task {
  362. self.addAutoSaveEvent()
  363. }
  364. self.toolbarController.selectItem(KMDocumentAnnotationToolbarItemIdentifier)
  365. self.closeRightPane()
  366. self.addKeyEventMonitor()
  367. self.addAdsBannerView()
  368. //检测OCR包是否需要更新
  369. #if VERSION_DMG
  370. // KMResourceDownloadManager.manager.checkDocumentAIVersion()
  371. #endif
  372. // Open snapshots?
  373. var snapshotSetups: NSArray?
  374. // if (hasWindowSetup)
  375. // snapshotSetups = [savedNormalSetup objectForKey:SNAPSHOTS_KEY];
  376. // else if ([sud boolForKey:SKRememberSnapshotsKey])
  377. if KMPreferenceManager.shared.rememberSnapshot {
  378. // snapshotSetups = [[SKBookmarkController sharedBookmarkController] snapshotsForRecentDocumentAtURL:[(NSDocument *)[self document] fileURL]];
  379. if let fileUrl = (self.myDocument as? KMMainDocument)?.fileURL {
  380. snapshotSetups = SKBookmarkController.shared().snapshotsForRecentDocument(at: fileUrl) as NSArray?
  381. }
  382. }
  383. if let cnt = snapshotSetups?.count, cnt > 0 {
  384. if let data = self.listView?.document?.isLocked, data {
  385. self.savedNormalSetup.setObject(snapshotSetups as Any, forKey: "snapshots" as NSCopying)
  386. } else {
  387. self.showSnapshots(setups: snapshotSetups)
  388. }
  389. }
  390. let readModel = UserDefaults.standard.bool(forKey: "kKMPDFViewIsReadMode")
  391. if readModel == true {
  392. self.openReadModel()
  393. }
  394. let hasWindowSetup = savedNormalSetup.count > 0
  395. if UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey) != nil {
  396. let pdfSettings: NSDictionary = hasWindowSetup ? savedNormalSetup : UserDefaults.standard.dictionary(forKey: KMDefaultPDFDisplaySettingsKey)! as NSDictionary
  397. self.applyPDFSettings(pdfSettings)
  398. } else {
  399. self.applyPDFSettings(savedNormalSetup)
  400. }
  401. }
  402. //MARK: - PDFListView
  403. func initPDFLeftViewVC() {
  404. var frame = self.leftView.frame
  405. frame.size.width += 44
  406. self.leftView.frame = frame
  407. leftSideViewController.isFirst = true
  408. leftSideViewController.listView = self.listView ?? CPDFListView()
  409. leftSideViewController.view.frame = CGRect(x: 0, y:0 , width: self.leftView.frame.size.width, height: self.leftView.frame.size.height)
  410. leftSideViewController.view.autoresizingMask = [.height,.width]
  411. leftSideViewController.delegate = self
  412. self.leftView.addSubview(leftSideViewController.view)
  413. }
  414. func initRightSideView() {
  415. self.rightSideViewController = KMRightSideViewController.init()
  416. self.rightSideViewController.view.frame = CGRect(x: 0, y: 0, width: self.rightView.frame.width, height: self.rightView.frame.size.height)
  417. self.rightSideViewController.view.autoresizingMask = [.height,.width]
  418. self.rightSideViewController.listView = self.listView
  419. // self.rightSideViewController.view.isHidden = true
  420. self.rightSideViewController.isHidden = true
  421. self.rightSideViewController.delegate = self
  422. self.rightView.addSubview(self.rightSideViewController.view)
  423. self.rightSideViewController.propertyDidChange = { [weak self] model in
  424. if let anno = model as? CSelfSignAnnotation {
  425. self?.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: nil)
  426. }
  427. }
  428. }
  429. func addAdsBannerView() {
  430. #if VERSION_FREE
  431. if !IAPProductsManager.default().isAvailableAllFunction(){
  432. guard let document = self.listView.document else {
  433. return
  434. }
  435. if !document.isLocked {
  436. KMAdsManager.defaultManager.beginSheetModalForView(self.readContentView, directions: .down, adPosY: 30, animated: false) { pageIndex in
  437. }
  438. }
  439. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "KMIAPProductPurchasedNotification"), object: nil)
  440. NotificationCenter.default.addObserver(self, selector: #selector(purchaseStateUpdateNoti), name: NSNotification.Name(rawValue: "kDeviceActivateNotification"), object: nil)
  441. }
  442. #endif
  443. //加载底部banner
  444. // - (void)loadingAdsManager {
  445. // #if VERSION_FREE
  446. // if(![self.pdfDocument isLocked]) {
  447. // if (![IAPProductsManager defaultManager].isAvailableAllFunction) {
  448. // [[KMAdsManager defaultManager] beginSheetModalForView:self.pdfView
  449. // directions:KMADViewDirectionsDown
  450. // animated:NO
  451. // completionHandler:nil];
  452. // }
  453. // [[NSNotificationCenter defaultCenter] addObserverForName:KMIAPProductPurchasedNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
  454. // if ([IAPProductsManager defaultManager].isAvailableAllFunction) {
  455. // [[KMAdsManager defaultManager] dismissSheetModalForView:self.pdfView];
  456. // }
  457. // }];
  458. // [[NSNotificationCenter defaultCenter] addObserverForName:kDeviceActivateStatusChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){
  459. // if ([IAPProductsManager defaultManager].isAvailableAllFunction) {
  460. // [[KMAdsManager defaultManager] dismissSheetModalForView:self.pdfView];
  461. // }
  462. // }];
  463. // }
  464. // #endif
  465. // }
  466. }
  467. // MARK: Private Methods
  468. internal func removeNotifications() {
  469. NotificationCenter.default.removeObserver(self)
  470. self.leftSideViewController.clearAnnotationFilterData()
  471. self.leftSideViewController.clearNotification()
  472. }
  473. func checkShouldAutoOpenLeftVC() {
  474. if KMPreference.shared.showLeftSideBar == false {
  475. return
  476. }
  477. if self.model.leftPanelOpen {
  478. return
  479. }
  480. Task { @MainActor in
  481. self.leftSideViewController.showThumbnail()
  482. self.toolbarController.findItem(KMLeftControlToolbarItemIdentifier)?.isSelected = true
  483. }
  484. }
  485. func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
  486. mianSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
  487. mianSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1) - mianSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
  488. self.model.lastLeftPanWidth = leftSideWidth
  489. self.model.lastRightPanWidth = rightSideWidth
  490. }
  491. internal var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
  492. internal func removeAllAnnotations() {
  493. let alert = NSAlert()
  494. alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  495. alert.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  496. alert.addButton(withTitle: NSLocalizedString("No", comment:""))
  497. if (alert.runModal() != .alertFirstButtonReturn) {
  498. return
  499. }
  500. DispatchQueue.main.async {
  501. self.removeAllAnnotationsStore.store(t: self.listView)
  502. }
  503. }
  504. // MARK: Set Methods
  505. var setDocument: CPDFDocument? {
  506. get {
  507. return document
  508. }
  509. set {
  510. if document != newValue {
  511. document = newValue
  512. }
  513. listView.document = document
  514. listView.document.delegate = self
  515. self.listView.layoutDocumentView()
  516. self.leftSideViewController.refreshUIForDocumentChanged()
  517. }
  518. }
  519. var setPageNumber: UInt {
  520. get {
  521. return pageNumber!
  522. }
  523. set {
  524. let pageCount = listView.document.pageCount
  525. var value = newValue
  526. if value > pageCount {
  527. value = pageCount
  528. }
  529. if value > 0 && listView.currentPage().pageIndex() != value-1 {
  530. listView.go(to: listView.document.page(at: value-1))
  531. }
  532. if pageNumber != value {
  533. pageNumber = value
  534. }
  535. }
  536. }
  537. // MARK: - 标记密文
  538. func enterRedact() {
  539. if !IAPProductsManager.default().isAvailableAllFunction(){
  540. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  541. return
  542. }
  543. if self.listView.document.allowsPrinting == false || self.listView.document.allowsCopying == false {
  544. Task {
  545. _ = await KMAlertTool.runModel(message: KMLocalizedString("This is a secured document. Editing is not permitted.", nil))
  546. }
  547. return
  548. }
  549. if self.hasEnterRedact() {
  550. self.exitRedact()
  551. return
  552. }
  553. self.leftSideViewController.thumbnailTableView.isEnabled = false
  554. self.leftSideViewController.tocOutlineView.isEnabled = false
  555. self.leftSideViewController.noteOutlineView.isEnabled = false
  556. self.leftSideViewController.findTableView.isEnabled = false
  557. self.leftSideViewController.groupedFindTableView.isEnabled = false
  558. self.leftSideViewController.snapshotTableView.isEnabled = false
  559. let ttsWindowC = KMTTSWindowController.share
  560. if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document.documentURL.path {
  561. if let data = ttsWindowC.window?.isVisible, data {
  562. ttsWindowC.stopSpeaking()
  563. ttsWindowC.close()
  564. }
  565. }
  566. NSColorPanel.shared.showsAlpha = false
  567. redactController = KMPDFRedactViewController(url: self.listView.document!.documentURL, password: self.listView.document.password)
  568. self.addChild(redactController)
  569. self.PDFContendView.addSubview(redactController.view)
  570. redactController.view.frame = self.PDFContendView.bounds
  571. redactController.view.autoresizingMask = [.width, .height]
  572. self.listView.isHidden = true
  573. redactController.scaleFactor = self.listView.scaleFactor
  574. redactController.titleBack = { [weak self] title in
  575. self?.view.window?.title = title
  576. }
  577. redactController.callback = { [weak self] result, currentPageIndex, saveResult, saveUrl in
  578. self?.listView.go(toPageIndex: self!.redactController.redactPdfView.currentPageIndex, animated: false)
  579. if result == false { // 退出
  580. self?.exitRedact()
  581. return
  582. }
  583. let controller = self?._getPDFRedactController()
  584. controller?.redactPdfView.newAddAnnotation.removeAll()
  585. self?.exitRedact()
  586. if saveResult {
  587. let newDocument = CPDFDocument(url: saveUrl)
  588. if let data = newDocument?.isLocked, data {
  589. newDocument?.unlock(withPassword: self?.listView.document.password ?? "")
  590. }
  591. self?.document = newDocument
  592. self?.listView.document = newDocument
  593. self?.listView.layoutDocumentView()
  594. }
  595. }
  596. redactController.setCurrentPageIndex(self.listView.currentPageIndex)
  597. }
  598. func exitRedact() {
  599. self.leftSideViewController.thumbnailTableView.isEnabled = true
  600. self.leftSideViewController.tocOutlineView.isEnabled = true
  601. self.leftSideViewController.noteOutlineView.isEnabled = true
  602. self.leftSideViewController.findTableView.isEnabled = true
  603. self.leftSideViewController.groupedFindTableView.isEnabled = true
  604. self.leftSideViewController.snapshotTableView.isEnabled = true
  605. let controller = self._getPDFRedactController()
  606. if let data = controller {
  607. if data.redactPdfView.newAddAnnotation.count > 0 {
  608. KMAlertTool.runModel(message: "", informative: KMLocalizedString("There are unapplied redactions in this file. Exit will not save redaction.", nil), buttons: [KMLocalizedString("Exit", nil), KMLocalizedString("Cancel", nil)]) { response in
  609. if response == .alertFirstButtonReturn {
  610. data.redactPdfView.newAddAnnotation.removeAll()
  611. self.exitRedact()
  612. }
  613. }
  614. return
  615. }
  616. }
  617. NSColorPanel.shared.showsAlpha = true
  618. self.toolbarController.findItem(KMDocumentRedactToolbarItemIdentifier)?.isSelected = false
  619. // self.toolbarController.toolbarType = .None
  620. // self.listView.toolMode = .moveToolMode
  621. controller?.redactPdfView.resignMonitor()
  622. controller?.view.removeFromSuperview()
  623. controller?.removeFromParent()
  624. self.listView.isHidden = false
  625. // self.listView.layoutDocumentView()
  626. // self.view.window?.makeFirstResponder(self.listView)
  627. self.listView.annotationType = .unkown
  628. }
  629. func hasEnterRedact() -> Bool {
  630. return self._getPDFRedactController() != nil
  631. }
  632. //MARK: - AI
  633. func showAITypeChooseView(aiConfigType: AIConfigType) -> Void {
  634. if (self.document != nil) {
  635. AIChatInfoManager.defaultManager.currentFilePath = (self.document?.documentURL.path)!
  636. } else {
  637. AIChatInfoManager.defaultManager.currentFilePath = ""
  638. }
  639. let windowVC: AINewConfigWindowController = AINewConfigWindowController.currentWC()
  640. windowVC.chooseCurFileHandle = {[unowned self] windowVC in
  641. if AIChatInfoManager.defaultManager.currentFilePath.isEmpty == false {
  642. let documentArray = NSDocumentController.shared.documents
  643. var didFileEdit: Bool = false
  644. var curDoc: KMMainDocument!
  645. for document in documentArray {
  646. if document.fileURL?.path == AIChatInfoManager.defaultManager.currentFilePath {
  647. didFileEdit = document.isDocumentEdited
  648. curDoc = document as! KMMainDocument
  649. break
  650. }
  651. }
  652. if didFileEdit {
  653. let tempFileURL = FileManager.default.temporaryDirectory.appendingPathComponent(AIChatInfoManager.defaultManager.currentFilePath.lastPathComponent)
  654. if FileManager.default.fileExists(atPath: tempFileURL.path) {
  655. do {
  656. try FileManager.default.removeItem(at: tempFileURL)
  657. } catch {
  658. }
  659. }
  660. if curDoc != nil {
  661. curDoc.mainViewController?.SaveTempPDFDocumentToURLPath(tempPath: tempFileURL.path)
  662. }
  663. }
  664. windowVC.window?.becomeMain()
  665. }
  666. }
  667. if windowVC.window?.isVisible == true && windowVC.didSetOriginFrame == true {
  668. } else {
  669. var windowRect = windowVC.window?.frame
  670. windowRect!.origin.x = CGRectGetMaxX(self.view.window!.frame) - (windowRect?.size.width)!
  671. windowRect!.origin.y = CGRectGetMaxY(self.view.window!.frame) - (windowRect?.size.height)! - 64
  672. windowVC.window?.setFrame(windowRect!, display: true)
  673. windowVC.didSetOriginFrame = true
  674. }
  675. windowVC.eventLabel = "AITools_Tbr"
  676. windowVC.showWindow(nil)
  677. if (aiConfigType != .none) {
  678. windowVC.eventLabel = "AITools_Start"
  679. if self.listView.currentSelection?.string()?.isEmpty == false {
  680. windowVC.setCurrentPDFSelection(self.listView.currentSelection.string())
  681. }
  682. windowVC.chooseAIFunctionWithType(aiConfigType)
  683. }
  684. }
  685. @objc func aiTipIconViewShowStateChangeNoti() {
  686. }
  687. //MARK: - 引导
  688. func loadFunctionGuide() -> Void {
  689. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  690. if self.view.window != nil {
  691. self.loadOpenFileFunctionGuide(.openFileNormal)
  692. }
  693. }
  694. }
  695. func loadOpenFileFunctionGuide(_ showType: KMGuideInfoType) -> Void {
  696. if showType == .openFileNormal && KMGuideInfoWindowController.availableShow(.openFileNormal) {
  697. let leftPanelItem:KMToolbarItemView = self.toolbarController.findItem("KMLeftControlToolbarItemIdentifier")!
  698. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  699. guard let guideWC = self.guideInfoWindowController else { return }
  700. guideWC.type = .openFileNormal
  701. guideWC.openPanelRect = (self.view.window?.contentView?.convert(leftPanelItem.frame, from: leftPanelItem.superview)) ?? CGRectZero
  702. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  703. guideWC.normalGuideFinishHandle = { [weak self] windowVC in
  704. let rightPanelItem = self?.toolbarController.findItem(KMRightControlToolbarItemIdentifier)
  705. let digitalPanelItem = self?.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)
  706. windowVC.rightPanelRect = (self!.view.window?.contentView?.convert(rightPanelItem?.frame ?? .zero, from: rightPanelItem?.superview)) ?? .zero
  707. guideWC.digitalBoxRect = (self!.view.window?.contentView?.convert(digitalPanelItem?.frame ?? .zero, from: digitalPanelItem?.superview)) ?? .zero
  708. }
  709. guideWC.finishHandle = { [weak self] windowVC, type in
  710. if type == .windowNewFinish ||
  711. type == . windowDigitalFinish {
  712. self?.checkFirstTrialController()
  713. }
  714. }
  715. guideWC.openFileToggleHandle = { [weak self] windowVC, type in
  716. self?.checkFirstTrialController()
  717. }
  718. var rect = self.view.window!.frame
  719. rect.size.height -= 20
  720. guideWC.window?.setFrame(rect, display: false)
  721. guideWC.window?.minSize = rect.size
  722. guideWC.window?.maxSize = rect.size
  723. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  724. guideWC.show()
  725. } else if showType == .digitalSignGuide && KMGuideInfoWindowController.availableShow(.digitalSignGuide) {
  726. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  727. guard let guideWC = self.guideInfoWindowController else { return }
  728. guideWC.type = .digitalSignGuide
  729. let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
  730. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  731. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  732. guideWC.finishHandle = { [weak self] windowVC, type in
  733. self?.checkFirstTrialController()
  734. }
  735. var rect = self.view.window!.frame
  736. rect.size.height -= 20
  737. guideWC.window?.setFrame(rect, display: false)
  738. guideWC.window?.minSize = rect.size
  739. guideWC.window?.maxSize = rect.size
  740. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  741. guideWC.show()
  742. } else if showType == .pdfCompareGuide && KMGuideInfoWindowController.availableShow(.pdfCompareGuide) {
  743. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  744. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  745. guard let guideWC = self.guideInfoWindowController else { return }
  746. guideWC.type = .pdfCompareGuide
  747. let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
  748. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  749. let compareItem:KMToolbarItemView = self.toolbarController.findItem(KMToolbarComparisonItemIdentifier)!
  750. guideWC.compareItemRect = (self.view.window?.contentView?.convert(compareItem.frame, from: compareItem.superview))!
  751. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  752. var rect = self.view.window!.frame
  753. rect.size.height -= 20
  754. guideWC.window?.setFrame(rect, display: false)
  755. guideWC.window?.minSize = rect.size
  756. guideWC.window?.maxSize = rect.size
  757. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  758. guideWC.show()
  759. }
  760. } else if showType == .convertGuide && KMGuideInfoWindowController.availableShow(.convertGuide) {
  761. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
  762. self.guideInfoWindowController = KMGuideInfoWindowController.currentWC()
  763. guard let guideWC = self.guideInfoWindowController else { return }
  764. guideWC.type = .convertGuide
  765. let digitalPanelItem:KMToolbarItemView = self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)!
  766. guideWC.digitalBoxRect = (self.view.window?.contentView?.convert(digitalPanelItem.frame, from: digitalPanelItem.superview))!
  767. guideWC.purchaseHandle = { [weak self] windowVC in
  768. #if VERSION_DMG
  769. if IAPProductsManager.default().isAvailableAllFunction() {
  770. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  771. //Convert:
  772. self?.showAllConvertWindow(convertT: .Word)
  773. } else {
  774. let limitWC = KMPurchaseLimitWindowController.currentLimitWC()
  775. limitWC.continueBlock = { windowController in
  776. }
  777. limitWC.window?.center()
  778. limitWC.showWindow(nil)
  779. }
  780. } else {
  781. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  782. }
  783. #else
  784. if IAPProductsManager.default().isAvailableAllFunction() {
  785. if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
  786. //Convert:
  787. } else {
  788. var vc = KMToolCompareWindowController(toolType: .Convert, selectNum: 1)
  789. vc.showWindow(nil)
  790. }
  791. } else {
  792. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  793. }
  794. #endif
  795. }
  796. guideWC.window?.collectionBehavior = [.canJoinAllSpaces]
  797. var rect = self.view.window!.frame
  798. rect.size.height -= 20
  799. guideWC.window?.setFrame(rect, display: false)
  800. guideWC.window?.minSize = rect.size
  801. guideWC.window?.maxSize = rect.size
  802. self.view.window?.addChildWindow(guideWC.window!, ordered: .above)
  803. guideWC.show()
  804. }
  805. } else {
  806. }
  807. }
  808. func checkFirstTrialController() -> Void {
  809. #if VERSION_DMG
  810. //打开文档后引导相关
  811. if VerificationManager.default().status == .none {
  812. let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
  813. let lastVersion = UserDefaults.standard.object(forKey: "SKLastTrialVersionMainDocumentLaunchedKey") as? String ?? ""
  814. if lastVersion.isEmpty || lastVersion != appVersion {
  815. UserDefaults.standard.setValue(appVersion, forKey: "SKLastTrialVersionMainDocumentLaunchedKey")
  816. UserDefaults.standard.synchronize()
  817. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  818. }
  819. }
  820. #endif
  821. }
  822. // MARK: - 页面编辑
  823. open func enterPageEdit(_ pages: [Int] = []) {
  824. if let doc = self.listView?.document {
  825. if doc.allowsCopying == false || doc.allowsPrinting == false {
  826. KMBaseWindowController.checkPassword(url: doc.documentURL, type: .owner) { result, pwd in
  827. if result && pwd.isEmpty == false {
  828. self.listView?.document?.unlock(withPassword: pwd)
  829. Task { @MainActor in
  830. self.enterPageEdit(pages)
  831. }
  832. } else {
  833. self.exitPageEdit()
  834. }
  835. }
  836. return
  837. }
  838. }
  839. //选中page
  840. var tPages = pages
  841. if tPages.count == 0 {
  842. if self.leftSideViewController.type.methodType == .Thumbnail {
  843. tPages = self.leftSideViewController.thumb_fetchSelectedRows() ?? [self.listView.currentPageIndex]
  844. }
  845. }
  846. if (hasEnterPageEdit()) {
  847. exitPageEdit()
  848. return
  849. }
  850. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  851. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  852. for (key, value) in toolBarView.toolbarItems {
  853. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  854. (value as! KMToolbarItemView).unEnabled = true
  855. }
  856. }
  857. }
  858. let controller = KMPDFEditViewController(self.listView.document)
  859. controller.selectedPages = tPages
  860. controller.listView = self.listView
  861. self.addChild(controller)
  862. self.PDFContendView.addSubview(controller.view)
  863. controller.view.frame = self.PDFContendView.bounds
  864. controller.view.autoresizingMask = [.width,.height]
  865. self.listView.isHidden = true
  866. controller.itemClick = { [weak self] index, params in
  867. if (index == 1) { /// 双击退出
  868. self?.enterEditMode(self!.leftSideViewController, [])
  869. DispatchQueue.main.async {
  870. let pageIndex: Int = params.first as! Int
  871. self?.listView.go(toPageIndex: pageIndex, animated: true)
  872. }
  873. } else if (index == 2) { // 打印
  874. self?.showPrintWindow(pageRange: KMPrintPageRange(type: .custom, selectPages: params.first as! [Int]))
  875. }
  876. }
  877. controller.documentEditedCallback = { [weak self] params in
  878. self?.recordIsPDFDocumentEdited()
  879. }
  880. controller.selectionDidChange = { selectedIndexs in
  881. var indexSet = IndexSet()
  882. for indexPath in selectedIndexs {
  883. indexSet.insert(indexPath.item)
  884. }
  885. if indexSet.count != 0 {
  886. // self?.leftSideViewController.thumbnailViewController.selectPages(indexs: indexSet, needScroll: true)
  887. // self?.listView.go(toPageIndex: indexSet.first!, animated: false)
  888. }
  889. }
  890. }
  891. open func exitPageEdit() {
  892. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  893. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  894. for (key, value) in toolBarView.toolbarItems {
  895. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  896. (value as! KMToolbarItemView).unEnabled = false
  897. }
  898. }
  899. }
  900. self.toolbarController.findItem(KMDocumentPageToolbarItemIdentifier)?.isSelected = false
  901. let editController = getPDFEditController()
  902. if (editController == nil) {
  903. return
  904. }
  905. self.listView.annotationType = .highlight
  906. editController?.view.removeFromSuperview()
  907. editController?.removeFromParent()
  908. self.listView.isHidden = false
  909. self.listView.layoutDocumentView()
  910. self.view.window?.makeFirstResponder(self.listView)
  911. self.listView.annotationType = .unkown
  912. self.listView.go(toPageIndex: editController!.listViewCurrentIndex, animated: false)
  913. if let data = editController?.isEdited, data {
  914. self.leftSideViewController.reloadThumbnailDataIfNeed()
  915. self.leftSideViewController.note_reloadDataIfNeed()
  916. self.leftSideViewController.refreshUIOfOutlineIfNeed()
  917. self.leftSideViewController.refreshUIOfSeachListIfNeed()
  918. }
  919. }
  920. open func hasEnterPageEdit() -> Bool {
  921. return self.getPDFEditController() != nil
  922. }
  923. // MARK: - Edit PDF
  924. func enterEditPDF() {
  925. self.listView.updateActiveAnnotations([])
  926. self.listView.setNeedsDisplayForVisiblePages()
  927. self.listView.commitEditFormText()
  928. self.listView.annotationType = .editTextImage
  929. }
  930. // MARK: - 数字签名
  931. func hasShowDigitalSign() -> Bool {
  932. return self.digitalSignController?.view.superview != nil
  933. }
  934. func canEnterDigitalSign() -> Bool {
  935. guard let doc = self.listView?.document else {
  936. return false
  937. }
  938. return doc.allowsPrinting && doc.allowsCopying
  939. }
  940. func enterDigitalSign() {
  941. self.listView.toolMode = .textToolMode
  942. if self.hasShowDigitalSign() {
  943. self.exitDigitalSign()
  944. } else {
  945. if self.needSaveDocument() {
  946. self.saveDocumentWithProgressAlert { [unowned self] params in
  947. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  948. }
  949. return
  950. }
  951. self.showDigitalSignWindow(withFilePathURL: self.listView.document.documentURL)
  952. }
  953. }
  954. func exitDigitalSign() {
  955. self.digitalSignController?.view.removeFromSuperview()
  956. // self.digitalSignController = nil
  957. self.toolbarController.findItem(KMDocumentDigitalSignToolbarItemIdentifier)?.isSelected = false
  958. }
  959. func showDigitalSignWindow(withFilePathURL fileURL: URL) {
  960. if !IAPProductsManager.default().isAvailableAllFunction(){
  961. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  962. return
  963. }
  964. if hasShowDigitalSign() {
  965. self.exitDigitalSign()
  966. }
  967. var currentPageIndex = listView.document?.index(for: listView.currentPage()) ?? 0
  968. var password: String = ""
  969. self.toolbarController.toolbarType = .None
  970. if digitalSignController == nil {
  971. password = listView.document?.password ?? ""
  972. digitalSignController = KMPDFDigitalSignViewController()
  973. }
  974. digitalSignController?.currentPageIndex = Int(currentPageIndex)
  975. digitalSignController?.url = listView.document.documentURL
  976. digitalSignController?.password = password
  977. digitalSignController?.scaleFactor = listView.scaleFactor
  978. digitalSignController?.titleChangeBlock = { title, index in
  979. currentPageIndex = UInt(index)
  980. }
  981. digitalSignController?.buttonActionBlock = { [weak self] type, isChanged in
  982. if type == .cancel {
  983. if let page = self?.listView?.document?.page(at: currentPageIndex) {
  984. self?.listView.go(to: page)
  985. }
  986. self?.exitDigitalSign()
  987. }
  988. }
  989. if let digitalSignView = digitalSignController?.view, let splitViewSuperview = mianSplitView.superview {
  990. digitalSignView.frame = splitViewSuperview.bounds
  991. digitalSignView.autoresizingMask = [.width, .height]
  992. splitViewSuperview.addSubview(digitalSignView)
  993. digitalSignController?.setCurrentPageIndex(Int(currentPageIndex))
  994. }
  995. }
  996. // MARK: - Toolbar
  997. func toolbarItemClickForExitMode(_ toolbarItem: KMToolbarItemView) {
  998. if(toolbarItem.itemIdentifier != KMDocumentPageToolbarItemIdentifier) {
  999. if (hasEnterPageEdit()) {
  1000. self.exitPageEdit()
  1001. }
  1002. }
  1003. if toolbarItem.itemIdentifier != KMDocumentRedactToolbarItemIdentifier {
  1004. if self.hasEnterRedact() {
  1005. self.exitRedact()
  1006. }
  1007. }
  1008. if toolbarItem.itemIdentifier != KMDocumentDigitalSignToolbarItemIdentifier {
  1009. if self.hasShowDigitalSign() {
  1010. self.exitDigitalSign()
  1011. }
  1012. }
  1013. }
  1014. // MARK: - Private Methods
  1015. private func getPDFEditController() -> KMPDFEditViewController? {
  1016. var editController: KMPDFEditViewController?
  1017. for controller in self.children {
  1018. if (controller.isKind(of: KMPDFEditViewController.self)) {
  1019. editController = (controller as! KMPDFEditViewController)
  1020. break
  1021. }
  1022. }
  1023. return editController
  1024. }
  1025. private func _getPDFRedactController() -> KMPDFRedactViewController? {
  1026. var controller: KMPDFRedactViewController?
  1027. for childC in self.children {
  1028. if (childC.isKind(of: KMPDFRedactViewController.self)) {
  1029. controller = (childC as! KMPDFRedactViewController)
  1030. break
  1031. }
  1032. }
  1033. return controller
  1034. }
  1035. private func addBackgroundMaskView() {
  1036. self.removeBackgroundMaskView()
  1037. if let superview = self.mianSplitView.superview {
  1038. let view = NSView()
  1039. superview.addSubview(view)
  1040. view.frame = superview.bounds
  1041. view.autoresizingMask = [.width, .height]
  1042. view.wantsLayer = true
  1043. view.layer?.backgroundColor = .white
  1044. self.background_mask = view
  1045. }
  1046. }
  1047. private func removeBackgroundMaskView() {
  1048. self.background_mask?.removeFromSuperview()
  1049. self.background_mask = nil
  1050. }
  1051. private func _goToFirstPageForFristAppear() {
  1052. DispatchQueue.main.asyncAfter(wallDeadline: .now()+0.1) {
  1053. self.listView.go(toPageIndex: 0, animated: false)
  1054. }
  1055. }
  1056. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  1057. let url = URL(fileURLWithPath: filePath)
  1058. guard let document = PDFDocument(url: url) else {
  1059. return false
  1060. }
  1061. let pageCount = document.pageCount
  1062. return pageCount > 30
  1063. }
  1064. // MARK: - Redact 【标记密文】
  1065. func exeRedactConfirm(_ type: KMRedactConfirmType, callback: @escaping () -> ()?) {
  1066. let windowController = KMRedactConfirmWindowController(type)
  1067. self.currentWindowController = windowController
  1068. self.view.window?.beginSheet(windowController.window!)
  1069. windowController.itemClick = { [weak self] index in
  1070. if (index == 2) { /// 取消
  1071. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1072. self?.currentWindowController = nil
  1073. callback()
  1074. return
  1075. }
  1076. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  1077. self?.currentWindowController = nil
  1078. let panel = NSSavePanel()
  1079. panel.nameFieldStringValue = "[新文件]"+(self?.listView.document.documentURL.lastPathComponent)!
  1080. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  1081. button.state = .on
  1082. panel.accessoryView = button
  1083. panel.isExtensionHidden = true
  1084. panel.beginSheetModal(for: (self?.view.window!)!) { response in
  1085. if response != .OK {
  1086. callback()
  1087. return
  1088. }
  1089. if (type == .redactOne) {
  1090. let anno = self!.listView.activeAnnotation
  1091. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1092. callback()
  1093. return
  1094. }
  1095. (anno as! CPDFRedactAnnotation).applyRedaction()
  1096. } else if (type == .redactAll) {
  1097. self?.listView.document.applyRedactions()
  1098. } else if (type == .eraserOne) {
  1099. let anno = self!.listView.activeAnnotation
  1100. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  1101. callback()
  1102. return
  1103. }
  1104. anno?.page.erasureRedact(from: anno!.bounds)
  1105. } else if (type == .eraserAll) {
  1106. KMRedactTools.eraserDocument((self?.listView.document)!) { result, errorAnno in
  1107. if (result == false) {
  1108. callback()
  1109. return
  1110. }
  1111. }
  1112. }
  1113. self!.listView.document.write(to: panel.url)
  1114. if (button.state == .on) {
  1115. NSDocumentController.shared.openDocument(withContentsOf: panel.url!, display: true) { document, alreadyOpen, error in
  1116. }
  1117. } else {
  1118. NSWorkspace.shared.activateFileViewerSelecting([panel.url!])
  1119. }
  1120. callback()
  1121. }
  1122. }
  1123. }
  1124. // MARK: - Secure 【安全】
  1125. public func showSecureLimitTip() {
  1126. self.hiddenSecureLimitTip()
  1127. if self.secureAlertView == nil {
  1128. self.secureAlertView = KMSecureAlertView()
  1129. self.secureAlertView?.show(in: self.listView)
  1130. self.secureAlertView?.closeAction = { [unowned self] view in
  1131. self.hiddenSecureLimitTip()
  1132. self.removeFromAlertView()
  1133. self.showFormAlertView()
  1134. }
  1135. self.secureAlertView?.passwordAction = { [unowned self] view in
  1136. self.removeOwnerPassword()
  1137. self.removeFromAlertView()
  1138. self.showFormAlertView()
  1139. }
  1140. }
  1141. }
  1142. func removeOwnerPassword() {
  1143. guard let doc = self.listView?.document else {
  1144. NSSound.beep()
  1145. return
  1146. }
  1147. if doc.allowsCopying && doc.allowsPrinting {
  1148. NSSound.beep()
  1149. return
  1150. }
  1151. _ = KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: doc.documentURL) { [weak self] result, password in
  1152. if result == .cancel { /// 关闭
  1153. return
  1154. }
  1155. /// 解密成功
  1156. self?.hiddenSecureLimitTip()
  1157. self?.model.isSaveKeyChain = false
  1158. self?.listView.document.unlock(withPassword: password)
  1159. }
  1160. }
  1161. public func hiddenSecureLimitTip() {
  1162. self.secureAlertView?.removeFromSuperview()
  1163. self.secureAlertView = nil
  1164. }
  1165. //MARK: - Form
  1166. func showFormAlertView() {
  1167. if (formAlertView == nil) {
  1168. formAlertView = KMFormAlertView()
  1169. formAlertView?.isCloseSecureView = self.secureAlertView != nil ? false : true
  1170. formAlertView?.showInView(self.listView)
  1171. } else {
  1172. self.removeFromAlertView()
  1173. }
  1174. }
  1175. func removeFromAlertView() {
  1176. formAlertView?.removeFromSuperview()
  1177. formAlertView = nil
  1178. }
  1179. override func mouseMoved(with event: NSEvent) {
  1180. self.view.window?.mouseMoved(with: event)
  1181. }
  1182. func savePageNumberIfNeed() {
  1183. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1184. let scaleFactor = self.listView?.scaleFactor ?? 0
  1185. if scaleFactor <= 0 {
  1186. return
  1187. }
  1188. if self.listView.document != nil {
  1189. KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  1190. KMPreferenceManager.shared.setPageScale(Float(self.listView.scaleFactor), forKey: self.listView.document.documentURL.path)
  1191. }
  1192. }
  1193. }
  1194. // MARK: - 显示合并窗口
  1195. public func showMergeWindow(url: URL? = nil, _ password: String?) {
  1196. DispatchQueue.main.async {
  1197. var documentURL = url
  1198. if documentURL == nil {
  1199. documentURL = self.listView.document.documentURL
  1200. }
  1201. guard let _url = documentURL else { return }
  1202. guard let document = PDFDocument(url: _url) else { return }
  1203. self.mergeWindowController = KMMergeWindowController(document: document, password: password ?? "")
  1204. self.mergeWindowController!.oriDucumentUrl = self.listView.document.documentURL
  1205. self.mergeWindowController!.pageIndex = self.listView.currentPageIndex
  1206. self.mergeWindowController!.cancelAction = { [unowned self] controller in
  1207. self.view.window?.endSheet(mergeWindowController!.window!)
  1208. }
  1209. self.mergeWindowController!.mergeAction = { [unowned self] controller, filePath in
  1210. self.view.window?.endSheet(mergeWindowController!.window!)
  1211. }
  1212. self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  1213. self.view.window?.beginSheet(self.mergeWindowController!.window!)
  1214. }
  1215. }
  1216. // MARK: - 显示加密弹窗
  1217. public func showSecureWindow(_ url: URL) {
  1218. self.securityWindowController = KMSecurityWindowController(windowNibName: "KMSecurityWindowController")
  1219. guard let securityWindowController = securityWindowController else { return }
  1220. securityWindowController.documentURL = self.listView.document.documentURL
  1221. securityWindowController.batchAction = { [unowned self] controller, files in
  1222. self.view.window?.endSheet((securityWindowController.window)!)
  1223. self.toolbarController.cancelSelected(KMToolbarToolCompressItemIdentifier)
  1224. let batchWindowController = KMBatchOperateWindowController.sharedWindowController
  1225. let batchOperateFile = KMBatchOperateFile(filePath: self.document?.documentURL.path ?? "", type: .AddPassword)
  1226. batchWindowController.switchToOperateType(.AddPassword, files: [batchOperateFile])
  1227. batchWindowController.window?.makeKeyAndOrderFront("")
  1228. }
  1229. securityWindowController.doneAction = { [unowned self] controller, options, attribute in
  1230. let openPanel = NSOpenPanel()
  1231. openPanel.canChooseFiles = false
  1232. openPanel.canChooseDirectories = true
  1233. openPanel.canCreateDirectories = true
  1234. openPanel.beginSheetModal(for: NSWindow.currentWindow()) { (result) in
  1235. if result == NSApplication.ModalResponse.OK {
  1236. for fileURL in openPanel.urls {
  1237. let document = CPDFDocument(url: self.document?.documentURL)
  1238. if document != nil {
  1239. document!.setDocumentAttributes(attribute)
  1240. let path = fileURL.path.stringByAppendingPathComponent(url.deletingPathExtension().lastPathComponent) + "_SetPassword" + "." + url.pathExtension
  1241. let success = document!.write(to: NSURL(fileURLWithPath: path) as URL, withOptions: options)
  1242. if success {
  1243. self.view.window?.endSheet((securityWindowController.window)!)
  1244. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: path)])
  1245. }
  1246. }
  1247. }
  1248. }
  1249. }
  1250. }
  1251. securityWindowController.cancelAction = { [unowned self] controller in
  1252. self.view.window?.endSheet((securityWindowController.window)!)
  1253. }
  1254. NSWindow.currentWindow().beginSheet(securityWindowController.window!)
  1255. }
  1256. // MARK: - 保存文档
  1257. internal func needSaveDocument() -> Bool {
  1258. if (self.isPDFDocumentEdited) {
  1259. return self.isPDFDocumentEdited
  1260. }
  1261. if (self.needSave) {
  1262. return self.needSave
  1263. }
  1264. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1265. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  1266. return false
  1267. }
  1268. return true
  1269. }
  1270. internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
  1271. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1272. if (overlook) {
  1273. document?.save(nil)
  1274. return
  1275. }
  1276. if (self.isPDFDocumentEdited) {
  1277. self.clearIsPDFDocumentEdited()
  1278. self.needSave = false
  1279. document?.save(nil)
  1280. return
  1281. }
  1282. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  1283. return
  1284. }
  1285. document?.save(nil)
  1286. }
  1287. internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
  1288. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  1289. if (overlook) {
  1290. DispatchQueue.main.async {
  1291. document?.save(nil)
  1292. callback()
  1293. }
  1294. return
  1295. }
  1296. if (self.isPDFDocumentEdited) {
  1297. self.clearIsPDFDocumentEdited()
  1298. self.needSave = false
  1299. DispatchQueue.main.async {
  1300. document?.save(nil)
  1301. callback()
  1302. }
  1303. return
  1304. }
  1305. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  1306. callback()
  1307. return
  1308. }
  1309. DispatchQueue.main.async {
  1310. document?.save(nil)
  1311. callback()
  1312. }
  1313. }
  1314. internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
  1315. // 显示进度
  1316. AutoSaveManager.manager.isSaving = true
  1317. self.showProgressWindow(message: NSLocalizedString("Save", comment: "") + "PDF")
  1318. self.progressC?.maxValue = 3.0
  1319. self.progressC?.increment(by: 1.0)
  1320. // 保存文档
  1321. self.asyncSaveDocument { [unowned self] params in
  1322. // 执行进度 [假进度]
  1323. self.progressC?.increment(by: 1.0)
  1324. self.progressC?.increment(by: 1.0)
  1325. // DispatchQueue.main.async {
  1326. DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
  1327. // 隐藏进度
  1328. self.hiddenProgressWindow()
  1329. DispatchQueue.main.asyncAfter(deadline: .now()+1) {
  1330. AutoSaveManager.manager.isSaving = false
  1331. }
  1332. // 回调
  1333. callback()
  1334. }
  1335. }
  1336. }
  1337. func SaveTempPDFDocumentToURLPath(tempPath: String) {
  1338. self.document?.write(toFile: tempPath)
  1339. }
  1340. // MARK: - 定时保存
  1341. func addAutoSaveEvent() {
  1342. if (self.autoSaveTimer != nil) {
  1343. self.autoSaveTimer?.invalidate()
  1344. self.autoSaveTimer = nil
  1345. }
  1346. if self.document != nil {
  1347. self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: AutoSaveManager.manager.timeInterval * 60, repeats: true, block: { [weak self] timer in
  1348. self?.autoSaveTimerAction(timer)
  1349. })
  1350. }
  1351. self.checkAutoSaveInfo()
  1352. }
  1353. func checkAutoSaveInfo() {
  1354. guard let cnt = AutoSaveManager.manager.autoSavePaths?.count, cnt > 0 else {
  1355. return
  1356. }
  1357. if AutoSaveManager.manager.autoSaveAlertShow {
  1358. return
  1359. }
  1360. AutoSaveManager.manager.autoSaveDidEndAction = false
  1361. AutoSaveManager.manager.autoSaveAlertShow = true
  1362. let blockSaveWindow = AutoSavePopController()
  1363. blockSaveWindow.cancelHandle = { [weak self] windowController in
  1364. AutoSaveManager.manager.autoSaveDidEndAction = true
  1365. AutoSaveManager.manager.clearCache()
  1366. self?.km_quick_endSheet()
  1367. }
  1368. blockSaveWindow.confirmHandle = { [weak self] windowController in
  1369. self?.km_quick_endSheet()
  1370. self?.saveAutoSaveInfo()
  1371. }
  1372. self.km_beginSheet(windowC: blockSaveWindow)
  1373. }
  1374. func saveAutoSaveInfo() {
  1375. let openPanel = NSOpenPanel()
  1376. openPanel.canChooseDirectories = true
  1377. openPanel.canChooseFiles = false
  1378. openPanel.allowsMultipleSelection = false
  1379. let win = NSApp.keyWindow != nil ? NSApp.keyWindow : self.view.window
  1380. openPanel.beginSheetModal(for: win!) { result in
  1381. if (result == .OK) {
  1382. let folderPath = openPanel.url?.path ?? openPanel.url?.absoluteString
  1383. for path in AutoSaveManager.manager.opendPaths ?? [] {
  1384. let _path = path as? String
  1385. var newPath = "\(folderPath ?? "")/\(_path?.lastPathComponent ?? "")"
  1386. newPath = self.getValidFilePath(newPath)
  1387. do {
  1388. try FileManager.default.moveItem(atPath: _path ?? "", toPath: newPath)
  1389. } catch {
  1390. NSWorkspace.shared.activateFileViewerSelecting([URL(fileURLWithPath: newPath)])
  1391. }
  1392. }
  1393. AutoSaveManager.manager.clearCache()
  1394. }
  1395. AutoSaveManager.manager.autoSaveDidEndAction = true
  1396. }
  1397. }
  1398. func autoSaveTimerAction(_ timer: Timer) {
  1399. if (self.document == nil || self.listView?.document?.documentURL.path == nil) {
  1400. return
  1401. }
  1402. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  1403. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  1404. return
  1405. }
  1406. if let data = self.document?.isLocked, data {
  1407. return
  1408. }
  1409. if AutoSaveManager.manager.autoSaveEnabled == false {
  1410. return
  1411. }
  1412. let documentArray = NSDocumentController.shared.documents
  1413. var didFileEdit = false
  1414. for doc in documentArray {
  1415. if doc.fileURL?.path == self.document?.documentURL.path {
  1416. didFileEdit = doc.isDocumentEdited
  1417. break
  1418. }
  1419. }
  1420. if (didFileEdit == false) {
  1421. return
  1422. }
  1423. AutoSaveManager.manager.isSaving = true
  1424. let savePath = AutoSaveManager.manager.autoSaveWithPath(self.listView?.document?.documentURL.path ?? "")
  1425. if (!self.document!.isLocked) {
  1426. self.document?.write(to: URL(fileURLWithPath: savePath))
  1427. }
  1428. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
  1429. AutoSaveManager.manager.isSaving = false
  1430. }
  1431. }
  1432. func removeAutoSaveInfo() {
  1433. if self.autoSaveTimer != nil {
  1434. self.autoSaveTimer?.invalidate()
  1435. self.autoSaveTimer = nil
  1436. }
  1437. if AutoSaveManager.manager.autoSaveDidEndAction == false {
  1438. //防止提示弹窗出现后,未进行任何操作又进入自动保存的机制
  1439. return
  1440. }
  1441. if AutoSaveManager.manager.autoSaveEnabled == false {
  1442. return
  1443. }
  1444. if self.document == nil || self.listView?.document?.documentURL.path == nil {
  1445. return
  1446. }
  1447. AutoSaveManager.manager.removeAutoSavePath(self.listView?.document?.documentURL.path ?? "")
  1448. }
  1449. // MARK: - 选择 PDFDisplay 模式
  1450. @objc public func selectDisplay(display: KMPDFDisplayType, viewSettingIsReload: Bool = true) {
  1451. let toolModel = self.listView.toolMode
  1452. self.isReadMode = false
  1453. switch display {
  1454. case .singlePage:
  1455. self.listView.setDisplay(.singlePage)
  1456. break
  1457. case .singlePageContinuous:
  1458. self.listView.setDisplay(.singlePageContinuous)
  1459. break
  1460. case .twoUp:
  1461. self.listView.setDisplay(.twoUp)
  1462. break
  1463. case .twoUpContinuous:
  1464. self.listView.setDisplay(.twoUpContinuous)
  1465. break
  1466. case .bookMode:
  1467. self.listView.displaysAsBook = true
  1468. self.listView.displayTwoUp = true
  1469. self.listView.displayDirection = .horizontal
  1470. break
  1471. case .bookContinuous:
  1472. self.listView.displaysAsBook = true
  1473. self.listView.displayTwoUp = true
  1474. self.listView.displayDirection = .vertical
  1475. break
  1476. case .readModel:
  1477. self.openReadModel()
  1478. break
  1479. case .readContinuous:
  1480. self.openReadModel()
  1481. break
  1482. }
  1483. self.listView.layoutDocumentView()
  1484. // if (viewSettingIsReload && self.leftSideViewController.panelSetViewController.isViewLoaded) {
  1485. // self.leftSideViewController.panelSetViewController.reloadListViewModel()
  1486. // }
  1487. if (toolModel == .editPDFToolMode) {
  1488. if self.rightSideViewController.eidtPDFImageProperty != nil {
  1489. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  1490. self.rightSideViewController.isHidden = true
  1491. self.closeRightPane()
  1492. }
  1493. }
  1494. }
  1495. // MARK: - 选择缩放模式
  1496. @objc public func selectZoom(_ type: KMPDFZoomType) {
  1497. switch type {
  1498. case .width:
  1499. self.listView.autoScales = true
  1500. // self.listView.autoScales = false
  1501. break
  1502. case .fit:
  1503. // self.listView.autoScales = !self.listView.autoScales
  1504. if let pageHeight = self.listView.currentPage()?.size.height, pageHeight > 0 {
  1505. let pdfviewHeight = self.listView.bounds.size.height
  1506. self.listView.scaleFactor = pdfviewHeight/pageHeight
  1507. self.listView.autoScales = false
  1508. }
  1509. break
  1510. case .actualSize:
  1511. if self.listView.scaleFactor != 1.0 {
  1512. self.listView.scaleFactor = 1.0
  1513. self.listView.autoScales = false
  1514. }
  1515. break
  1516. }
  1517. }
  1518. internal func createPdf(index:Int) {
  1519. if index == 1 {
  1520. self.homeVC?.openBlankPage()
  1521. } else if index == 4 {
  1522. self.homeVC?.importFromCamera()
  1523. } else if index == 5 {
  1524. self.homeVC?.importFromScanner()
  1525. } else if index == 3 {
  1526. self.homeVC?.importFromWebPage()
  1527. } else if index == 2 {
  1528. self.homeVC?.newFromImages()
  1529. }
  1530. }
  1531. // MARK - Event 监听
  1532. private func addEventMonitor() {
  1533. if (self.eventMonitor != nil) {
  1534. self.removeEventMonitor()
  1535. }
  1536. KMPrint("已添加事件监听")
  1537. self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { [weak self] event in
  1538. if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
  1539. self?.listView.magnifyWheel(event)
  1540. return nil
  1541. }
  1542. return event
  1543. }
  1544. }
  1545. func addKeyEventMonitor() {
  1546. if (self.keyEventMonitor != nil) {
  1547. self.removeKeyEventMonitor()
  1548. }
  1549. keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
  1550. // print(event.keyCode)
  1551. if event.keyCode == 53 {
  1552. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  1553. if let data = self?.canExitPresentation(), data {
  1554. self?.browserWindowController?.exitFullscreen()
  1555. }
  1556. return nil
  1557. }
  1558. if self?.listView.toolMode == .editPDFToolMode {
  1559. if self != nil {
  1560. //使用editingSelectionString获取内容文字
  1561. if self!.listView.editingAreas() != nil {
  1562. if self!.listView.editingAreas().count > 0 && self!.listView.isEditable() {
  1563. self!.listView.clearEditingSelectCharItem()
  1564. } else if self!.listView.editingAreas().count > 0 {
  1565. if self?.listView.annotationType == .addImage ||
  1566. self?.listView.annotationType == .addText {
  1567. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1568. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1569. textItem?.isSelected = false
  1570. imageItem?.isSelected = false
  1571. }
  1572. self?.rightSideViewController.isHidden = true
  1573. self?.listView.endEditIsRemoveBlock(with: self!.listView.editingAreas().first as? CPDFEditArea)
  1574. self?.listView.updateEditing([])
  1575. self?.listView.isEditImage = false
  1576. self?.listView.setNeedsDisplayPageViewFor(self!.listView.currentPage())
  1577. if self?.listView.annotationType == .addImage {
  1578. self?.listView.change([.text, .image])
  1579. }
  1580. self?.listView.annotationType = .editTextImage
  1581. self?.closeRightPane()
  1582. } else if(self?.listView.annotationType == .addImage || self!.listView.annotationType == .addText) {
  1583. if self?.listView.annotationType == .addImage ||
  1584. self?.listView.annotationType == .addText {
  1585. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1586. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1587. textItem?.isSelected = false
  1588. imageItem?.isSelected = false
  1589. }
  1590. self?.rightSideViewController.isHidden = true
  1591. self?.listView.setShouAddEdit([])
  1592. self?.listView.change([.text, .image])
  1593. self?.listView.annotationType = .editTextImage
  1594. self?.closeRightPane()
  1595. }
  1596. } else {
  1597. if self?.listView.annotationType == .addImage ||
  1598. self?.listView.annotationType == .addText {
  1599. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1600. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1601. textItem?.isSelected = false
  1602. imageItem?.isSelected = false
  1603. }
  1604. }
  1605. }
  1606. }
  1607. } else {
  1608. if let data = self?.interactionMode, data == .presentation { // 幻灯片模式下
  1609. self?.listView.keyDown(with: event)
  1610. return nil
  1611. }
  1612. }
  1613. return event
  1614. }
  1615. }
  1616. func removeKeyEventMonitor() {
  1617. if (self.keyEventMonitor != nil) {
  1618. KMPrint("removeKeyEventMonitor 已移除事件监听")
  1619. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  1620. self.keyEventMonitor = nil
  1621. }
  1622. }
  1623. private func removeEventMonitor() {
  1624. if (self.eventMonitor != nil) {
  1625. KMPrint("已移除事件监听")
  1626. NSEvent.removeMonitor(self.eventMonitor as Any)
  1627. self.eventMonitor = nil
  1628. }
  1629. }
  1630. // MARK: - Tools
  1631. func pdfViewCanHorizontalScroll() -> Bool {
  1632. let scroll = self.listView.scroll()
  1633. if (scroll == nil) {
  1634. return false
  1635. }
  1636. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  1637. }
  1638. func pdfViewCanVerticalScroll() -> Bool {
  1639. let scroll = self.listView.scroll()
  1640. if (scroll == nil) {
  1641. return false
  1642. }
  1643. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  1644. }
  1645. // MARK: - Public Methods
  1646. // 清理数据 [eg. 通知]
  1647. public func clearData() {
  1648. self.removeNotifications()
  1649. if (self.listView.spellingTag() > 0) {
  1650. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  1651. }
  1652. self.removeAutoSaveInfo()
  1653. KMAdsManager.defaultManager.dismissSheetModal(for: self.readContentView)
  1654. // self.myDocument = nil
  1655. }
  1656. public func clearSecureOptions() {
  1657. self._secureOptions = nil
  1658. self.documentAttribute = nil
  1659. }
  1660. public func recordRemoveSecureFlag() {
  1661. self._removeSecureFlag = true
  1662. self.clearSecureOptions()
  1663. self.recordIsPDFDocumentEdited(type: .removePassword)
  1664. self._needSave = true
  1665. }
  1666. public func clearRemoveSecureFlag() {
  1667. self._removeSecureFlag = false
  1668. }
  1669. public func clearSaveWatermarkFlag() {
  1670. km_synchronized(self) {
  1671. self._saveWatermarkFlag = false
  1672. }
  1673. }
  1674. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  1675. km_synchronized(self) {
  1676. self.model.isPDFDocumentEdited = true
  1677. if let _document = self.myDocument {
  1678. KMTools.setDocumentEditedState(document: _document)
  1679. }
  1680. }
  1681. }
  1682. public func clearIsPDFDocumentEdited() {
  1683. km_synchronized(self) {
  1684. self.model.isPDFDocumentEdited = false
  1685. }
  1686. }
  1687. func showSnapshots(setups: NSArray?) {
  1688. for setup in setups ?? [] {
  1689. let swc = KMSnapshotWindowController()
  1690. swc.delegate = self
  1691. swc.setPdfDocument(self.listView.document, setup: setup as? NSDictionary)
  1692. swc.setForceOnTop(self.interactionMode != .normal)
  1693. self.myDocument?.addWindowController(swc)
  1694. }
  1695. }
  1696. func dealDocumentDidLoaded() {
  1697. self.removeBackgroundMaskView()
  1698. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1699. self.showSecureLimitTip()
  1700. }
  1701. if self.model.needConvertNotes {
  1702. self.showConvertNotesProgress()
  1703. }
  1704. if (self._documentFirstLoad) {
  1705. self.checkShouldAutoOpenLeftVC()
  1706. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1707. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  1708. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  1709. if (pageScale != nil) {
  1710. self.listView.scaleFactor = CGFloat(pageScale!)
  1711. }
  1712. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  1713. self.listView.go(toPageIndex: pageNumber!, animated: false)
  1714. } else {
  1715. self._goToFirstPageForFristAppear()
  1716. }
  1717. } else {
  1718. self._goToFirstPageForFristAppear()
  1719. }
  1720. self._documentFirstLoad = false
  1721. }
  1722. }
  1723. func tabViewIsDragging() -> Bool {
  1724. let level = self.view.window?.level ?? .normal
  1725. return level == .floating
  1726. }
  1727. // MARK: - Noti Actions
  1728. internal func documentDidUnlockNotification(_ sender: Notification) {
  1729. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  1730. if (self.myDocument == nil) {
  1731. return
  1732. }
  1733. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  1734. self.hiddenSecureLimitTip()
  1735. }
  1736. let isUnlockFromKeychain = (self.myDocument as? KMMainDocument)?.isUnlockFromKeychain ?? false
  1737. if (isUnlockFromKeychain || self.model.isSaveKeyChain == false) {
  1738. return
  1739. }
  1740. let type = KMPreferenceManager.shared.savePasswordType
  1741. if (type == .never) {
  1742. return
  1743. }
  1744. if (type == .always) {
  1745. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1746. return
  1747. }
  1748. // 保存到钥匙串
  1749. let alert = NSAlert()
  1750. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  1751. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  1752. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  1753. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  1754. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  1755. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1756. return
  1757. }
  1758. }
  1759. }
  1760. func annotationsAttributeHasChange(_ sender: Notification) {
  1761. guard let dict = sender.object as? [String : Any] else {
  1762. return
  1763. }
  1764. if let anno = dict["object"] as? CPDFAnnotation {
  1765. let value = dict["keyPath"] as? String ?? ""
  1766. let didEnd = dict["didEnd"] as? Bool ?? false
  1767. if didEnd {
  1768. if value == CPDFAnnotationBoundsKey {
  1769. if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  1770. anno.contents = anno.page?.string(for: anno.bounds) ?? ""
  1771. }
  1772. }
  1773. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
  1774. } else {
  1775. if value != CPDFAnnotationBoundsKey && value != CPDFAnnotationStartPointKey && value != CPDFAnnotationEndPointKey && value != CPDFAnnotationPathsKey { // 改变bounds(箭头、直线注释 开始点和结束点, 手绘注释的paths)的操作会卡顿,比如移动
  1776. self.leftSideViewController.refreshUIForAnnoAttributeDidChange(anno, attributes: ["keyPath" : value])
  1777. }
  1778. }
  1779. }
  1780. }
  1781. internal func applicationWillTerminateNotification(_ sender: Notification) {
  1782. self.savePageNumberIfNeed()
  1783. self.saveDocument()
  1784. }
  1785. func KMPDFViewCurrentPageDidChangedNotification(_ sender: Notification) {
  1786. if self.isReadMode {
  1787. self.readModelView.currentPageIndex = self.listView.currentPageIndex
  1788. }
  1789. //刷新前一页后一页按钮
  1790. self.updateNextAndPreViousButtonState()
  1791. }
  1792. func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
  1793. if self.isReadMode {
  1794. self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
  1795. }
  1796. //刷新前一页后一页按钮
  1797. self.updateNextAndPreViousButtonState()
  1798. }
  1799. func CEditPDFToolModeChangeStateUnkownNotification(_ sender: Notification) {
  1800. var editSelectd = false
  1801. if (self.listView.annotationType == .addText || self.listView.annotationType == .addImage) && self.listView.toolMode == .editPDFToolMode {
  1802. editSelectd = true
  1803. }
  1804. if self.listView.toolMode == .editPDFToolMode {
  1805. if editSelectd {
  1806. self.toolbarController.cancelSelected(KMToolbarAddTextEditPDFItemIdentifier)
  1807. }
  1808. }
  1809. }
  1810. @objc func handlePageChangedNotification(_ sender: Notification) {
  1811. // When the PDFView is changing scale, or when view settings change when switching fullscreen modes,
  1812. // a lot of wrong page change notifications may be send, which we better ignore.
  1813. // Full screen switching and zooming should not change the current page anyway.
  1814. if self.mwcFlags.isSwitchingFullScreen > 0 {
  1815. // if ([pdfView isZooming] || mwcFlags.isSwitchingFullScreen) {
  1816. // [self updatePageNumber];
  1817. // [self updateLeftStatus];
  1818. return
  1819. }
  1820. //
  1821. let page = self.listView.currentPage()
  1822. let pageIndex = page?.pageIndex() ?? 0
  1823. //
  1824. // if ([lastViewedPages count] == 0) {
  1825. // [lastViewedPages addPointer:(void *)pageIndex];
  1826. // } else if ((NSUInteger)[lastViewedPages pointerAtIndex:0] != pageIndex) {
  1827. // [lastViewedPages insertPointer:(void *)pageIndex atIndex:0];
  1828. // if ([lastViewedPages count] > 5)
  1829. // [lastViewedPages setCount:5];
  1830. // }
  1831. self.leftSideViewController.thumb_selectRowIndexsIfNeed(IndexSet(integer: IndexSet.Element(pageIndex)))
  1832. self.leftSideViewController.thumbnailTableView.needsDisplay = true
  1833. self.leftSideViewController.tocOutlineView.needsDisplay = true
  1834. //
  1835. // [self updatePageNumber];
  1836. // [self updatePageLabel];
  1837. //
  1838. // [self updateOutlineSelection];
  1839. // [self updateNoteSelection];
  1840. // [self updateThumbnailSelection];
  1841. //
  1842. // if (beforeMarkedPageIndex != NSNotFound && [[pdfView currentPage] pageIndex] != markedPageIndex)
  1843. // beforeMarkedPageIndex = NSNotFound;
  1844. //
  1845. // [self synchronizeWindowTitleWithDocumentName];
  1846. // [self updateLeftStatus];
  1847. // if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisplayPageBoundsKey])
  1848. // [self updateRightStatus];
  1849. // if ([self interactionMode] == SKPresentationMode)
  1850. // [[self presentationNotesDocument] setCurrentPage:[[[self presentationNotesDocument] pdfDocument] pageAtIndex:[page pageIndex]]];
  1851. }
  1852. @objc func handleDisplayBoxChangedNotification(_ sender: Notification) {
  1853. self.leftSideViewController.reloadThumbnailDataIfNeed()
  1854. // if ([[NSUserDefaults standardUserDefaults] boolForKey:SKDisplayPageBoundsKey])
  1855. // [self updateRightStatus];
  1856. }
  1857. @objc func willEnterInteractionModeNotification(_ sender: Notification) {
  1858. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1859. return
  1860. }
  1861. let interactionMode = sender.userInfo?[NSWindow.UserInfo.interactionModeKey] as? KMInteractionMode
  1862. if interactionMode == .presentation {
  1863. let backgroundColor = NSColor.black
  1864. let level = UserDefaults.standard.bool(forKey: "SKUseNormalLevelForPresentationKey") ? NSWindow.Level.normal : NSWindow.Level.popUpMenu
  1865. let wasInteractionMode = self.interactionMode
  1866. if wasInteractionMode == .normal {
  1867. self.savedNormalSetup.setDictionary(self.currentPDFSettings() as! [AnyHashable : Any])
  1868. }
  1869. // if findController.view().window() != nil {
  1870. // findController.toggleAboveView(nil, animate: false)
  1871. // }
  1872. if wasInteractionMode == .legacyFullScreen {
  1873. self.enterPresentationMode()
  1874. // updatePresentationOptions(for: self.view.window!)
  1875. self.pdfSplitView.frame = CGRect(x: 0, y: 0, width: CGRectGetWidth(centerContentView.bounds), height: CGRectGetHeight(centerContentView.bounds)-1)
  1876. self.centerContentView.addSubview(pdfSplitView)
  1877. self.listView.frame = (self.view.window?.contentView?.bounds)!
  1878. self.view.window?.contentView?.addSubview(listView)
  1879. self.view.window?.backgroundColor = backgroundColor
  1880. self.view.window?.level = level
  1881. self.listView.layoutDocumentView()
  1882. self.listView.requiresDisplay()
  1883. self.forceSubwindowsOnTop(false)
  1884. self.hideLeftSideWindow()
  1885. self.hideRightSideWindow()
  1886. self.removeBlankingWindows()
  1887. }
  1888. } else {
  1889. KMPrint("2")
  1890. }
  1891. }
  1892. @objc func didEnterInteractionModeNotification(_ sender: Notification) {
  1893. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1894. return
  1895. }
  1896. if self.interactionMode == .presentation {
  1897. // if self.pdfView().currentPage()?.isEqual(page) == false {
  1898. // self.pdfView().go(to: page)
  1899. // }
  1900. // pdfView().setInteractionMode(SKPresentationMode)
  1901. self.listView?.layoutDocumentView()
  1902. self.listView?.requiresDisplay()
  1903. }
  1904. }
  1905. @objc func willShowFullScreenNotification(_ sender: Notification) {
  1906. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1907. return
  1908. }
  1909. if self.interactionMode == .presentation {
  1910. let view = self.view.window?.firstResponder as? NSView
  1911. if let data = view?.isDescendant(of: self.pdfSplitView), data {
  1912. self.view.window?.makeFirstResponder(nil)
  1913. }
  1914. }
  1915. }
  1916. @objc func didShowFullScreenNotification(_ sender: Notification) {
  1917. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1918. return
  1919. }
  1920. if self.interactionMode == .presentation {
  1921. self.enterPresentationMode()
  1922. }
  1923. }
  1924. @objc func didAddContentViewNotification(_ sender: Notification) {
  1925. guard let win = sender.object as? NSWindow, win.isEqual(to: self.view.window) else {
  1926. return
  1927. }
  1928. if self.interactionMode == .presentation {
  1929. }
  1930. }
  1931. @objc func purchaseStateUpdateNoti() {
  1932. if IAPProductsManager.default().isAvailableAllFunction() {
  1933. KMAdsManager.defaultManager.dismissSheetModal(for: self.readContentView)
  1934. }
  1935. }
  1936. // MARK: Split View
  1937. func changePDFDocument(isChange: Bool, replaceBlock: @escaping (String) -> Void) {
  1938. let openPanel = NSOpenPanel()
  1939. openPanel.allowedFileTypes = ["pdf", "PDF"]
  1940. openPanel.allowsMultipleSelection = false
  1941. guard let mainWindow = NSApp.mainWindow else {
  1942. return
  1943. }
  1944. openPanel.beginSheetModal(for: mainWindow) { [weak self] response in
  1945. if response == NSApplication.ModalResponse.OK {
  1946. guard let url = openPanel.url else {
  1947. return
  1948. }
  1949. if let document = CPDFDocument(url: url) {
  1950. self?.secondaryPdfView?.document = nil
  1951. self?.secondaryPdfView?.document = document
  1952. if isChange {
  1953. self!.openSecondaryPdfView!.view.removeFromSuperview()
  1954. }
  1955. replaceBlock(document.documentURL?.path ?? "")
  1956. } else {
  1957. let alert = NSAlert()
  1958. alert.alertStyle = .critical
  1959. alert.messageText = NSLocalizedString("An error occurred while opening this document. The file is damaged and could not be repaired.", comment: "")
  1960. alert.runModal()
  1961. }
  1962. }
  1963. }
  1964. }
  1965. }
  1966. extension KMMainViewController {
  1967. func currentSetup() -> [String: Any] {
  1968. var setup: [String: Any] = [:]
  1969. var point = NSZeroPoint
  1970. // var rotated = listView.currentPage().rotation
  1971. if listView == nil {
  1972. return setup
  1973. }
  1974. let pageIndex = listView.currentPageIndexAndPoint(&point, rotated: nil)
  1975. setup[kWindowFrameKey] = NSStringFromRect(mainWindow?.frame ?? NSZeroRect)
  1976. setup[KMMainModel.Key.kLeftSidePaneWidth] = self.model.lastLeftPanWidth
  1977. setup[KMMainModel.Key.kRightSidePaneWidth] = self.model.lastRightPanWidth
  1978. setup[KMMainModel.Key.pageIndex] = pageIndex
  1979. // if rotated != 0 {
  1980. // setup[SCROLLPOINT_KEY] = NSStringFromPoint(point)
  1981. // }
  1982. // if !snapshots.isEmpty {
  1983. // setup[SNAPSHOTS_KEY] = snapshots.map { $0[SKSnapshotCurrentSetupKey] }
  1984. // }
  1985. // if interactionMode == SKNormalMode {
  1986. // setup.merge(currentPDFSettings(), uniquingKeysWith: { $1 })
  1987. // } else {
  1988. // setup.merge(savedNormalSetup, uniquingKeysWith: { $1 })
  1989. // ["HASHORIZONTALSCROLLER_KEY", "HASVERTICALSCROLLER_KEY", "AUTOHIDESSCROLLERS_KEY", "LOCKED_KEY"].forEach { setup.removeValue(forKey: $0) }
  1990. // }
  1991. return setup
  1992. }
  1993. // MARK: - Recommond活动
  1994. func loadRecommondPopWindow() {
  1995. if IAPProductsManager.default().isAvailableAllFunction() {
  1996. return
  1997. }
  1998. if let info = KMAdvertisementManager.manager.info.popWindowContent?.content?.first {
  1999. if recommondPopWindowVC == nil {
  2000. recommondPopWindowVC = KMRecommondPopWindow()
  2001. }
  2002. recommondPopWindowVC?.recommondInfo = info
  2003. guard let windowFrame = self.view.window?.frame, let popWindowFrame = recommondPopWindowVC?.window?.frame else {
  2004. return
  2005. }
  2006. let x = windowFrame.minX + (windowFrame.size.width - popWindowFrame.size.width) / 2.0
  2007. let y = windowFrame.minY + (windowFrame.size.height - popWindowFrame.size.height) / 2.0
  2008. recommondPopWindowVC?.window?.setFrame(NSRect(x: x, y: y, width: popWindowFrame.size.width, height: popWindowFrame.size.height), display: true)
  2009. recommondPopWindowVC?.window?.orderFront((Any).self)
  2010. recommondPopWindowVC?.window?.becomeMain()
  2011. UserDefaults.standard.set("Show", forKey: info.version ?? "")
  2012. UserDefaults.standard.synchronize()
  2013. }
  2014. }
  2015. }