KMMainViewController.swift 94 KB

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