KMMainViewController.swift 97 KB

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