KMMainViewController.swift 94 KB

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