KMMainViewController.swift 94 KB

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