KMMainViewController.swift 103 KB

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