KMMainViewController.swift 93 KB

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