KMMainViewController.swift 93 KB

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