KMMainViewController.swift 94 KB

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