KMMainViewController.swift 102 KB

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