KMMainViewController.swift 94 KB

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