KMMainViewController.swift 94 KB

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