KMMainViewController.swift 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318
  1. //
  2. // KMMainViewController.swift
  3. // PDF Master
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Cocoa
  8. @objcMembers class KMMainViewController: NSViewController,CPDFViewDelegate,CPDFListViewDelegate,NSTextFieldDelegate {
  9. @IBOutlet var PDFContendView: NSView!
  10. @IBOutlet var centerContentView: NSView!
  11. @IBOutlet var listView: CPDFListView!
  12. @IBOutlet var secondaryPdfView: CPDFView!
  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 pdfContentView: NSView!
  20. @IBOutlet weak var pdfSplitSecondView: NSBox!
  21. @IBOutlet weak var locationPageView: NSView!
  22. @IBOutlet weak var tipLabel: NSTextField!
  23. @IBOutlet weak var toplayoutConstraint: NSLayoutConstraint!
  24. @IBOutlet var childToolbarController: KMToolbarViewController!
  25. @IBOutlet var toolbarController: KMToolbarController!
  26. @IBOutlet weak var toolbarBox: NSBox!
  27. @IBOutlet weak var heightOffset: NSLayoutConstraint!
  28. //阅读模式界面
  29. @IBOutlet weak var readModelView: KMReadModelView!
  30. @IBOutlet weak var bottomAreaView: KMBox!
  31. @IBOutlet weak var readModelViewWidthConstraint: NSLayoutConstraint!
  32. var isReadMode: Bool = false
  33. var readLeftMethodType: BotaType = .None
  34. var readLeftPanelOpen = false
  35. var readLastLeftPanWidth = 0.0
  36. var readLeftViewShowPanel = false
  37. var readRightPanelOpen = false
  38. var readToolbarType: KMToolbarViewType = .None
  39. var readToolbarItemIdentifier: String = ""
  40. var readToolMode: CToolMode = .textToolMode
  41. var readAnnotationType: CAnnotationType = .unkown
  42. var readSubViewType: RightSubViewType = .None
  43. //页码显示器
  44. @IBOutlet weak var pageNumberDisplayView: KMPageNumberDisplayView!
  45. @IBOutlet weak var tipCurrentPageBoxWidthConstraint: NSLayoutConstraint!
  46. private var _needSave = false
  47. var needSave: Bool {
  48. set {
  49. _needSave = newValue
  50. if (_needSave == false) {
  51. self.clearIsPDFDocumentEdited()
  52. self.hiddenSecureSuccessTip()
  53. }
  54. }
  55. get {
  56. return _needSave
  57. }
  58. }
  59. // 标识 pdf 已编辑
  60. fileprivate var _isPDFDocumentEdited = false
  61. // 标识 pdf文字图片已编辑
  62. internal var isPDFTextImageEdited = false
  63. var isPDFDocumentEdited: Bool {
  64. get {
  65. return _isPDFDocumentEdited
  66. }
  67. }
  68. var password: String?
  69. var leftSideViewController: KMLeftSideViewController = KMLeftSideViewController.init(type: KMLeftMethodMode())
  70. var rightSideViewController: KMRightSideViewController!
  71. var searchResults: [KMSearchMode] = []
  72. var mwcFlags: MwcFlags = MwcFlags()
  73. var isShowQuickTour: Bool = false
  74. var document: CPDFDocument?
  75. var myDocument: NSDocument?
  76. var browserWindowController: KMBrowserWindowController?
  77. var documentAIViewController: KMDocumentAIViewController?
  78. var cropSettingWindowController: KMCropSettingWindowController!
  79. var currentWindowController: NSWindowController!
  80. let CPDFOfficeLeftSidePaneWidthKey = "CPDFOfficeLeftSidePaneWidthKey"
  81. let CPDFOfficeRightSidePaneWidthKey = "CPDFOfficeRightSidePaneWidthKey"
  82. @IBOutlet weak var topTipBox: NSBox!
  83. @IBOutlet weak var exitFullButton: NSButton!
  84. var hasAddRedact: Bool = false
  85. var functionWidth: Double {
  86. get {
  87. if self.isReadMode {
  88. if !self.isShowBOTA {
  89. return 0
  90. }
  91. }
  92. return 48
  93. }
  94. }
  95. var isShowBOTA: Bool = false
  96. let panelWidth = 212.0
  97. let defaultRightWidth = 260.0
  98. var lastLeftPanWidth = 0.0
  99. var lastRightPanWidth = 0.0
  100. var leftPanelOpen: Bool = false
  101. var rightPanelIsOpen = false
  102. var pageNumber: UInt?
  103. var openSecondaryPdfView: KMSecondaryViewController?
  104. var secondaryPdfContentView: NSView?
  105. var lastSplitPDFHeight: Float?
  106. internal var isSaveKeyChain = true
  107. var rightMouseEventing = false
  108. var pdfEditController: KMPDFEditViewController? {
  109. get {
  110. return self.getPDFEditController()
  111. }
  112. }
  113. var autoSaveTimer: Timer?
  114. var progressController: SKProgressController?
  115. private var _documentFirstLoad: Bool = true
  116. var eventMonitor: Any?
  117. var keyEventMonitor: Any?
  118. var mouseRightMenuEvent: NSEvent?
  119. var aiTranslationWindow: KMAITranslationWindowController?
  120. var aiTranslationConfirWC: KMAITranslationConfirmWindowController?
  121. private var background_mask: NSView?
  122. fileprivate var _secureOptions: [CPDFDocumentWriteOption : Any]?
  123. var secureOptions: [CPDFDocumentWriteOption : Any]? {
  124. get {
  125. return self._secureOptions
  126. }
  127. }
  128. fileprivate var _removeSecureFlag = false
  129. var removeSecureFlag: Bool {
  130. get {
  131. return self._removeSecureFlag
  132. }
  133. }
  134. fileprivate var _saveWatermarkFlag = false
  135. var saveWatermarkFlag: Bool {
  136. get {
  137. return self._saveWatermarkFlag
  138. }
  139. }
  140. deinit {
  141. NotificationCenter.default.removeObserver(self)
  142. self.stopAutoSaveTimer()
  143. self.removeEventMonitor()
  144. self.removeKeyEventMonitor()
  145. }
  146. override func awakeFromNib() {
  147. super.awakeFromNib()
  148. self.addBackgroundMaskView()
  149. // pdfSplitView.frame = NSMakeRect(0, 0, NSWidth(centerContentView.bounds), NSHeight(centerContentView.bounds)-1)
  150. // centerContentView.addSubview(pdfSplitView)
  151. self.PDFContendView.backgroundColor(NSColor.km_init(hex: "FFFFFF"))
  152. listView.delegate = self
  153. listView.pdfListViewDelegate = self
  154. // listView.editingConfig().isSupportMultipleSelectEditingArea = true
  155. if (document != nil) {
  156. // if (self.document!.isLocked) {
  157. //
  158. // } else {
  159. listView.document = document
  160. // }
  161. // listView.document.delegate = self
  162. let autoScale = listView.autoScales
  163. if !autoScale {
  164. listView.scaleFactor = 1.0
  165. }
  166. }
  167. self.initPDFLeftViewVC()
  168. self.initRightSideView()
  169. self.toolbarController.listView = self.listView
  170. }
  171. override func viewDidAppear() {
  172. super.viewDidAppear()
  173. //刷新向前向后按钮
  174. self.updateBackAndForwardButtonState()
  175. KMLightMemberManager.manager.canShowAdvancedView = false
  176. Task { @MainActor in
  177. await KMLightMemberManager.manager.canUseAdvanced(needNetworking: true)
  178. }
  179. // self.addEventMonitor()
  180. self.view.window?.makeFirstResponder(self.listView)
  181. // 更新属性页面的信息
  182. NotificationCenter.default.post(name: NSNotification.Name(rawValue: kKMWindowDidBecomeMainNotificationName), object: self.myDocument)
  183. if (self.document == nil) {
  184. return
  185. }
  186. if (self.document!.isLocked == false) {
  187. return
  188. }
  189. if (self.view.window == nil) {
  190. return
  191. }
  192. if (self.password != nil) {
  193. self.isSaveKeyChain = false
  194. self.listView.document.unlock(withPassword: self.password)
  195. return
  196. }
  197. KMPasswordInputWindow.openWindow(window: self.view.window!, url: self.document!.documentURL) { result , password in
  198. if (result == .cancel) {
  199. self.browserWindowController?.browser.closeTab()
  200. return
  201. }
  202. self.isSaveKeyChain = true
  203. self.listView.document = self.document
  204. self.document?.unlock(withPassword: password)
  205. }
  206. }
  207. override func viewWillAppear() {
  208. super.viewWillAppear()
  209. self.reStartAutoSaveTimer()
  210. //是否弹出登录窗口
  211. // self.needShowRegisterView()
  212. }
  213. override func viewWillDisappear() {
  214. super.viewWillDisappear()
  215. // KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  216. self.pauseAutoSaveTimer()
  217. self.removeEventMonitor()
  218. }
  219. override func viewWillLayout() {
  220. super.viewWillLayout()
  221. if (KMTools.isFullScreen(self.view.window ?? NSWindow())) { // 全屏
  222. self.exitFullButton.isHidden = false
  223. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundFullScreenColor
  224. } else {
  225. self.exitFullButton.isHidden = true
  226. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
  227. }
  228. }
  229. override func viewDidLoad() {
  230. super.viewDidLoad()
  231. leftSideViewController.mainVC = self
  232. mwcFlags.settingUpWindow = 1
  233. toolbarController.delegate = self
  234. //TODO: 先让项目运行,看后面怎么调整这段逻辑,目前最外层是 KMBrowserWindowController
  235. toolbarBox.contentView = toolbarController.view
  236. // self.childToolbarController.updateType(newType: .Annatiton)
  237. // self.showChildToolbar(showToolbar: true)
  238. // self.toolbarController.editPDFButtonAction(item: NSMenuItem())
  239. if (UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) != nil) {
  240. UserDefaults.standard.set(256, forKey: CPDFOfficeLeftSidePaneWidthKey)
  241. UserDefaults.standard.synchronize()
  242. }
  243. if (UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) != nil) {
  244. UserDefaults.standard.set(256, forKey: CPDFOfficeRightSidePaneWidthKey)
  245. UserDefaults.standard.synchronize()
  246. }
  247. let position = mianSplitView.maxPossiblePositionOfDivider(at: 1)
  248. mianSplitView.setPosition(position, ofDividerAt: 0, animate: false)
  249. mianSplitView.setPosition(mianSplitView.minPossiblePositionOfDivider(at: 0), ofDividerAt: 0, animate: false)
  250. pdfSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1), ofDividerAt: 0, animate: true)
  251. self.locationPageView.wantsLayer = true;
  252. self.locationPageView.layer?.backgroundColor = NSColor(red: 189.0/255.0, green: 223.0/255.0, blue: 253.0/255.0, alpha: 1).cgColor
  253. 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: "")
  254. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  255. if (self.listView.document != nil) {
  256. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  257. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  258. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  259. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
  260. if (pageScale != nil) {
  261. self.listView.scaleFactor = CGFloat(pageScale!)
  262. }
  263. self.listView.go(toPageIndex: pageNumber!, animated: false)
  264. }
  265. } else {
  266. self._goToFirstPageForFristAppear()
  267. }
  268. }
  269. } else {
  270. self._goToFirstPageForFristAppear()
  271. }
  272. //阅读页面
  273. readModelView.delegate = self
  274. pageNumberDisplayView.delegate = self
  275. tipCurrentPageBox.moveCallback = { [unowned self] mouseEntered, mouseBox in
  276. if mouseEntered {
  277. self.pageNumberDisplayView.hover = true
  278. // self.updatePageIndicatoreType()
  279. } else {
  280. self.pageNumberDisplayView.hover = false
  281. // self.updatePageIndicatoreType()
  282. }
  283. }
  284. NotificationCenter.default.addObserver(self, selector: #selector(rename(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerRename"), object: nil)
  285. NotificationCenter.default.addObserver(self, selector: #selector(closeTab(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerCloseTabs"), object: nil)
  286. NotificationCenter.default.addObserver(self, selector: #selector(showInFinder(_:)), name: NSNotification.Name.init(rawValue: "KMTabControllerShowInFinder"), object: nil)
  287. NotificationCenter.default.addObserver(self, selector: #selector(preferenceDidChangeNotification), name: KMPreferenceManager.didChangeNotification, object: nil)
  288. NotificationCenter.default.addObserver(self, selector: #selector(documentDidUnlockNotification), name: Notification.Name("CPDFDocumentDidUnlockNotification"), object: nil)
  289. NotificationCenter.default.addObserver(self, selector: #selector(applicationWillTerminateNotification), name: NSApplication.willTerminateNotification, object: nil)
  290. NotificationCenter.default.addObserver(self, selector: #selector(KMPDFViewCurrentPageDidChangedNotification), name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: nil)
  291. NotificationCenter.default.addObserver(self, selector: #selector(CPDFDocumentPageCountChangedNotification), name: NSNotification.Name.init(rawValue: "CPDFDocumentPageCountChangedNotification"), object: nil)
  292. NotificationCenter.default.addObserver(self, selector: #selector(CEditPDFToolModeChangeStateUnkownNotification), name: Notification.Name.init("CEditPDFToolModeChangeStateUnkown"), object: nil)
  293. self.autoSaveTimeStartOrStopIfNeed()
  294. self.toolbarController.selectItem(KMDocumentAnnotationToolbarItemIdentifier)
  295. self.closeRightPane()
  296. self.addKeyEventMonitor()
  297. //检测OCR包是否需要更新
  298. #if VERSION_DMG
  299. KMResourceDownloadManager.manager.checkDocumentAIVersion()
  300. #endif
  301. }
  302. //MARK: - PDFListView
  303. func initPDFLeftViewVC() {
  304. leftSideViewController.listView = self.listView ?? CPDFListView()
  305. leftSideViewController.view.frame = CGRect(x: 0, y:0 , width: self.leftView.frame.size.width, height: self.leftView.frame.size.height)
  306. leftSideViewController.view.autoresizingMask = [.height,.width]
  307. leftSideViewController.delegate = self
  308. self.leftView.addSubview(leftSideViewController.view)
  309. }
  310. func initRightSideView() {
  311. self.rightSideViewController = KMRightSideViewController.init()
  312. self.rightSideViewController.view.frame = CGRect(x: 0, y: 0, width: self.rightView.frame.width, height: self.rightView.frame.size.height)
  313. self.rightSideViewController.view.autoresizingMask = [.height,.width]
  314. self.rightSideViewController.listView = self.listView
  315. // self.rightSideViewController.view.isHidden = true
  316. self.rightSideViewController.isHidden = true
  317. self.rightSideViewController.delegate = self
  318. self.rightView.addSubview(self.rightSideViewController.view)
  319. self.rightSideViewController.propertyDidChange = {
  320. [weak self] (model: AnyObject?) in
  321. let topBarView = self?.toolbarController.fetchTopBarView()
  322. if (topBarView == nil || ((topBarView?.isKind(of: KMWatermarkAdjectiveTopBarView.self)) == false)) {
  323. return
  324. }
  325. /// Bates码、页眉页脚、背景、水印
  326. if (model == nil) {
  327. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: false)
  328. } else {
  329. if ((model?.isKind(of: KMBatesModel.self))!) {
  330. if ((model as! KMBatesModel).hasVaild) {
  331. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
  332. } else {
  333. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: false)
  334. }
  335. } else if ((model?.isKind(of: KMHeaderFooterModel.self))!) {
  336. if ((model as! KMHeaderFooterModel).hasVaild) {
  337. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
  338. } else {
  339. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: false)
  340. }
  341. } else if ((model?.isKind(of: KMBackgroundModel.self))!) {
  342. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
  343. } else if ((model?.isKind(of: KMWatermarkModel.self))!) {
  344. (topBarView as! KMWatermarkAdjectiveTopBarView).isCanApply(can: true)
  345. }
  346. }
  347. }
  348. }
  349. // MARK: Private Methods
  350. internal func removeNotifications() {
  351. NotificationCenter.default.removeObserver(self)
  352. self.leftSideViewController.clearAnnotationFilterData()
  353. self.leftSideViewController.clearNotification()
  354. }
  355. func checkShouldAutoOpenLeftVC() {
  356. if (KMPreferenceManager.shared.leftSideNeedCloseWhenOpenFile()) {
  357. return
  358. }
  359. if (KMPreferenceManager.shared.leftSideDisplayType == .showOutlineIfHas) {
  360. let outlineRoot = self.listView.document.outlineRoot()
  361. let hasOutline = (outlineRoot != nil && outlineRoot!.numberOfChildren > 0)
  362. if (hasOutline == false) {
  363. return
  364. }
  365. DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
  366. self.leftSideViewController.refreshMethodType(methodType: .Outline)
  367. }
  368. return
  369. }
  370. DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {
  371. let selectedIndex = UserDefaults.standard.integer(forKey: "KMBOTASelectedIndexKey")
  372. let thumai = KMLeftMethodMode()
  373. if selectedIndex == 0 {
  374. thumai.methodType = .Thumbnail
  375. } else if selectedIndex == 1 {
  376. thumai.methodType = .Outline
  377. } else if selectedIndex == 2 {
  378. thumai.methodType = .BookMark
  379. } else if selectedIndex == 3 {
  380. thumai.methodType = .Annotation
  381. } else if selectedIndex == 4 {
  382. thumai.methodType = .Search
  383. }
  384. self.leftSideViewController.refreshMethodType(methodType: thumai.methodType)
  385. }
  386. }
  387. func applyLeftSideWidth(_ leftSideWidth: CGFloat, rightSideWidth: CGFloat) -> Void {
  388. mianSplitView.setPosition(leftSideWidth, ofDividerAt: 0)
  389. mianSplitView.setPosition(mianSplitView.maxPossiblePositionOfDivider(at: 1) - mianSplitView.dividerThickness - rightSideWidth, ofDividerAt: 1)
  390. lastLeftPanWidth = leftSideWidth
  391. lastRightPanWidth = rightSideWidth
  392. }
  393. //MARK: 动画 暂未接入
  394. func animateSplitView(to position: CGFloat) {
  395. let frame1 = NSRect(x: 0, y: 0, width: position, height: mianSplitView.frame.height)
  396. let frame2 = NSRect(x: position, y: 0, width: mianSplitView.frame.width - position, height: mianSplitView.frame.height)
  397. // 创建一个新的动画上下文
  398. let animationContext = NSAnimationContext.current
  399. animationContext.duration = 0.5
  400. animationContext.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
  401. // 启用隐式动画
  402. NSAnimationContext.current.allowsImplicitAnimation = true
  403. // 移动分隔条
  404. mianSplitView.setPosition(position, ofDividerAt: 0)
  405. mianSplitView.subviews[0].frame = frame1
  406. mianSplitView.subviews[1].frame = frame2
  407. }
  408. internal var removeAllAnnotationsStore = KMPDFViewRemoveAllAnnotationsStore()
  409. internal func removeAllAnnotations() {
  410. let alert = NSAlert()
  411. alert.messageText = NSLocalizedString("This will permanently remove all annotations. Are you sure to continue?", comment: "")
  412. alert.addButton(withTitle: NSLocalizedString("Yes", comment:""))
  413. alert.addButton(withTitle: NSLocalizedString("No", comment:""))
  414. if (alert.runModal() != .alertFirstButtonReturn) {
  415. return
  416. }
  417. DispatchQueue.main.async {
  418. self.removeAllAnnotationsStore.store(t: self.listView)
  419. }
  420. }
  421. // MARK: Set Methods
  422. var setDocument: CPDFDocument? {
  423. get {
  424. return document
  425. }
  426. set {
  427. if document != newValue {
  428. document = newValue
  429. }
  430. listView.document = document
  431. // listView.document.delegate = self
  432. self.listView.layoutDocumentView()
  433. }
  434. }
  435. var setPageNumber: UInt {
  436. get {
  437. return pageNumber!
  438. }
  439. set {
  440. let pageCount = listView.document.pageCount
  441. var value = newValue
  442. if value > pageCount {
  443. value = pageCount
  444. }
  445. if value > 0 && listView.currentPage().pageIndex() != value-1 {
  446. listView.go(to: listView.document.page(at: value-1))
  447. }
  448. if pageNumber != value {
  449. pageNumber = value
  450. }
  451. }
  452. }
  453. // MARK: - 页面编辑
  454. open func enterPageEdit(_ pages: [Int] = []) {
  455. //选中page
  456. var tPages = pages
  457. if tPages.count == 0 {
  458. tPages = self.leftSideViewController.selectPages ?? [self.listView.currentPageIndex]
  459. }
  460. if (hasEnterPageEdit()) {
  461. exitPageEdit()
  462. return
  463. }
  464. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  465. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  466. for (key, value) in toolBarView.toolbarItems {
  467. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  468. (value as! KMToolBoxItem).unEnabled = true
  469. }
  470. }
  471. }
  472. #if VERSION_DMG
  473. let controller = KMPDFEditViewController_dmg(self.listView.document)
  474. #else
  475. let controller = KMPDFEditViewController(self.listView.document)
  476. #endif
  477. controller.selectedPages = tPages
  478. controller.listView = self.listView
  479. self.addChild(controller)
  480. self.PDFContendView.addSubview(controller.view)
  481. controller.view.frame = self.PDFContendView.bounds
  482. controller.view.autoresizingMask = [.width,.height]
  483. self.listView.isHidden = true
  484. controller.itemClick = { [weak self] index, params in
  485. if (index == 1) { /// 双击退出
  486. self?.enterEditMode(self!.leftSideViewController, [])
  487. DispatchQueue.main.async {
  488. let pageIndex: Int = params.first as! Int
  489. self?.listView.go(toPageIndex: pageIndex, animated: true)
  490. }
  491. } else if (index == 2) { // 打印
  492. self?.showPrintWindow(pageRange: KMPrintPageRange(type: .custom, selectPages: params.first as! [Int]))
  493. }
  494. }
  495. controller.documentEditedCallback = { [weak self] params in
  496. self?.recordIsPDFDocumentEdited()
  497. // self?.needSave = true
  498. if let data = params.first as? KMPageEditType {
  499. self?.recordSaveWatermarkFlag(type: data.toSubscribeWaterMarkType())
  500. } else {
  501. self?.recordSaveWatermarkFlag()
  502. }
  503. }
  504. controller.selectionDidChange = { [weak self] selectedIndexs in
  505. var indexSet = IndexSet()
  506. for indexPath in selectedIndexs {
  507. indexSet.insert(indexPath.item)
  508. }
  509. if indexSet.count != 0 {
  510. self?.leftSideViewController.thumbnailViewController.selectPages(indexs: indexSet, needScroll: true)
  511. // self?.listView.go(toPageIndex: indexSet.first!, animated: false)
  512. }
  513. }
  514. }
  515. open func exitPageEdit() {
  516. if (self.toolbarController != nil && self.toolbarController.mainToolBarView != nil) {
  517. let toolBarView: KMToolbarViewController = self.toolbarController.mainToolBarView!
  518. for (key, value) in toolBarView.toolbarItems {
  519. if (key == KMRightControlToolbarItemIdentifier || key == KMLeftControlToolbarItemIdentifier) {
  520. (value as! KMToolBoxItem).unEnabled = false
  521. }
  522. }
  523. }
  524. let editController = getPDFEditController()
  525. if (editController == nil) {
  526. return
  527. }
  528. self.listView.annotationType = .highlight
  529. editController?.view.removeFromSuperview()
  530. editController?.removeFromParent()
  531. self.listView.isHidden = false
  532. self.listView.layoutDocumentView()
  533. self.view.window?.makeFirstResponder(self.listView)
  534. self.listView.annotationType = .unkown
  535. self.listView.go(toPageIndex: editController!.listViewCurrentIndex, animated: false)
  536. }
  537. open func hasEnterPageEdit() -> Bool {
  538. return self.getPDFEditController() != nil
  539. }
  540. // MARK: - Private Methods
  541. private func getPDFEditController() -> KMPDFEditViewController? {
  542. var editController: KMPDFEditViewController?
  543. for controller in self.children {
  544. if (controller.isKind(of: KMPDFEditViewController.self)) {
  545. editController = (controller as! KMPDFEditViewController)
  546. break
  547. }
  548. }
  549. return editController
  550. }
  551. private func addBackgroundMaskView() {
  552. self.removeBackgroundMaskView()
  553. if let superview = self.mianSplitView.superview {
  554. let view = NSView()
  555. superview.addSubview(view)
  556. view.frame = superview.bounds
  557. view.autoresizingMask = [.width, .height]
  558. view.wantsLayer = true
  559. view.layer?.backgroundColor = .white
  560. self.background_mask = view
  561. }
  562. }
  563. private func removeBackgroundMaskView() {
  564. self.background_mask?.removeFromSuperview()
  565. self.background_mask = nil
  566. }
  567. private func _goToFirstPageForFristAppear() {
  568. DispatchQueue.main.asyncAfter(wallDeadline: .now()+0.1) {
  569. self.listView.go(toPageIndex: 0, animated: false)
  570. }
  571. }
  572. func isFileGreaterThan10MB(atPath filePath: String) -> Bool {
  573. let fileManager = FileManager.default
  574. do {
  575. let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
  576. if let fileSize = fileAttributes[.size] as? UInt64 {
  577. let megabyteSize = fileSize / (1024 * 1024)
  578. return megabyteSize >= 10
  579. }
  580. } catch {
  581. KMPrint("Error: \(error)")
  582. }
  583. return false
  584. }
  585. func isPDFPageCountExceedsLimit(filePath: String) -> Bool {
  586. let url = URL(fileURLWithPath: filePath)
  587. guard let document = PDFDocument(url: url) else {
  588. return false
  589. }
  590. let pageCount = document.pageCount
  591. return pageCount > 30
  592. }
  593. // MARK: Redact 【标记密文】
  594. func exeRedactConfirm(_ type: KMRedactConfirmType, callback: @escaping () -> ()?) {
  595. let windowController = KMRedactConfirmWindowController(type)
  596. self.currentWindowController = windowController
  597. self.view.window?.beginSheet(windowController.window!)
  598. windowController.itemClick = { [weak self] index in
  599. if (index == 2) { /// 取消
  600. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  601. self?.currentWindowController = nil
  602. callback()
  603. return
  604. }
  605. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  606. self?.currentWindowController = nil
  607. let panel = NSSavePanel()
  608. panel.nameFieldStringValue = "[新文件]"+(self?.listView.document.documentURL.lastPathComponent)!
  609. let button = NSButton.init(checkboxWithTitle: "保存后打开文档", target: nil, action: nil)
  610. button.state = .on
  611. panel.accessoryView = button
  612. panel.isExtensionHidden = true
  613. panel.beginSheetModal(for: (self?.view.window!)!) { response in
  614. if response != .OK {
  615. callback()
  616. return
  617. }
  618. if (type == .redactOne) {
  619. let anno = self!.listView.activeAnnotation
  620. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  621. callback()
  622. return
  623. }
  624. (anno as! CPDFRedactAnnotation).applyRedaction()
  625. } else if (type == .redactAll) {
  626. self?.listView.document.applyRedactions()
  627. } else if (type == .eraserOne) {
  628. let anno = self!.listView.activeAnnotation
  629. if (anno == nil || (anno?.isKind(of: CPDFRedactAnnotation.self)) == false) {
  630. callback()
  631. return
  632. }
  633. anno?.page.erasureRedact(from: anno!.bounds)
  634. } else if (type == .eraserAll) {
  635. KMRedactTools.eraserDocument((self?.listView.document)!) { result, errorAnno in
  636. if (result == false) {
  637. callback()
  638. return
  639. }
  640. }
  641. }
  642. self!.listView.document.write(to: panel.url)
  643. if (button.state == .on) {
  644. NSDocumentController.shared.openDocument(withContentsOf: panel.url!, display: true) { document, alreadyOpen, error in
  645. }
  646. } else {
  647. NSWorkspace.shared.activateFileViewerSelecting([panel.url!])
  648. }
  649. callback()
  650. }
  651. }
  652. }
  653. // MARK: Secure 【安全】
  654. public func showSecureSuccessTip() {
  655. let view: NSView = self.view
  656. let tip = KMSecureEncryptSuccessTipView()
  657. let size = NSSize(width: 379, height: 176)
  658. tip.frame = NSMakeRect(view.frame.size.width-size.width-16, view.frame.size.height-size.height-88, size.width, size.height)
  659. tip.autoresizingMask = [.minXMargin, .minYMargin]
  660. view.addSubview(tip)
  661. tip.itemClick = { [weak self] in
  662. self!.hiddenSecureSuccessTip()
  663. }
  664. }
  665. public func hiddenSecureSuccessTip() {
  666. let view: NSView = self.view
  667. var tip: KMSecureEncryptSuccessTipView?
  668. for subview in view.subviews {
  669. if (subview.isKind(of: KMSecureEncryptSuccessTipView.self)) {
  670. tip = (subview as! KMSecureEncryptSuccessTipView)
  671. break
  672. }
  673. }
  674. if (tip == nil) {
  675. return
  676. }
  677. tip?.removeFromSuperview()
  678. }
  679. public func showSecureLimitTip() {
  680. self.hiddenSecureLimitTip()
  681. let view: NSView = self.view
  682. let tip = KMSecureLimitAlertView()
  683. let size = NSSize(width: 379, height: 154)
  684. tip.frame = NSMakeRect(view.frame.size.width-size.width-16, view.frame.size.height-size.height-50, size.width, size.height)
  685. tip.autoresizingMask = [.minXMargin, .minYMargin]
  686. view.addSubview(tip)
  687. tip.itemClick = { [unowned self] index in
  688. if (index == 1) {
  689. self.hiddenSecureLimitTip()
  690. return
  691. }
  692. if (self.listView.document.allowsPrinting == false || self.listView.document.allowsCopying == false) {
  693. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  694. if result == .cancel { /// 关闭
  695. return
  696. }
  697. /// 解密成功
  698. self?.hiddenSecureLimitTip()
  699. self?.isSaveKeyChain = false
  700. self?.listView.document.unlock(withPassword: password)
  701. }
  702. return
  703. }
  704. }
  705. }
  706. public func hiddenSecureLimitTip() {
  707. let view: NSView = self.view
  708. var tip: KMSecureLimitAlertView?
  709. for subview in view.subviews {
  710. if (subview.isKind(of: KMSecureLimitAlertView.self)) {
  711. tip = (subview as! KMSecureLimitAlertView)
  712. break
  713. }
  714. }
  715. if (tip == nil) {
  716. return
  717. }
  718. tip?.removeFromSuperview()
  719. }
  720. override func mouseMoved(with event: NSEvent) {
  721. }
  722. func savePageNumberIfNeed() {
  723. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  724. if self.listView.document != nil {
  725. KMPreferenceManager.shared.setPageNumber(self.listView.currentPageIndex, forKey: self.listView.document.documentURL.path)
  726. KMPreferenceManager.shared.setPageScale(Float(self.listView.scaleFactor), forKey: self.listView.document.documentURL.path)
  727. }
  728. }
  729. }
  730. // MARK: -
  731. // MARK: 退出全屏
  732. @IBAction func exitFullScreen(_ sender: Any) {
  733. if (self.view.window == nil) {
  734. return
  735. }
  736. if (KMTools.isFullScreen(self.view.window!)) {
  737. self.view.window?.toggleFullScreen(nil)
  738. }
  739. }
  740. // MARK: -
  741. // MARK: 显示合并窗口
  742. public func showMergeWindow(url: URL? = nil, _ password: String?) {
  743. DispatchQueue.main.async {
  744. if let _url = url {
  745. let document = PDFDocument(url: _url)
  746. let windowController = KMPDFEditAppendWindow(pdfDocument: document, password: password)
  747. windowController?.oriDucumentUrl = self.listView.document.documentURL
  748. self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  749. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, selectedIndexSet in
  750. })
  751. } else {
  752. let document = PDFDocument(url: self.listView.document.documentURL)
  753. let windowController = KMPDFEditAppendWindow(pdfDocument: document, password: password)
  754. self.toolbarController.cancelSelected(KMToolbarToolMergeItemIdentifier)
  755. windowController?.beginSheetModal(for: self.view.window, completionHandler: { result, selectedIndexSet in
  756. })
  757. }
  758. }
  759. }
  760. // MARK: -
  761. // MARR: 显示加密弹窗
  762. public func showSecureWindow(_ url: URL) {
  763. let windowController = KMSecureEncryptWindowController(windowNibName: "KMSecureEncryptWindowController")
  764. windowController.documentURL = url
  765. windowController.myDocument = self.listView.document
  766. self.currentWindowController = windowController
  767. windowController.itemClick = { [weak self] index in
  768. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  769. self?.currentWindowController = nil
  770. }
  771. windowController.resultCallback = { [weak self] result in
  772. let windowController_secure = self?.currentWindowController as! KMSecureEncryptWindowController
  773. self?.view.window?.endSheet((self?.currentWindowController.window)!)
  774. self?.currentWindowController = nil
  775. self?._secureOptions = windowController_secure.options
  776. self?.needSave = true
  777. self?.recordIsPDFDocumentEdited(type: .setPassword)
  778. if (result) {
  779. self?.showSecureSuccessTip()
  780. self?.recordSaveWatermarkFlag(type: .setPassword)
  781. } else {
  782. let alert = NSAlert()
  783. alert.messageText = NSLocalizedString("Failure", comment: "")
  784. alert.runModal()
  785. }
  786. }
  787. self.view.window?.beginSheet(windowController.window!)
  788. }
  789. // MARK: -
  790. // MARK: 保存文档
  791. internal func needSaveDocument() -> Bool {
  792. if (self.isPDFDocumentEdited) {
  793. return self.isPDFDocumentEdited
  794. }
  795. if (self.needSave) {
  796. return self.needSave
  797. }
  798. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  799. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  800. return false
  801. }
  802. return true
  803. }
  804. internal func saveDocument(overlookDocumentIfEdited overlook: Bool = false) {
  805. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  806. if (overlook) {
  807. document?.save(nil)
  808. return
  809. }
  810. if (self.isPDFDocumentEdited) {
  811. self.clearIsPDFDocumentEdited()
  812. self.needSave = false
  813. document?.save(nil)
  814. return
  815. }
  816. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  817. return
  818. }
  819. document?.save(nil)
  820. }
  821. internal func asyncSaveDocument(overlookDocumentIfEdited overlook: Bool = false, callback:@escaping KMCommonBlock) {
  822. let document: KMMainDocument? = self.myDocument as? KMMainDocument
  823. if (overlook) {
  824. DispatchQueue.main.async {
  825. document?.save(nil)
  826. callback()
  827. }
  828. return
  829. }
  830. if (self.isPDFDocumentEdited) {
  831. self.clearIsPDFDocumentEdited()
  832. self.needSave = false
  833. DispatchQueue.main.async {
  834. document?.save(nil)
  835. callback()
  836. }
  837. return
  838. }
  839. if (document?.isDocumentEdited == nil || document!.isDocumentEdited == false) {
  840. callback()
  841. return
  842. }
  843. DispatchQueue.main.async {
  844. document?.save(nil)
  845. callback()
  846. }
  847. }
  848. internal func saveDocumentWithProgressAlert(callback:@escaping KMCommonBlock) {
  849. // 显示进度
  850. self.showProgressWindow(message: NSLocalizedString("Save PDF", comment: ""))
  851. self.progressController?.maxValue = 3.0
  852. self.progressController?.increment(by: 1.0)
  853. // 保存文档
  854. self.asyncSaveDocument { [unowned self] params in
  855. // 执行进度 [假进度]
  856. self.progressController?.increment(by: 1.0)
  857. self.progressController?.increment(by: 1.0)
  858. // DispatchQueue.main.async {
  859. DispatchQueue.main.asyncAfter(deadline: .now()+0.1) {
  860. // 隐藏进度
  861. self.hiddenProgressWindow()
  862. // 回调
  863. callback()
  864. }
  865. }
  866. }
  867. // MARK: -
  868. // MARK: 选择 PDFDisplay 模式
  869. @objc public func selectDisplay(display: KMPDFDisplayType, viewSettingIsReload: Bool = true) {
  870. let toolModel = self.listView.toolMode
  871. self.isReadMode = false
  872. switch display {
  873. case .singlePage:
  874. self.listView.setDisplay(.singlePage)
  875. break
  876. case .singlePageContinuous:
  877. self.listView.setDisplay(.singlePageContinuous)
  878. break
  879. case .twoUp:
  880. self.listView.setDisplay(.twoUp)
  881. break
  882. case .twoUpContinuous:
  883. self.listView.setDisplay(.twoUpContinuous)
  884. break
  885. case .bookMode:
  886. self.listView.displaysAsBook = true
  887. self.listView.displayTwoUp = true
  888. self.listView.displayDirection = .horizontal
  889. break
  890. case .bookContinuous:
  891. self.listView.displaysAsBook = true
  892. self.listView.displayTwoUp = true
  893. self.listView.displayDirection = .vertical
  894. break
  895. case .readModel:
  896. self.openReadModel()
  897. break
  898. case .readContinuous:
  899. self.openReadModel()
  900. break
  901. }
  902. self.listView.layoutDocumentView()
  903. if (viewSettingIsReload && self.leftSideViewController.panelSetViewController.isViewLoaded) {
  904. self.leftSideViewController.panelSetViewController.reloadListViewModel()
  905. }
  906. if (toolModel == .editPDFToolMode) {
  907. if self.rightSideViewController.eidtPDFImageProperty != nil {
  908. self.rightSideViewController.eidtPDFImageProperty?.cancelCutImageAction("")
  909. self.rightSideViewController.isHidden = true
  910. self.closeRightPane()
  911. }
  912. }
  913. }
  914. // Mark: -
  915. // MARK: - 选择缩放模式
  916. @objc public func selectZoom(_ type: KMPDFZoomType) {
  917. switch type {
  918. case .width:
  919. self.listView.autoScales = true
  920. // self.listView.autoScales = false
  921. break
  922. case .fit:
  923. // self.listView.autoScales = !self.listView.autoScales
  924. let pageHeight = self.listView.currentPage()!.size.height
  925. let pdfviewHeight = self.listView.bounds.size.height
  926. self.listView.scaleFactor = pdfviewHeight/pageHeight
  927. self.listView.autoScales = false
  928. break
  929. case .actualSize:
  930. if self.listView.scaleFactor != 1.0 {
  931. self.listView.scaleFactor = 1.0
  932. self.listView.autoScales = false
  933. }
  934. break
  935. }
  936. }
  937. // MARK: - 自动保存
  938. internal func autoSaveTimeStartOrStopIfNeed() {
  939. if (KMPreferenceManager.shared.autoSave == false) {
  940. self.stopAutoSaveTimer()
  941. return
  942. }
  943. self.startAutoSaveTimer(KMPreferenceManager.shared.autoSaveTimeInterval)
  944. if (self.myDocument == nil) {
  945. self.stopAutoSaveTimer()
  946. return
  947. }
  948. let browser = self.browserWindowController?.browser
  949. guard let activeDocument = browser?.activeTabContents() else {
  950. return
  951. }
  952. if (self.myDocument!.isEqual(to: activeDocument) == false) {
  953. self.pauseAutoSaveTimer()
  954. return
  955. }
  956. }
  957. private func startAutoSaveTimer(_ interval: TimeInterval) {
  958. if (self.autoSaveTimer != nil) {
  959. self.autoSaveTimer?.invalidate()
  960. self.autoSaveTimer = nil
  961. }
  962. self.autoSaveTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: true) { [weak self] timer in
  963. DispatchQueue.main.async {
  964. #if DEBUG
  965. Swift.debugPrint("文档已自动保存")
  966. if let _document = self?.myDocument {
  967. Swift.debugPrint(_document.fileURL as Any)
  968. }
  969. #endif
  970. self?.saveDocument()
  971. }
  972. }
  973. RunLoop.current.add(self.autoSaveTimer!, forMode: .common)
  974. }
  975. private func pauseAutoSaveTimer() {
  976. self.autoSaveTimer?.fireDate = Date.distantFuture
  977. }
  978. private func reStartAutoSaveTimer() {
  979. self.autoSaveTimer?.fireDate = Date()+KMPreferenceManager.shared.autoSaveTimeInterval
  980. }
  981. private func needShowRegisterView() {
  982. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1) {
  983. if KMLightMemberManager.manager.checkPopupRegister() {
  984. // Login & Logout
  985. let window = NSApp.mainWindow ?? self.view.window
  986. if KMLightMemberManager.manager.isLogin() {
  987. } else if window != nil {
  988. var email: String = UserDefaults.standard.value(forKey: "kLoginEmail") as? String ?? ""
  989. if email.count == 0 {
  990. KMLoginWindowController.show(window: window!, .Batch, .register)
  991. } else {
  992. KMLoginWindowController.show(window: window!, .Batch, .login)
  993. }
  994. }
  995. }
  996. }
  997. }
  998. private func stopAutoSaveTimer() {
  999. self.autoSaveTimer?.invalidate()
  1000. self.autoSaveTimer = nil
  1001. }
  1002. // MARK: -
  1003. // MARK: Progress
  1004. func showProgressWindow(message: String = "") {
  1005. if (self.progressController != nil) {
  1006. self.hiddenProgressWindow()
  1007. }
  1008. let progress = SKProgressController()
  1009. progress.showClose = false
  1010. progress.message = message
  1011. progress.window?.backgroundColor = NSColor.km_init(hex: "#36383B")
  1012. progress.window?.contentView?.wantsLayer = true
  1013. progress.window?.contentView?.layer?.backgroundColor = NSColor.km_init(hex: "#36383B").cgColor
  1014. progress.progressField.textColor = NSColor.white
  1015. self.progressController = progress
  1016. self.view.window?.beginSheet(progress.window!)
  1017. }
  1018. func hiddenProgressWindow() {
  1019. if (self.progressController != nil) {
  1020. self.view.window?.endSheet((self.progressController?.window)!)
  1021. self.progressController = nil
  1022. }
  1023. }
  1024. // MARK -
  1025. // MARK - Event 监听
  1026. private func addEventMonitor() {
  1027. if (self.eventMonitor != nil) {
  1028. self.removeEventMonitor()
  1029. }
  1030. KMPrint("已添加事件监听")
  1031. self.eventMonitor = NSEvent.addLocalMonitorForEvents(matching: .scrollWheel) { [weak self] event in
  1032. if (event.type == .scrollWheel && event.modifierFlags.contains(.option)) { // Alt + 鼠标滚轮
  1033. self?.listView.magnifyWheel(event)
  1034. return nil
  1035. }
  1036. return event
  1037. }
  1038. }
  1039. func addKeyEventMonitor() {
  1040. if (self.keyEventMonitor != nil) {
  1041. self.removeKeyEventMonitor()
  1042. }
  1043. keyEventMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
  1044. // print(event.keyCode)
  1045. if event.keyCode == 53 {
  1046. if self?.listView.toolMode == .editPDFToolMode {
  1047. if self != nil {
  1048. //使用editingSelectionString获取内容文字
  1049. if self!.listView.editingAreas() != nil {
  1050. if self!.listView.editingAreas().count > 0 && self!.listView.isEditable() {
  1051. self!.listView.clearEditingSelectCharItem()
  1052. } else if self!.listView.editingAreas().count > 0 {
  1053. if self?.listView.annotationType == .addImage ||
  1054. self?.listView.annotationType == .addText {
  1055. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1056. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1057. textItem?.isSelected = false
  1058. imageItem?.isSelected = false
  1059. }
  1060. self?.rightSideViewController.isHidden = true
  1061. self?.listView.endEditIsRemoveBlock(with: self!.listView.editingAreas().first as? CPDFEditArea)
  1062. self?.listView.updateEditing([])
  1063. self?.listView.isEditImage = false
  1064. self?.listView.setNeedsDisplayPageViewFor(self!.listView.currentPage())
  1065. self?.closeRightPane()
  1066. } else if(self?.listView.annotationType == .addImage || self!.listView.annotationType == .addText) {
  1067. if self?.listView.annotationType == .addImage ||
  1068. self?.listView.annotationType == .addText {
  1069. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1070. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1071. textItem?.isSelected = false
  1072. imageItem?.isSelected = false
  1073. }
  1074. self?.rightSideViewController.isHidden = true
  1075. self?.listView.setShouAddEdit([])
  1076. self?.listView.change([.text, .image])
  1077. self?.listView.annotationType = .editTextImage
  1078. self?.closeRightPane()
  1079. }
  1080. } else {
  1081. if self?.listView.annotationType == .addImage ||
  1082. self?.listView.annotationType == .addText {
  1083. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1084. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1085. textItem?.isSelected = false
  1086. imageItem?.isSelected = false
  1087. }
  1088. }
  1089. }
  1090. }
  1091. }
  1092. return event
  1093. }
  1094. }
  1095. func removeKeyEventMonitor() {
  1096. if (self.keyEventMonitor != nil) {
  1097. KMPrint("removeKeyEventMonitor 已移除事件监听")
  1098. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  1099. self.keyEventMonitor = nil
  1100. }
  1101. }
  1102. private func removeEventMonitor() {
  1103. if (self.eventMonitor != nil) {
  1104. KMPrint("已移除事件监听")
  1105. NSEvent.removeMonitor(self.eventMonitor as Any)
  1106. self.eventMonitor = nil
  1107. }
  1108. }
  1109. // MARK: -
  1110. // MARK: Tools
  1111. func pdfViewCanHorizontalScroll() -> Bool {
  1112. let scroll = self.listView.scroll()
  1113. if (scroll == nil) {
  1114. return false
  1115. }
  1116. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  1117. }
  1118. func pdfViewCanVerticalScroll() -> Bool {
  1119. let scroll = self.listView.scroll()
  1120. if (scroll == nil) {
  1121. return false
  1122. }
  1123. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  1124. }
  1125. // MARK: - Public Methods
  1126. // 清理数据 [eg. 通知]
  1127. public func clearData() {
  1128. self.removeNotifications()
  1129. if (self.listView.spellingTag() > 0) {
  1130. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  1131. }
  1132. }
  1133. public func clearSecureOptions() {
  1134. self._secureOptions = nil
  1135. }
  1136. public func recordRemoveSecureFlag() {
  1137. self._removeSecureFlag = true
  1138. self.clearSecureOptions()
  1139. self.recordIsPDFDocumentEdited(type: .removePassword)
  1140. self._needSave = true
  1141. }
  1142. public func clearRemoveSecureFlag() {
  1143. self._removeSecureFlag = false
  1144. }
  1145. public func recordSaveWatermarkFlag(type: KMSubscribeWaterMarkType = .none) {
  1146. km_synchronized(self) {
  1147. self._saveWatermarkFlag = true
  1148. }
  1149. if let _document = self.myDocument as? KMMainDocument {
  1150. _document.recordTrackEvent(type: type)
  1151. }
  1152. }
  1153. public func clearSaveWatermarkFlag() {
  1154. km_synchronized(self) {
  1155. self._saveWatermarkFlag = false
  1156. }
  1157. }
  1158. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  1159. km_synchronized(self) {
  1160. self._isPDFDocumentEdited = true
  1161. if let _document = self.myDocument {
  1162. KMTools.setDocumentEditedState(document: _document)
  1163. }
  1164. }
  1165. }
  1166. public func clearIsPDFDocumentEdited() {
  1167. km_synchronized(self) {
  1168. self._isPDFDocumentEdited = false
  1169. }
  1170. }
  1171. // MARK: - Noti Actions
  1172. internal func documentDidUnlockNotification(_ sender: Notification) {
  1173. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  1174. if (self.myDocument == nil) {
  1175. return
  1176. }
  1177. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  1178. self.hiddenSecureLimitTip()
  1179. }
  1180. if ((self.myDocument as! KMMainDocument).isUnlockFromKeychain || self.isSaveKeyChain == false) {
  1181. return
  1182. }
  1183. let type = KMPreferenceManager.shared.savePasswordType
  1184. if (type == .never) {
  1185. return
  1186. }
  1187. if (type == .always) {
  1188. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1189. return
  1190. }
  1191. // 保存到钥匙串
  1192. let alert = NSAlert()
  1193. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  1194. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  1195. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  1196. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  1197. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  1198. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1199. return
  1200. }
  1201. }
  1202. }
  1203. internal func applicationWillTerminateNotification(_ sender: Notification) {
  1204. self.savePageNumberIfNeed()
  1205. self.saveDocument()
  1206. }
  1207. func KMPDFViewCurrentPageDidChangedNotification(_ sender: Notification) {
  1208. if self.isReadMode {
  1209. self.readModelView.currentPageIndex = self.listView.currentPageIndex
  1210. }
  1211. //刷新向前向后按钮
  1212. self.updateBackAndForwardButtonState()
  1213. }
  1214. func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
  1215. if self.isReadMode {
  1216. self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
  1217. }
  1218. //刷新向前向后按钮
  1219. self.updateBackAndForwardButtonState()
  1220. }
  1221. func CEditPDFToolModeChangeStateUnkownNotification(_ sender: Notification) {
  1222. var editSelectd = false
  1223. if (self.listView.annotationType == .addText || self.listView.annotationType == .addImage) && self.listView.toolMode == .editPDFToolMode {
  1224. editSelectd = true
  1225. }
  1226. if self.listView.toolMode == .editPDFToolMode {
  1227. if editSelectd {
  1228. self.toolbarController.cancelSelected(KMToolbarAddTextEditPDFItemIdentifier)
  1229. }
  1230. }
  1231. }
  1232. //MARK: - PDFListViewDelegate
  1233. func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  1234. // KMPrint("pdfViewDocumentDidLoaded")
  1235. self.removeBackgroundMaskView()
  1236. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1237. self.showSecureLimitTip()
  1238. }
  1239. if (self._documentFirstLoad) {
  1240. self.checkShouldAutoOpenLeftVC()
  1241. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1242. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  1243. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  1244. if (pageScale != nil) {
  1245. self.listView.scaleFactor = CGFloat(pageScale!)
  1246. }
  1247. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  1248. self.listView.go(toPageIndex: pageNumber!, animated: false)
  1249. } else {
  1250. self._goToFirstPageForFristAppear()
  1251. }
  1252. } else {
  1253. self._goToFirstPageForFristAppear()
  1254. }
  1255. self._documentFirstLoad = false
  1256. }
  1257. let notification = Notification(name: Notification.Name(rawValue: "pdfViewDocumentDidLoaded"))
  1258. self.preferenceDidChangeNotification(notification:notification)
  1259. let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) as? NSNumber ?? NSNumber(value: panelWidth + functionWidth)
  1260. let rightWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) as? NSNumber ?? NSNumber(value: defaultRightWidth)
  1261. applyLeftSideWidth(leftWidthNumber.doubleValue, rightSideWidth: rightWidthNumber.doubleValue)
  1262. self.updatePageIndicatoreType()
  1263. }
  1264. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  1265. self.updatePageIndicatoreType()
  1266. NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: self.document)
  1267. // KMPrint("KMPDFViewCurrentPageDidChanged")
  1268. }
  1269. func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
  1270. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor * 100))%"
  1271. self.updateZoomInOutButtonState()
  1272. // KMPrint("pdfViewScaleDidChanged")
  1273. }
  1274. func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
  1275. if let urlString = url, urlString == kKMPurchaseProductURLString {
  1276. //跳转订阅比较表
  1277. let _ = KMComparativeTableViewController.show(window: NSApp.mainWindow ?? NSWindow())
  1278. return
  1279. }
  1280. KMTools.openURL(urlString: url)
  1281. }
  1282. func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  1283. KMPrint("pdfViewPerformURL")
  1284. }
  1285. func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  1286. KMPrint("pdfViewPerformPrint")
  1287. }
  1288. func pdfViewPerformGo(toPage pdfView: CPDFView!) {
  1289. KMPrint("pdfViewPerformGo")
  1290. }
  1291. func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
  1292. KMPrint("pdfViewOpenPDF")
  1293. }
  1294. func pdfViewPerformReset(_ pdfView: CPDFView!) {
  1295. KMPrint("pdfViewPerformReset")
  1296. }
  1297. func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
  1298. KMPrint("pdfViewEditingBlockDidChanged")
  1299. }
  1300. func pdfViewAsBookBookmark() -> NSImage! {
  1301. return NSImage(named: "KMImageNameUXIconPDFViewBookMark")!
  1302. }
  1303. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  1304. self.recordSaveWatermarkFlag()
  1305. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText {
  1306. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  1307. self.rightSideViewController.eidtPDFTextProperty.updateTextTextPresuppositionState()
  1308. }
  1309. }
  1310. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  1311. let areas = self.listView.editingAreas()
  1312. if areas == nil || areas?.count ?? 0 == 0 {
  1313. if self.listView.toolMode == .editPDFToolMode {
  1314. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  1315. if self.listView.isEditImage {
  1316. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1317. } else {
  1318. // if self.listView.annotationType == .addImage {
  1319. // self.closeRightPane()
  1320. // }
  1321. // if self.rightSideViewController.eidtPDFImageProperty != nil {
  1322. // self.rightSideViewController.eidtPDFImageProperty.reloadData()
  1323. // }
  1324. // self.openRightPane()
  1325. }
  1326. } else {
  1327. self.closeRightPane()
  1328. }
  1329. } else {
  1330. self.rightSideViewController.isHidden = true
  1331. self.closeRightPane()
  1332. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1333. self.rightSideViewController.eidtPDFTextProperty.initData()
  1334. }
  1335. }
  1336. if self.listView.isEdited() {
  1337. self.recordIsPDFDocumentEdited(type: .editText)
  1338. }
  1339. if self.listView.annotationType != .addText {
  1340. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  1341. }
  1342. return
  1343. }
  1344. self.isPDFTextImageEdited = true
  1345. if (self.listView.annotationType == .addImage) && areas!.count > 0 {
  1346. var isImageArea = false
  1347. for i in 0 ... areas!.count-1 {
  1348. if areas![i] is CPDFEditImageArea {
  1349. isImageArea = true
  1350. }
  1351. }
  1352. if isImageArea {
  1353. // self.rightSideViewController.view.isHidden = false
  1354. self.rightSideViewController.isHidden = false
  1355. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddImage {
  1356. self.rightSideViewController.subViewType = .EditPDFAddImage
  1357. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  1358. }
  1359. self.openRightPane()
  1360. } else {
  1361. // self.rightSideViewController.view.isHidden = true
  1362. self.rightSideViewController.isHidden = true
  1363. self.closeRightPane()
  1364. }
  1365. } else if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1366. // self.rightSideViewController.view.isHidden = false
  1367. self.rightSideViewController.isHidden = false
  1368. if self.listView.editingSelectionString().count != 0 {
  1369. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  1370. } else {
  1371. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1372. }
  1373. self.openRightPane()
  1374. } else {
  1375. var textsAreas : [CPDFEditTextArea] = []
  1376. var imagesAreas : [CPDFEditImageArea] = []
  1377. if self.listView.editingAreas()?.count ?? 0 < 1 {
  1378. return
  1379. }
  1380. for i in 0 ... areas!.count-1 {
  1381. if areas![i] is CPDFEditTextArea {
  1382. textsAreas.append(areas![i] as! CPDFEditTextArea)
  1383. }
  1384. if areas![i] is CPDFEditImageArea {
  1385. imagesAreas.append(areas![i] as! CPDFEditImageArea)
  1386. }
  1387. }
  1388. if textsAreas.count > 0 && textsAreas.count == areas!.count {
  1389. // self.rightSideViewController.view.isHidden = false
  1390. self.rightSideViewController.isHidden = false
  1391. self.rightSideViewController.subViewType = .EditPDFAddText
  1392. self.rightSideViewController.eidtPDFTextProperty?.reloadData()
  1393. self.openRightPane()
  1394. } else if imagesAreas.count > 0 {
  1395. // self.rightSideViewController.view.isHidden = false
  1396. self.rightSideViewController.isHidden = false
  1397. self.rightSideViewController.subViewType = .EditPDFAddImage
  1398. self.rightSideViewController.eidtPDFImageProperty?.reloadData()
  1399. self.openRightPane()
  1400. }
  1401. }
  1402. if self.listView.isEdited() {
  1403. self.recordIsPDFDocumentEdited(type: .editText)
  1404. if self.listView.annotationType != .addText {
  1405. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  1406. }
  1407. }
  1408. }
  1409. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  1410. self.recordSaveWatermarkFlag()
  1411. if editArea != nil && (editArea is CPDFEditImageArea){
  1412. self.listView.cropAreas = editArea as? CPDFEditImageArea
  1413. }
  1414. }
  1415. //编辑PDF 创建图片区域回调
  1416. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1417. self.recordSaveWatermarkFlag(type: .editImage)
  1418. if self.listView.isEditImage {
  1419. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1420. } else {
  1421. let panel = NSOpenPanel()
  1422. panel.allowsMultipleSelection = false
  1423. panel.allowedFileTypes = ["png","jpg"]
  1424. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  1425. if response == .OK {
  1426. var filePath = panel.url?.path
  1427. var image = NSImage.init(contentsOf: panel.url!)
  1428. //图片自适应范围
  1429. if image != nil {
  1430. var imageRect = rect
  1431. let imageSize = image!.size
  1432. var previewSize = rect.size
  1433. var isChangeSize = false
  1434. if previewSize.width == 0 && previewSize.height == 0 {
  1435. previewSize = CGSize(width: 500, height: 500)
  1436. isChangeSize = true
  1437. }
  1438. let scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  1439. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  1440. if isChangeSize {
  1441. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  1442. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  1443. } else {
  1444. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  1445. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  1446. }
  1447. imageRect.size = newSize
  1448. let limitWidth = 1920.0
  1449. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  1450. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  1451. targetSize: CGSize(width: limitWidth, height: limitWidth),
  1452. maxSizeInBytes: 1024 * 1024 * 5,
  1453. targetCompression: 1.0)
  1454. }
  1455. //自适应page
  1456. let pageRect = self.listView.currentPage().bounds
  1457. if imageRect.width > pageRect.width ||
  1458. imageRect.height > pageRect.height {
  1459. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  1460. imageRect = CGRect(x: imageRect.origin.x,
  1461. y: imageRect.origin.y,
  1462. width: imageRect.width * pageScale,
  1463. height: imageRect.height * pageScale)
  1464. }
  1465. if imageRect.origin.x < 0 {
  1466. imageRect.origin.x = 5
  1467. }
  1468. if imageRect.origin.y < 0 {
  1469. imageRect.origin.y = 5
  1470. }
  1471. if imageRect.origin.x + imageRect.width > pageRect.width ||
  1472. imageRect.origin.y + imageRect.height > pageRect.height {
  1473. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  1474. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  1475. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  1476. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  1477. }
  1478. DispatchQueue.main.async {
  1479. self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  1480. self.isPDFTextImageEdited = true
  1481. self.recordIsPDFDocumentEdited(type: .editImage)
  1482. // self.asyncSaveDocument { params in
  1483. //
  1484. // }
  1485. }
  1486. }
  1487. }
  1488. }
  1489. }
  1490. }
  1491. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1492. // print(rect)
  1493. var newrect = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height)
  1494. if __CGSizeEqualToSize(rect.size, CGSize.zero) {
  1495. newrect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  1496. } else {
  1497. newrect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  1498. }
  1499. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  1500. let fontName = KMEditPDFTextManager.manager.fetchFontName(fontName: model.fontName)
  1501. let fontSize = model.fontSize
  1502. let fontColor = model.color
  1503. let fontAlign = model.alignment
  1504. let fontStyle = KMEditPDFTextManager.manager.fetchFontStyle(fontName: model.fontName)
  1505. NSColorPanel.shared.color = fontColor
  1506. let font = KMEditPDFTextManager.manager.fetchFont(fontName: fontName, style: fontStyle, size: fontSize)
  1507. let style = NSMutableParagraphStyle()
  1508. style.alignment = fontAlign
  1509. let attributes = [NSAttributedString.Key.font:font, NSAttributedString.Key.foregroundColor:fontColor,NSAttributedString.Key.paragraphStyle:style] as [NSAttributedString.Key : Any]
  1510. self.listView.createEmptyStringBounds(newrect,withAttributes: attributes as [NSAttributedString.Key : Any], page: pdfView.currentPage())
  1511. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1512. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1513. }
  1514. // self.asyncSaveDocument { params in
  1515. //
  1516. // }
  1517. self.recordSaveWatermarkFlag(type: .editText)
  1518. }
  1519. // func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
  1520. // debugPrint("pdfViewEditingDoubleClick")
  1521. // }
  1522. func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
  1523. debugPrint("pdfViewEditingOperationDidChanged")
  1524. if self.listView.isEdited() {
  1525. self.recordSaveWatermarkFlag()
  1526. }
  1527. }
  1528. // func pdfListViewEditAnnotation(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
  1529. // debugPrint("pdfListViewEditAnnotation")
  1530. // }
  1531. func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
  1532. let command = theEvent.modifierFlags.contains(.command)
  1533. let control = theEvent.modifierFlags.contains(.control)
  1534. KMPrint(theEvent.keyCode)
  1535. if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
  1536. self.menuItemBookMarkClick_add(sender: NSMenuItem())
  1537. return false
  1538. } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
  1539. return false
  1540. } else if (theEvent.keyCode == 123) { // 向左
  1541. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1542. return false
  1543. } else {
  1544. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  1545. self.listView.goToPreviousPage(nil)
  1546. return false
  1547. }
  1548. }
  1549. } else if (theEvent.keyCode == 126) { // 向上
  1550. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1551. return false
  1552. } else {
  1553. if (self.listView.isContinousScroll()) {
  1554. return true
  1555. }
  1556. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  1557. self.listView.goToPreviousPage(nil)
  1558. return false
  1559. }
  1560. }
  1561. } else if (theEvent.keyCode == 124) { // 向右
  1562. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1563. return false
  1564. } else {
  1565. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  1566. self.listView.goToNextPage(nil)
  1567. return false
  1568. }
  1569. }
  1570. } else if (theEvent.keyCode == 125) { // 向下
  1571. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1572. return false
  1573. } else {
  1574. if (self.listView.isContinousScroll()) {
  1575. return true
  1576. }
  1577. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  1578. self.listView.goToNextPage(nil)
  1579. return false
  1580. }
  1581. }
  1582. } else if (theEvent.keyCode == 36) {
  1583. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  1584. if self.listView.isEditImage {
  1585. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1586. }
  1587. }
  1588. }
  1589. if theEvent.keyCode == 53 {
  1590. if self.isReadMode {
  1591. self.closeReadModel()
  1592. }
  1593. self.leftSideViewCancelSelect()
  1594. if (self.toolbarController.toolbarType.isToolMode()) {
  1595. self.toolbarController.selectItem(self.toolbarController.toolbarType.itemIdentifier())
  1596. }
  1597. }
  1598. return true
  1599. }
  1600. func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
  1601. guard let action = menuItem.action else {
  1602. isTakesEffect.pointee = false
  1603. return false
  1604. }
  1605. if (KMSystemMenu.isEditSelector(sel: action)) {
  1606. if (KMSystemMenu.Edit.deleteSelector == action) {
  1607. isTakesEffect.pointee = true
  1608. return self.listView.activeAnnotations.count > 0
  1609. } else if (KMSystemMenu.Edit.copySelector == action) {
  1610. isTakesEffect.pointee = true
  1611. return true//self.listView.canCopy()
  1612. } else if (KMSystemMenu.Edit.cutSelector == action) {
  1613. isTakesEffect.pointee = true
  1614. return self.listView.canCopy()
  1615. } else if (KMSystemMenu.Edit.pasteSelector == action) {
  1616. isTakesEffect.pointee = true
  1617. return self.listView.canPaste()
  1618. }
  1619. }
  1620. isTakesEffect.pointee = false
  1621. return false
  1622. }
  1623. //MARK: -CPDFListViewDelegate
  1624. func cPDFListView(_ pdfListView: CPDFListView, didDelete annotation: CPDFAnnotation, in pdfPage: CPDFPage) {
  1625. }
  1626. func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
  1627. self.view.window?.makeFirstResponder(self.listView)
  1628. if isRightMenu {
  1629. } else if annotations.count > 0 {
  1630. if annotations.count > 1 {
  1631. let fristAnnotation = annotations.first
  1632. var isSameAnnotation = true
  1633. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1634. for annotation in annotations {
  1635. let cunrrentClassName = NSStringFromClass(annotation.classForCoder)
  1636. if (className == "CPDFSquareAnnotation") ||
  1637. (className == "CPDFCircleAnnotation") ||
  1638. (className == "CPDFLineAnnotation") {
  1639. if (cunrrentClassName != "CPDFSquareAnnotation") &&
  1640. (cunrrentClassName != "CPDFCircleAnnotation") &&
  1641. (cunrrentClassName != "CPDFLineAnnotation") {
  1642. isSameAnnotation = false
  1643. }
  1644. } else {
  1645. if className != cunrrentClassName {
  1646. isSameAnnotation = false
  1647. }
  1648. }
  1649. }
  1650. if isSameAnnotation == false {
  1651. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1652. // self.closeRightPane()
  1653. } else {
  1654. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1655. self.openRightPane()
  1656. }
  1657. } else {
  1658. let fristAnnotation = annotations.first
  1659. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1660. if self.isReadMode {
  1661. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1662. self.closeRightPane()
  1663. } else {
  1664. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1665. if className != "CPDFStampAnnotation" &&
  1666. className != "CPDFSignatureAnnotation" &&
  1667. className != "CPDFListStampAnnotation" {
  1668. self.openRightPane()
  1669. }
  1670. }
  1671. }
  1672. } else if (annotations.count == 0){
  1673. if pdfListView.annotationType == .unkown {
  1674. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1675. self.closeRightPane()
  1676. } else {
  1677. if self.isReadMode {
  1678. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1679. self.closeRightPane()
  1680. } else {
  1681. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1682. self.openRightPane()
  1683. }
  1684. }
  1685. }
  1686. }
  1687. func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
  1688. if(annotationType == .unkown) {
  1689. // self.rightSideViewController.view.isHidden = true
  1690. self.rightSideViewController.isHidden = true
  1691. self.closeRightPane()
  1692. }
  1693. }
  1694. ///开始定位链接注释
  1695. func pdfListViewLinkDestinationStart(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1696. if self.locationPageView.superview == nil {
  1697. self.locationPageView.frame = CGRect(x: 0, y: pdfListView.frame.maxY-32, width: pdfListView.frame.width, height: 32)
  1698. pdfListView.addSubview(self.locationPageView)
  1699. }
  1700. }
  1701. ///刷新链接注释
  1702. func pdfListViewLinkDestinationEnd(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1703. if self.locationPageView.superview != nil {
  1704. self.locationPageView.removeFromSuperview()
  1705. }
  1706. if self.rightSideViewController.subViewType == .AnnotationProperts && pdfListView.annotationType == .link {
  1707. self.rightSideViewController.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1708. }
  1709. }
  1710. func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
  1711. if (listView.toolMode != CToolMode.editPDFToolMode) {
  1712. return menuItems
  1713. }
  1714. var tMenuItems = menuItems;
  1715. if(listView.isSelectEditCharRange() ||
  1716. listView.isSelecteditArea(with: point)) {
  1717. tMenuItems?.append(NSMenuItem.separator())
  1718. // tMenuItems?.append(self.fontColorMenuItem())
  1719. // tMenuItems?.append(self.fontSizeMenuItem())
  1720. }
  1721. let areas = self.listView.editingAreas() ?? []
  1722. if areas.count == 1 {
  1723. let fristAreas = areas.first
  1724. if fristAreas is CPDFEditImageArea {
  1725. self.listView.selectImageAreas = fristAreas as! CPDFEditImageArea
  1726. if self.listView.isEditImage {
  1727. tMenuItems?.removeAll()
  1728. tMenuItems?.append(self.corpImageMenuItem())
  1729. tMenuItems?.append(self.cancelCorpImageMenuItem())
  1730. tMenuItems?.append(self.restoreCorpImageMenuItem())
  1731. } else {
  1732. tMenuItems?.append(NSMenuItem.separator())
  1733. tMenuItems?.append(self.cutImageArea())
  1734. tMenuItems?.append(self.replaceImageArea())
  1735. tMenuItems?.append(self.exportImageArea())
  1736. }
  1737. } else {
  1738. tMenuItems?.swapAt(0, 1)
  1739. }
  1740. } else if areas.count == 0 {
  1741. tMenuItems?.append(NSMenuItem.separator())
  1742. tMenuItems?.append(self.addText())
  1743. tMenuItems?.append(self.addImage())
  1744. }
  1745. return tMenuItems
  1746. }
  1747. func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!) {
  1748. self.mouseRightMenuEvent = theEvent
  1749. let currentMenu : NSMenu = menu.pointee!
  1750. if (listView.toolMode == .redactToolMode) {
  1751. if (listView.activeAnnotation == nil) {
  1752. } else {
  1753. let currentPoint: NSPoint = pdfListView.convert(theEvent.locationInWindow, from: pdfListView.superview)
  1754. let currentPage = pdfListView.page(for: currentPoint, nearest: true)
  1755. // let currentPage = pdfListView.activeAnnotation.page
  1756. let pagePoint = pdfListView.convert(currentPoint, to: currentPage)
  1757. currentMenu.removeAllItems()
  1758. if (pdfListView.activeAnnotation.bounds.contains(pagePoint)) {
  1759. currentMenu.insertItem(withTitle: NSLocalizedString("Delete", comment: ""), action: #selector(redact_menuItemClick_delete), target: self, at: currentMenu.items.count)
  1760. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1761. currentMenu.insertItem(withTitle: NSLocalizedString("Properties...", comment: ""), action: #selector(redact_menuItemClick_setProperty), target: self, at: currentMenu.items.count)
  1762. currentMenu.insertItem(withTitle: NSLocalizedString("Use Current Properties as New Default", comment: ""), action: #selector(redact_menuItemClick_setCurrentPropertyToDefaultValue), target: self, at: currentMenu.items.count)
  1763. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1764. currentMenu.insertItem(withTitle: NSLocalizedString("Repeat mark across pages", comment: ""), action: #selector(redact_menuItemClick_MultiPageFlag), target: self, at: currentMenu.items.count)
  1765. currentMenu.insertItem(withTitle: NSLocalizedString("Apply Redactions", comment: ""), action: #selector(redact_menuItemClick_apply), target: self, at: currentMenu.items.count)
  1766. currentMenu.insertItem(withTitle: NSLocalizedString("Erase Redactions", comment: ""), action: #selector(redact_menuItemClick_clear), target: self, at: currentMenu.items.count)
  1767. } else {
  1768. currentMenu.insertItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(redact_menuItemClick_paste), target: self, at: currentMenu.items.count)
  1769. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1770. currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
  1771. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1772. }
  1773. }
  1774. return
  1775. }
  1776. if(listView.toolMode == .selectToolMode) {
  1777. if currentMenu.items.count > 0 {
  1778. let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
  1779. export?.submenu = self.exportMenu()
  1780. currentMenu.insertItem(export!, at: currentMenu.items.count)
  1781. let corp = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action:#selector(cropCurrentPage), target: self)
  1782. // corp?.submenu = self.cropMenu()
  1783. currentMenu.insertItem(corp!, at: currentMenu.items.count)
  1784. // MARK: 暂时拿掉 2023.04.26
  1785. // currentMenu.insertItem(self.zoomSelectionMenuItem(), at: currentMenu.items.count)
  1786. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1787. }
  1788. } else {
  1789. if listView.currentSelection != nil {
  1790. if (listView.currentSelection.string() != nil || listView.currentSelection.selectionType() == .image) {
  1791. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1792. currentMenu.insertItem(self.exportImageStampItem(), at: currentMenu.items.count-2)
  1793. } else {
  1794. var isMarkup = false
  1795. for item in self.listView.activeAnnotations {
  1796. if (item is CPDFMarkupAnnotation) {
  1797. isMarkup = true
  1798. break
  1799. }
  1800. }
  1801. if(!isMarkup) {
  1802. self.addAnnotationForStyleMenu(menu: currentMenu)
  1803. }
  1804. }
  1805. }
  1806. } else if (listView.activeAnnotation == nil) {
  1807. if(currentMenu.items.count > 2) {
  1808. currentMenu.insertItem(self.enterAnnotationStype(), at: 2)
  1809. }
  1810. if(currentMenu.items.count > 3) {
  1811. currentMenu.insertItem(self.addBookmarkMenu(), at: 4)
  1812. }
  1813. if(currentMenu.items.count > 4) {
  1814. currentMenu.insertItem(NSMenuItem.separator(), at: 5)
  1815. }
  1816. if(currentMenu.items.count > 5) {
  1817. currentMenu.insertItem(self.setAnnotationToolStype(), at: 6)
  1818. }
  1819. if (currentMenu.items.count > 6) {
  1820. currentMenu.insertItem(self.addReadModelStype(), at: 7)
  1821. }
  1822. if (currentMenu.items.count > 7 && self.isReadMode) {
  1823. currentMenu.removeItem(currentMenu.item(withTitle: "Zoom")!)
  1824. }
  1825. // if(currentMenu.items.count > 6) {
  1826. // let menuItem = NSMenuItem(title: NSLocalizedString("Automatic rolling", comment: ""), action:nil, target: self)!
  1827. // currentMenu.insertItem(menuItem, at: 6)
  1828. // }
  1829. // if(currentMenu.items.count > 7) {
  1830. // let menuItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action:nil, target: self)!
  1831. // currentMenu.insertItem(menuItem, at: 7)
  1832. // }
  1833. // if(currentMenu.items.count > 8) {
  1834. // let menuItem = NSMenuItem(title: NSLocalizedString("menuItem", comment: ""), action:nil, target: self)!
  1835. // currentMenu.insertItem(menuItem, at: 8)
  1836. // }
  1837. if !self.isReadMode {
  1838. if (currentMenu.items.count > 10) {
  1839. currentMenu.insertItem(self.addHighlightLinksStype(), at: 11)
  1840. }
  1841. }
  1842. if self.isReadMode {
  1843. } else {
  1844. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1845. currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
  1846. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1847. }
  1848. } else if listView.activeAnnotation != nil {
  1849. var type : CAnnotationType = .unkown
  1850. if listView.activeAnnotation is CPDFMarkupAnnotation {
  1851. if (listView.activeAnnotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  1852. type = .highlight
  1853. } else if (listView.activeAnnotation as! CPDFMarkupAnnotation).markupType() == .underline {
  1854. type = .underline
  1855. } else {
  1856. type = .strikeOut
  1857. }
  1858. } else if listView.activeAnnotation is CPDFInkAnnotation {
  1859. type = .ink
  1860. } else if listView.activeAnnotation is CPDFFreeTextAnnotation {
  1861. type = .freeText
  1862. } else if listView.activeAnnotation is CPDFTextAnnotation {
  1863. type = .anchored
  1864. } else if listView.activeAnnotation is CPDFCircleAnnotation {
  1865. type = .circle
  1866. } else if listView.activeAnnotation is CPDFSquareAnnotation {
  1867. type = .square
  1868. }
  1869. if ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1870. if listView.activeAnnotations.count == 1 {
  1871. currentMenu.insertItem(self.exportImageStampItem(), at: currentMenu.items.count-2)
  1872. }
  1873. }
  1874. if type != .unkown && listView.activeAnnotations.count == 1{
  1875. currentMenu.insertItem(self.setDefaultAnnotationPorpert(type: type), at: currentMenu.items.count)
  1876. }
  1877. // closeRightPane()
  1878. }
  1879. }
  1880. for item in currentMenu.items {
  1881. if (item.action == NSSelectorFromString("menuItemClick_HidenorShowNote:")) {
  1882. // 显示与隐藏注释 item action 截取
  1883. item.action = #selector(menuItemClick_HidenorShowNote)
  1884. item.target = self
  1885. break
  1886. }
  1887. }
  1888. }
  1889. func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  1890. var addRedact = false
  1891. var saveWatermark = false
  1892. var saveWatermarkType: KMSubscribeWaterMarkType = .none
  1893. for anno in annotations {
  1894. if (anno.isKind(of: CPDFRedactAnnotation.self)) {
  1895. addRedact = true
  1896. // break
  1897. } else if (anno.isKind(of: CPDFLinkAnnotation.self)) { // link 注释
  1898. saveWatermark = true
  1899. saveWatermarkType = .link
  1900. } else if (anno.isKind(of: CPDFListStampAnnotation.self)) { // 图章注释
  1901. saveWatermark = true
  1902. saveWatermarkType = .stamp
  1903. } else if (anno.isKind(of: CPDFListSignatureAnnotation.self)) { // 签名注释
  1904. saveWatermark = true
  1905. saveWatermarkType = .sign
  1906. }
  1907. }
  1908. if (saveWatermark) {
  1909. self.recordSaveWatermarkFlag(type: saveWatermarkType)
  1910. }
  1911. self.hasAddRedact = addRedact
  1912. if self.isReadMode || self.listView.toolMode == .moveToolMode {
  1913. self.listView.toolMode = .textToolMode
  1914. self.listView.annotationType = .unkown
  1915. self.toolbarController.toolbarType = .Annatiton
  1916. }
  1917. if (self.rightMouseEventing) {
  1918. self.rightMouseEventing = false
  1919. if (self.toolbarController.ignoreCurrentAnnotationTypeChange && self.listView.annotationType == .ink) {
  1920. self.listView.toolMode = .textToolMode
  1921. self.listView.annotationType = .unkown
  1922. }
  1923. }
  1924. self.toolbarController.ignoreCurrentAnnotationTypeChange = false
  1925. }
  1926. func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
  1927. if (!self.listView.isEqual(to: pdfListView)) {
  1928. return
  1929. }
  1930. if (self.listView.toolMode != .selectToolMode) {
  1931. return
  1932. }
  1933. if (self.topTipBox.isHidden || self.topTipBox.contentView?.subviews.count == 0) {
  1934. return
  1935. }
  1936. let tipView = self.topTipBox.contentView?.subviews.first
  1937. if (tipView?.isKind(of: KMCropTipView.self) == false) {
  1938. return
  1939. }
  1940. (tipView as! KMCropTipView).setString(string: "请按 Enter 键确定裁剪区域")
  1941. }
  1942. func pdfListViewKeyDowClosePanel(_ speedy: CPDFViewSidebarSpeedMode, event theEvent: NSEvent!) {
  1943. if(speedy == .right) {
  1944. self.toggleRightPane()
  1945. } else if (speedy == .left) {
  1946. self.menuItemAction_hiddenLeftSide(speedy)
  1947. }
  1948. }
  1949. func pdfListViewEventMarkupColor(with annotation: CPDFAnnotation!) -> [NSColor]! {
  1950. if (annotation.isKind(of: CPDFMarkupAnnotation.self)) {
  1951. if (annotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  1952. return KMAnnotationPropertiesColorManager.default().markHighlightColors
  1953. } else {
  1954. return KMAnnotationPropertiesColorManager.default().markOtherColors
  1955. }
  1956. } else {
  1957. return KMAnnotationPropertiesColorManager.default().markOtherColors
  1958. }
  1959. }
  1960. func pdfListViewHaveDocumentAttribute() -> Bool {
  1961. if(!self.listView.document.allowsCopying) {
  1962. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  1963. if (result == .cancel) {
  1964. return
  1965. }
  1966. self?.isSaveKeyChain = false
  1967. self?.listView.document.unlock(withPassword: password)
  1968. self?.hiddenSecureLimitTip()
  1969. }
  1970. return false
  1971. }
  1972. return true
  1973. }
  1974. func addTopTip(_ view: NSView?) {
  1975. if (Thread.isMainThread) {
  1976. if (view == nil) {
  1977. let contentView: NSView = self.topTipBox.contentView!
  1978. for subview in contentView.subviews {
  1979. subview.removeFromSuperview()
  1980. }
  1981. self.topTipBox.isHidden = true
  1982. return
  1983. }
  1984. let contentView: NSView = self.topTipBox.contentView!
  1985. for subview in contentView.subviews {
  1986. subview.removeFromSuperview()
  1987. }
  1988. self.topTipBox.isHidden = false
  1989. self.topTipBox.contentView?.addSubview(view!)
  1990. } else {
  1991. DispatchQueue.main.async {
  1992. if (view == nil) {
  1993. let contentView: NSView = self.topTipBox.contentView!
  1994. for subview in contentView.subviews {
  1995. subview.removeFromSuperview()
  1996. }
  1997. self.topTipBox.isHidden = true
  1998. return
  1999. }
  2000. let contentView: NSView = self.topTipBox.contentView!
  2001. for subview in contentView.subviews {
  2002. subview.removeFromSuperview()
  2003. }
  2004. self.topTipBox.isHidden = false
  2005. self.topTipBox.contentView?.addSubview(view!)
  2006. }
  2007. }
  2008. }
  2009. }
  2010. extension KMMainViewController: KMEditImagePropertyViewControllerDelegate {
  2011. func editImagePropertyViewControllerDidChanged(controller: KMEditImagePropertyViewController, type: KMEditImagePropertyViewControllerChangeType) {
  2012. self.isPDFTextImageEdited = true
  2013. }
  2014. }