KMMainViewController.swift 94 KB

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