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