KMMainViewController.swift 94 KB

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