KMMainViewController.swift 95 KB

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