KMMainViewController.swift 94 KB

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