KMMainViewController.swift 101 KB

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