KMMainViewController.swift 99 KB

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