KMMainViewController.swift 100 KB

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