KMMainViewController.swift 95 KB

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