KMMainViewController.swift 95 KB

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