KMMainViewController.swift 100 KB

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