KMMainViewController.swift 91 KB

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