KMMainViewController.swift 103 KB

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