KMMainViewController.swift 95 KB

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