KMMainViewController.swift 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324
  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. if self?.listView.annotationType == .addImage {
  1066. self?.listView.change([.text, .image])
  1067. }
  1068. self?.listView.annotationType = .editTextImage
  1069. self?.closeRightPane()
  1070. } else if(self?.listView.annotationType == .addImage || self!.listView.annotationType == .addText) {
  1071. if self?.listView.annotationType == .addImage ||
  1072. self?.listView.annotationType == .addText {
  1073. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1074. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1075. textItem?.isSelected = false
  1076. imageItem?.isSelected = false
  1077. }
  1078. self?.rightSideViewController.isHidden = true
  1079. self?.listView.setShouAddEdit([])
  1080. self?.listView.change([.text, .image])
  1081. self?.listView.annotationType = .editTextImage
  1082. self?.closeRightPane()
  1083. }
  1084. } else {
  1085. if self?.listView.annotationType == .addImage ||
  1086. self?.listView.annotationType == .addText {
  1087. let textItem = self?.toolbarController.findItem(KMToolbarAddTextEditPDFItemIdentifier)
  1088. let imageItem = self?.toolbarController.findItem(KMToolbarAddImageEditPDFItemIdentifier)
  1089. textItem?.isSelected = false
  1090. imageItem?.isSelected = false
  1091. }
  1092. }
  1093. }
  1094. }
  1095. }
  1096. return event
  1097. }
  1098. }
  1099. func removeKeyEventMonitor() {
  1100. if (self.keyEventMonitor != nil) {
  1101. KMPrint("removeKeyEventMonitor 已移除事件监听")
  1102. NSEvent.removeMonitor(self.keyEventMonitor as Any)
  1103. self.keyEventMonitor = nil
  1104. }
  1105. }
  1106. private func removeEventMonitor() {
  1107. if (self.eventMonitor != nil) {
  1108. KMPrint("已移除事件监听")
  1109. NSEvent.removeMonitor(self.eventMonitor as Any)
  1110. self.eventMonitor = nil
  1111. }
  1112. }
  1113. // MARK: -
  1114. // MARK: Tools
  1115. func pdfViewCanHorizontalScroll() -> Bool {
  1116. let scroll = self.listView.scroll()
  1117. if (scroll == nil) {
  1118. return false
  1119. }
  1120. return scroll?.horizontalScroller?.isHidden == nil ? false : !(scroll!.horizontalScroller!.isHidden)
  1121. }
  1122. func pdfViewCanVerticalScroll() -> Bool {
  1123. let scroll = self.listView.scroll()
  1124. if (scroll == nil) {
  1125. return false
  1126. }
  1127. return scroll?.verticalScroller?.isHidden == nil ? false : !(scroll!.verticalScroller!.isHidden)
  1128. }
  1129. // MARK: - Public Methods
  1130. // 清理数据 [eg. 通知]
  1131. public func clearData() {
  1132. self.removeNotifications()
  1133. if (self.listView.spellingTag() > 0) {
  1134. NSSpellChecker.shared.closeSpellDocument(withTag: self.listView.spellingTag())
  1135. }
  1136. }
  1137. public func clearSecureOptions() {
  1138. self._secureOptions = nil
  1139. }
  1140. public func recordRemoveSecureFlag() {
  1141. self._removeSecureFlag = true
  1142. self.clearSecureOptions()
  1143. self.recordIsPDFDocumentEdited(type: .removePassword)
  1144. self._needSave = true
  1145. }
  1146. public func clearRemoveSecureFlag() {
  1147. self._removeSecureFlag = false
  1148. }
  1149. public func recordSaveWatermarkFlag(type: KMSubscribeWaterMarkType = .none) {
  1150. km_synchronized(self) {
  1151. self._saveWatermarkFlag = true
  1152. }
  1153. if let _document = self.myDocument as? KMMainDocument {
  1154. _document.recordTrackEvent(type: type)
  1155. }
  1156. }
  1157. public func clearSaveWatermarkFlag() {
  1158. km_synchronized(self) {
  1159. self._saveWatermarkFlag = false
  1160. }
  1161. }
  1162. public func recordIsPDFDocumentEdited(type: KMSubscribeWaterMarkType = .none) {
  1163. km_synchronized(self) {
  1164. self._isPDFDocumentEdited = true
  1165. if let _document = self.myDocument {
  1166. KMTools.setDocumentEditedState(document: _document)
  1167. }
  1168. }
  1169. }
  1170. public func clearIsPDFDocumentEdited() {
  1171. km_synchronized(self) {
  1172. self._isPDFDocumentEdited = false
  1173. }
  1174. }
  1175. // MARK: - Noti Actions
  1176. internal func documentDidUnlockNotification(_ sender: Notification) {
  1177. if (self.listView.document != nil && self.listView.document.isEqual(to: sender.object)) {
  1178. if (self.myDocument == nil) {
  1179. return
  1180. }
  1181. if (self.listView.document.allowsPrinting && self.listView.document.allowsCopying) {
  1182. self.hiddenSecureLimitTip()
  1183. }
  1184. if ((self.myDocument as! KMMainDocument).isUnlockFromKeychain || self.isSaveKeyChain == false) {
  1185. return
  1186. }
  1187. let type = KMPreferenceManager.shared.savePasswordType
  1188. if (type == .never) {
  1189. return
  1190. }
  1191. if (type == .always) {
  1192. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1193. return
  1194. }
  1195. // 保存到钥匙串
  1196. let alert = NSAlert()
  1197. alert.messageText = NSLocalizedString("Remember Password?", comment: "")
  1198. alert.informativeText = NSLocalizedString("Do you want to save this password in your Keychain?", comment: "")
  1199. alert.addButton(withTitle: NSLocalizedString("Yes", comment: ""))
  1200. alert.addButton(withTitle: NSLocalizedString("No", comment: ""))
  1201. if (alert.runModal() == .alertFirstButtonReturn) { // 保存密码
  1202. self.myDocument?.savePasswordInKeychain(self.listView.document.password, self.listView.document)
  1203. return
  1204. }
  1205. }
  1206. }
  1207. internal func applicationWillTerminateNotification(_ sender: Notification) {
  1208. self.savePageNumberIfNeed()
  1209. self.saveDocument()
  1210. }
  1211. func KMPDFViewCurrentPageDidChangedNotification(_ sender: Notification) {
  1212. if self.isReadMode {
  1213. self.readModelView.currentPageIndex = self.listView.currentPageIndex
  1214. }
  1215. //刷新向前向后按钮
  1216. self.updateBackAndForwardButtonState()
  1217. }
  1218. func CPDFDocumentPageCountChangedNotification(_ sender: Notification) {
  1219. if self.isReadMode {
  1220. self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
  1221. }
  1222. //刷新向前向后按钮
  1223. self.updateBackAndForwardButtonState()
  1224. }
  1225. func CEditPDFToolModeChangeStateUnkownNotification(_ sender: Notification) {
  1226. var editSelectd = false
  1227. if (self.listView.annotationType == .addText || self.listView.annotationType == .addImage) && self.listView.toolMode == .editPDFToolMode {
  1228. editSelectd = true
  1229. }
  1230. if self.listView.toolMode == .editPDFToolMode {
  1231. if editSelectd {
  1232. self.toolbarController.cancelSelected(KMToolbarAddTextEditPDFItemIdentifier)
  1233. }
  1234. }
  1235. }
  1236. //MARK: - PDFListViewDelegate
  1237. func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  1238. // KMPrint("pdfViewDocumentDidLoaded")
  1239. self.removeBackgroundMaskView()
  1240. if (!self.listView.document!.allowsCopying || !self.listView.document!.allowsPrinting) {
  1241. self.showSecureLimitTip()
  1242. }
  1243. if (self._documentFirstLoad) {
  1244. self.checkShouldAutoOpenLeftVC()
  1245. if (KMPreferenceManager.shared.openLastUnlockedDocumentWhenAppStart) {
  1246. let pageNumber = KMPreferenceManager.shared.getPageNumber(forKey: self.listView.document.documentURL.path)
  1247. let pageScale = KMPreferenceManager.shared.getPageScale(forKey: self.listView.document.documentURL.path)
  1248. if (pageScale != nil) {
  1249. self.listView.scaleFactor = CGFloat(pageScale!)
  1250. }
  1251. if (pageNumber != nil && pageNumber! >= 0 && pageNumber! < self.listView.document.pageCount) {
  1252. self.listView.go(toPageIndex: pageNumber!, animated: false)
  1253. } else {
  1254. self._goToFirstPageForFristAppear()
  1255. }
  1256. } else {
  1257. self._goToFirstPageForFristAppear()
  1258. }
  1259. self._documentFirstLoad = false
  1260. }
  1261. let notification = Notification(name: Notification.Name(rawValue: "pdfViewDocumentDidLoaded"))
  1262. self.preferenceDidChangeNotification(notification:notification)
  1263. let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) as? NSNumber ?? NSNumber(value: panelWidth + functionWidth)
  1264. let rightWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) as? NSNumber ?? NSNumber(value: defaultRightWidth)
  1265. applyLeftSideWidth(leftWidthNumber.doubleValue, rightSideWidth: rightWidthNumber.doubleValue)
  1266. self.updatePageIndicatoreType()
  1267. }
  1268. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  1269. self.updatePageIndicatoreType()
  1270. NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: self.document)
  1271. // KMPrint("KMPDFViewCurrentPageDidChanged")
  1272. }
  1273. func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
  1274. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor * 100))%"
  1275. self.updateZoomInOutButtonState()
  1276. // KMPrint("pdfViewScaleDidChanged")
  1277. }
  1278. func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
  1279. if let urlString = url, urlString == kKMPurchaseProductURLString {
  1280. //跳转订阅比较表
  1281. let _ = KMComparativeTableViewController.show(window: NSApp.mainWindow ?? NSWindow())
  1282. return
  1283. }
  1284. KMTools.openURL(urlString: url)
  1285. }
  1286. func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  1287. KMPrint("pdfViewPerformURL")
  1288. }
  1289. func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  1290. KMPrint("pdfViewPerformPrint")
  1291. }
  1292. func pdfViewPerformGo(toPage pdfView: CPDFView!) {
  1293. KMPrint("pdfViewPerformGo")
  1294. }
  1295. func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
  1296. KMPrint("pdfViewOpenPDF")
  1297. }
  1298. func pdfViewPerformReset(_ pdfView: CPDFView!) {
  1299. KMPrint("pdfViewPerformReset")
  1300. }
  1301. func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
  1302. KMPrint("pdfViewEditingBlockDidChanged")
  1303. }
  1304. func pdfViewAsBookBookmark() -> NSImage! {
  1305. return NSImage(named: "KMImageNameUXIconPDFViewBookMark")!
  1306. }
  1307. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  1308. self.recordSaveWatermarkFlag()
  1309. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText {
  1310. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  1311. self.rightSideViewController.eidtPDFTextProperty.updateTextTextPresuppositionState()
  1312. }
  1313. }
  1314. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  1315. let areas = self.listView.editingAreas()
  1316. if areas == nil || areas?.count ?? 0 == 0 {
  1317. if self.listView.toolMode == .editPDFToolMode {
  1318. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  1319. if self.listView.isEditImage {
  1320. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1321. } else {
  1322. // if self.listView.annotationType == .addImage {
  1323. // self.closeRightPane()
  1324. // }
  1325. if self.listView.annotationType == .addImage {
  1326. if self.rightSideViewController.eidtPDFImageProperty != nil {
  1327. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  1328. }
  1329. }
  1330. // self.openRightPane()
  1331. }
  1332. } else {
  1333. self.closeRightPane()
  1334. }
  1335. } else {
  1336. self.rightSideViewController.isHidden = true
  1337. self.closeRightPane()
  1338. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1339. self.rightSideViewController.eidtPDFTextProperty.initData()
  1340. }
  1341. }
  1342. if self.listView.isEdited() {
  1343. self.recordIsPDFDocumentEdited(type: .editText)
  1344. }
  1345. if self.listView.annotationType != .addText {
  1346. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  1347. }
  1348. return
  1349. }
  1350. self.isPDFTextImageEdited = true
  1351. if (self.listView.annotationType == .addImage) && areas!.count > 0 {
  1352. var isImageArea = false
  1353. for i in 0 ... areas!.count-1 {
  1354. if areas![i] is CPDFEditImageArea {
  1355. isImageArea = true
  1356. }
  1357. }
  1358. if isImageArea {
  1359. // self.rightSideViewController.view.isHidden = false
  1360. self.rightSideViewController.isHidden = false
  1361. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddImage {
  1362. self.rightSideViewController.subViewType = .EditPDFAddImage
  1363. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  1364. }
  1365. self.openRightPane()
  1366. } else {
  1367. // self.rightSideViewController.view.isHidden = true
  1368. self.rightSideViewController.isHidden = true
  1369. self.closeRightPane()
  1370. }
  1371. } else if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1372. // self.rightSideViewController.view.isHidden = false
  1373. self.rightSideViewController.isHidden = false
  1374. if self.listView.editingSelectionString().count != 0 {
  1375. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  1376. } else {
  1377. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1378. }
  1379. self.openRightPane()
  1380. } else {
  1381. var textsAreas : [CPDFEditTextArea] = []
  1382. var imagesAreas : [CPDFEditImageArea] = []
  1383. if self.listView.editingAreas()?.count ?? 0 < 1 {
  1384. return
  1385. }
  1386. for i in 0 ... areas!.count-1 {
  1387. if areas![i] is CPDFEditTextArea {
  1388. textsAreas.append(areas![i] as! CPDFEditTextArea)
  1389. }
  1390. if areas![i] is CPDFEditImageArea {
  1391. imagesAreas.append(areas![i] as! CPDFEditImageArea)
  1392. }
  1393. }
  1394. if textsAreas.count > 0 && textsAreas.count == areas!.count {
  1395. // self.rightSideViewController.view.isHidden = false
  1396. self.rightSideViewController.isHidden = false
  1397. self.rightSideViewController.subViewType = .EditPDFAddText
  1398. self.rightSideViewController.eidtPDFTextProperty?.reloadData()
  1399. self.openRightPane()
  1400. } else if imagesAreas.count > 0 {
  1401. // self.rightSideViewController.view.isHidden = false
  1402. self.rightSideViewController.isHidden = false
  1403. self.rightSideViewController.subViewType = .EditPDFAddImage
  1404. self.rightSideViewController.eidtPDFImageProperty?.reloadData()
  1405. self.openRightPane()
  1406. }
  1407. }
  1408. if self.listView.isEdited() {
  1409. self.recordIsPDFDocumentEdited(type: .editText)
  1410. if self.listView.annotationType != .addText {
  1411. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  1412. }
  1413. }
  1414. }
  1415. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  1416. self.recordSaveWatermarkFlag()
  1417. if editArea != nil && (editArea is CPDFEditImageArea){
  1418. self.listView.cropAreas = editArea as? CPDFEditImageArea
  1419. }
  1420. }
  1421. //编辑PDF 创建图片区域回调
  1422. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1423. self.recordSaveWatermarkFlag(type: .editImage)
  1424. if self.listView.isEditImage {
  1425. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1426. } else {
  1427. let panel = NSOpenPanel()
  1428. panel.allowsMultipleSelection = false
  1429. panel.allowedFileTypes = ["png","jpg"]
  1430. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  1431. if response == .OK {
  1432. var filePath = panel.url?.path
  1433. var image = NSImage.init(contentsOf: panel.url!)
  1434. //图片自适应范围
  1435. if image != nil {
  1436. var imageRect = rect
  1437. let imageSize = image!.size
  1438. var previewSize = rect.size
  1439. var isChangeSize = false
  1440. if previewSize.width == 0 && previewSize.height == 0 {
  1441. previewSize = CGSize(width: 500, height: 500)
  1442. isChangeSize = true
  1443. }
  1444. let scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  1445. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  1446. if isChangeSize {
  1447. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  1448. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  1449. } else {
  1450. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  1451. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  1452. }
  1453. imageRect.size = newSize
  1454. let limitWidth = 1920.0
  1455. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  1456. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  1457. targetSize: CGSize(width: limitWidth, height: limitWidth),
  1458. maxSizeInBytes: 1024 * 1024 * 5,
  1459. targetCompression: 1.0)
  1460. }
  1461. //自适应page
  1462. let pageRect = self.listView.currentPage().bounds
  1463. if imageRect.width > pageRect.width ||
  1464. imageRect.height > pageRect.height {
  1465. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  1466. imageRect = CGRect(x: imageRect.origin.x,
  1467. y: imageRect.origin.y,
  1468. width: imageRect.width * pageScale,
  1469. height: imageRect.height * pageScale)
  1470. }
  1471. if imageRect.origin.x < 0 {
  1472. imageRect.origin.x = 5
  1473. }
  1474. if imageRect.origin.y < 0 {
  1475. imageRect.origin.y = 5
  1476. }
  1477. if imageRect.origin.x + imageRect.width > pageRect.width ||
  1478. imageRect.origin.y + imageRect.height > pageRect.height {
  1479. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  1480. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  1481. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  1482. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  1483. }
  1484. DispatchQueue.main.async {
  1485. self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  1486. self.isPDFTextImageEdited = true
  1487. self.recordIsPDFDocumentEdited(type: .editImage)
  1488. // self.asyncSaveDocument { params in
  1489. //
  1490. // }
  1491. }
  1492. }
  1493. }
  1494. }
  1495. }
  1496. }
  1497. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1498. // print(rect)
  1499. var newrect = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height)
  1500. if __CGSizeEqualToSize(rect.size, CGSize.zero) {
  1501. newrect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  1502. } else {
  1503. newrect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  1504. }
  1505. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  1506. let fontName = KMEditPDFTextManager.manager.fetchFontName(fontName: model.fontName)
  1507. let fontSize = model.fontSize
  1508. let fontColor = model.color
  1509. let fontAlign = model.alignment
  1510. let fontStyle = KMEditPDFTextManager.manager.fetchFontStyle(fontName: model.fontName)
  1511. NSColorPanel.shared.color = fontColor
  1512. let font = KMEditPDFTextManager.manager.fetchFont(fontName: fontName, style: fontStyle, size: fontSize)
  1513. let style = NSMutableParagraphStyle()
  1514. style.alignment = fontAlign
  1515. let attributes = [NSAttributedString.Key.font:font, NSAttributedString.Key.foregroundColor:fontColor,NSAttributedString.Key.paragraphStyle:style] as [NSAttributedString.Key : Any]
  1516. self.listView.createEmptyStringBounds(newrect,withAttributes: attributes as [NSAttributedString.Key : Any], page: pdfView.currentPage())
  1517. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1518. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1519. }
  1520. // self.asyncSaveDocument { params in
  1521. //
  1522. // }
  1523. self.recordSaveWatermarkFlag(type: .editText)
  1524. }
  1525. // func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
  1526. // debugPrint("pdfViewEditingDoubleClick")
  1527. // }
  1528. func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
  1529. debugPrint("pdfViewEditingOperationDidChanged")
  1530. if self.listView.isEdited() {
  1531. self.recordSaveWatermarkFlag()
  1532. }
  1533. }
  1534. // func pdfListViewEditAnnotation(_ pdfListView: CPDFListView!, for anotation: CPDFAnnotation!) {
  1535. // debugPrint("pdfListViewEditAnnotation")
  1536. // }
  1537. func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
  1538. let command = theEvent.modifierFlags.contains(.command)
  1539. let control = theEvent.modifierFlags.contains(.control)
  1540. KMPrint(theEvent.keyCode)
  1541. if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
  1542. self.menuItemBookMarkClick_add(sender: NSMenuItem())
  1543. return false
  1544. } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
  1545. return false
  1546. } else if (theEvent.keyCode == 123) { // 向左
  1547. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1548. return false
  1549. } else {
  1550. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  1551. self.listView.goToPreviousPage(nil)
  1552. return false
  1553. }
  1554. }
  1555. } else if (theEvent.keyCode == 126) { // 向上
  1556. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1557. return false
  1558. } else {
  1559. if (self.listView.isContinousScroll()) {
  1560. return true
  1561. }
  1562. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  1563. self.listView.goToPreviousPage(nil)
  1564. return false
  1565. }
  1566. }
  1567. } else if (theEvent.keyCode == 124) { // 向右
  1568. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1569. return false
  1570. } else {
  1571. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  1572. self.listView.goToNextPage(nil)
  1573. return false
  1574. }
  1575. }
  1576. } else if (theEvent.keyCode == 125) { // 向下
  1577. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1578. return false
  1579. } else {
  1580. if (self.listView.isContinousScroll()) {
  1581. return true
  1582. }
  1583. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  1584. self.listView.goToNextPage(nil)
  1585. return false
  1586. }
  1587. }
  1588. } else if (theEvent.keyCode == 36) {
  1589. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  1590. if self.listView.isEditImage {
  1591. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1592. }
  1593. }
  1594. }
  1595. if theEvent.keyCode == 53 {
  1596. if self.isReadMode {
  1597. self.closeReadModel()
  1598. }
  1599. self.leftSideViewCancelSelect()
  1600. if (self.toolbarController.toolbarType.isToolMode()) {
  1601. self.toolbarController.selectItem(self.toolbarController.toolbarType.itemIdentifier())
  1602. }
  1603. }
  1604. return true
  1605. }
  1606. func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
  1607. guard let action = menuItem.action else {
  1608. isTakesEffect.pointee = false
  1609. return false
  1610. }
  1611. if (KMSystemMenu.isEditSelector(sel: action)) {
  1612. if (KMSystemMenu.Edit.deleteSelector == action) {
  1613. isTakesEffect.pointee = true
  1614. return self.listView.activeAnnotations.count > 0
  1615. } else if (KMSystemMenu.Edit.copySelector == action) {
  1616. isTakesEffect.pointee = true
  1617. return true//self.listView.canCopy()
  1618. } else if (KMSystemMenu.Edit.cutSelector == action) {
  1619. isTakesEffect.pointee = true
  1620. return self.listView.canCopy()
  1621. } else if (KMSystemMenu.Edit.pasteSelector == action) {
  1622. isTakesEffect.pointee = true
  1623. return self.listView.canPaste()
  1624. }
  1625. }
  1626. isTakesEffect.pointee = false
  1627. return false
  1628. }
  1629. //MARK: -CPDFListViewDelegate
  1630. func cPDFListView(_ pdfListView: CPDFListView, didDelete annotation: CPDFAnnotation, in pdfPage: CPDFPage) {
  1631. }
  1632. func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
  1633. self.view.window?.makeFirstResponder(self.listView)
  1634. if isRightMenu {
  1635. } else if annotations.count > 0 {
  1636. if annotations.count > 1 {
  1637. let fristAnnotation = annotations.first
  1638. var isSameAnnotation = true
  1639. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1640. for annotation in annotations {
  1641. let cunrrentClassName = NSStringFromClass(annotation.classForCoder)
  1642. if (className == "CPDFSquareAnnotation") ||
  1643. (className == "CPDFCircleAnnotation") ||
  1644. (className == "CPDFLineAnnotation") {
  1645. if (cunrrentClassName != "CPDFSquareAnnotation") &&
  1646. (cunrrentClassName != "CPDFCircleAnnotation") &&
  1647. (cunrrentClassName != "CPDFLineAnnotation") {
  1648. isSameAnnotation = false
  1649. }
  1650. } else {
  1651. if className != cunrrentClassName {
  1652. isSameAnnotation = false
  1653. }
  1654. }
  1655. }
  1656. if isSameAnnotation == false {
  1657. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1658. // self.closeRightPane()
  1659. } else {
  1660. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1661. self.openRightPane()
  1662. }
  1663. } else {
  1664. let fristAnnotation = annotations.first
  1665. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1666. if self.isReadMode {
  1667. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1668. self.closeRightPane()
  1669. } else {
  1670. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1671. if className != "CPDFStampAnnotation" &&
  1672. className != "CPDFSignatureAnnotation" &&
  1673. className != "CPDFListStampAnnotation" {
  1674. self.openRightPane()
  1675. }
  1676. }
  1677. }
  1678. } else if (annotations.count == 0){
  1679. if pdfListView.annotationType == .unkown {
  1680. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1681. self.closeRightPane()
  1682. } else {
  1683. if self.isReadMode {
  1684. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1685. self.closeRightPane()
  1686. } else {
  1687. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1688. self.openRightPane()
  1689. }
  1690. }
  1691. }
  1692. }
  1693. func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
  1694. if(annotationType == .unkown) {
  1695. // self.rightSideViewController.view.isHidden = true
  1696. self.rightSideViewController.isHidden = true
  1697. self.closeRightPane()
  1698. }
  1699. }
  1700. ///开始定位链接注释
  1701. func pdfListViewLinkDestinationStart(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1702. if self.locationPageView.superview == nil {
  1703. self.locationPageView.frame = CGRect(x: 0, y: pdfListView.frame.maxY-32, width: pdfListView.frame.width, height: 32)
  1704. pdfListView.addSubview(self.locationPageView)
  1705. }
  1706. }
  1707. ///刷新链接注释
  1708. func pdfListViewLinkDestinationEnd(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1709. if self.locationPageView.superview != nil {
  1710. self.locationPageView.removeFromSuperview()
  1711. }
  1712. if self.rightSideViewController.subViewType == .AnnotationProperts && pdfListView.annotationType == .link {
  1713. self.rightSideViewController.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1714. }
  1715. }
  1716. func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
  1717. if (listView.toolMode != CToolMode.editPDFToolMode) {
  1718. return menuItems
  1719. }
  1720. var tMenuItems = menuItems;
  1721. if(listView.isSelectEditCharRange() ||
  1722. listView.isSelecteditArea(with: point)) {
  1723. tMenuItems?.append(NSMenuItem.separator())
  1724. // tMenuItems?.append(self.fontColorMenuItem())
  1725. // tMenuItems?.append(self.fontSizeMenuItem())
  1726. }
  1727. let areas = self.listView.editingAreas() ?? []
  1728. if areas.count == 1 {
  1729. let fristAreas = areas.first
  1730. if fristAreas is CPDFEditImageArea {
  1731. self.listView.selectImageAreas = fristAreas as! CPDFEditImageArea
  1732. if self.listView.isEditImage {
  1733. tMenuItems?.removeAll()
  1734. tMenuItems?.append(self.corpImageMenuItem())
  1735. tMenuItems?.append(self.cancelCorpImageMenuItem())
  1736. tMenuItems?.append(self.restoreCorpImageMenuItem())
  1737. } else {
  1738. tMenuItems?.append(NSMenuItem.separator())
  1739. tMenuItems?.append(self.cutImageArea())
  1740. tMenuItems?.append(self.replaceImageArea())
  1741. tMenuItems?.append(self.exportImageArea())
  1742. }
  1743. } else {
  1744. tMenuItems?.swapAt(0, 1)
  1745. }
  1746. } else if areas.count == 0 {
  1747. tMenuItems?.append(NSMenuItem.separator())
  1748. tMenuItems?.append(self.addText())
  1749. tMenuItems?.append(self.addImage())
  1750. }
  1751. return tMenuItems
  1752. }
  1753. func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!) {
  1754. self.mouseRightMenuEvent = theEvent
  1755. let currentMenu : NSMenu = menu.pointee!
  1756. if (listView.toolMode == .redactToolMode) {
  1757. if (listView.activeAnnotation == nil) {
  1758. } else {
  1759. let currentPoint: NSPoint = pdfListView.convert(theEvent.locationInWindow, from: pdfListView.superview)
  1760. let currentPage = pdfListView.page(for: currentPoint, nearest: true)
  1761. // let currentPage = pdfListView.activeAnnotation.page
  1762. let pagePoint = pdfListView.convert(currentPoint, to: currentPage)
  1763. currentMenu.removeAllItems()
  1764. if (pdfListView.activeAnnotation.bounds.contains(pagePoint)) {
  1765. currentMenu.insertItem(withTitle: NSLocalizedString("Delete", comment: ""), action: #selector(redact_menuItemClick_delete), target: self, at: currentMenu.items.count)
  1766. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1767. currentMenu.insertItem(withTitle: NSLocalizedString("Properties...", comment: ""), action: #selector(redact_menuItemClick_setProperty), target: self, at: currentMenu.items.count)
  1768. currentMenu.insertItem(withTitle: NSLocalizedString("Use Current Properties as New Default", comment: ""), action: #selector(redact_menuItemClick_setCurrentPropertyToDefaultValue), target: self, at: currentMenu.items.count)
  1769. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1770. currentMenu.insertItem(withTitle: NSLocalizedString("Repeat mark across pages", comment: ""), action: #selector(redact_menuItemClick_MultiPageFlag), target: self, at: currentMenu.items.count)
  1771. currentMenu.insertItem(withTitle: NSLocalizedString("Apply Redactions", comment: ""), action: #selector(redact_menuItemClick_apply), target: self, at: currentMenu.items.count)
  1772. currentMenu.insertItem(withTitle: NSLocalizedString("Erase Redactions", comment: ""), action: #selector(redact_menuItemClick_clear), target: self, at: currentMenu.items.count)
  1773. } else {
  1774. currentMenu.insertItem(withTitle: NSLocalizedString("Paste", comment: ""), action: #selector(redact_menuItemClick_paste), target: self, at: currentMenu.items.count)
  1775. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1776. currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
  1777. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1778. }
  1779. }
  1780. return
  1781. }
  1782. if(listView.toolMode == .selectToolMode) {
  1783. if currentMenu.items.count > 0 {
  1784. let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
  1785. export?.submenu = self.exportMenu()
  1786. currentMenu.insertItem(export!, at: currentMenu.items.count)
  1787. let corp = NSMenuItem(title: NSLocalizedString("Crop", comment: ""), action:#selector(cropCurrentPage), target: self)
  1788. // corp?.submenu = self.cropMenu()
  1789. currentMenu.insertItem(corp!, at: currentMenu.items.count)
  1790. // MARK: 暂时拿掉 2023.04.26
  1791. // currentMenu.insertItem(self.zoomSelectionMenuItem(), at: currentMenu.items.count)
  1792. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1793. }
  1794. } else {
  1795. if listView.currentSelection != nil {
  1796. if (listView.currentSelection.string() != nil || listView.currentSelection.selectionType() == .image) {
  1797. if listView.activeAnnotation != nil && ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1798. currentMenu.insertItem(self.exportImageStampItem(), at: currentMenu.items.count-2)
  1799. } else {
  1800. var isMarkup = false
  1801. for item in self.listView.activeAnnotations {
  1802. if (item is CPDFMarkupAnnotation) {
  1803. isMarkup = true
  1804. break
  1805. }
  1806. }
  1807. if(!isMarkup) {
  1808. self.addAnnotationForStyleMenu(menu: currentMenu)
  1809. }
  1810. }
  1811. }
  1812. } else if (listView.activeAnnotation == nil) {
  1813. if(currentMenu.items.count > 2) {
  1814. currentMenu.insertItem(self.enterAnnotationStype(), at: 2)
  1815. }
  1816. if(currentMenu.items.count > 3) {
  1817. currentMenu.insertItem(self.addBookmarkMenu(), at: 4)
  1818. }
  1819. if(currentMenu.items.count > 4) {
  1820. currentMenu.insertItem(NSMenuItem.separator(), at: 5)
  1821. }
  1822. if(currentMenu.items.count > 5) {
  1823. currentMenu.insertItem(self.setAnnotationToolStype(), at: 6)
  1824. }
  1825. if (currentMenu.items.count > 6) {
  1826. currentMenu.insertItem(self.addReadModelStype(), at: 7)
  1827. }
  1828. if (currentMenu.items.count > 7 && self.isReadMode) {
  1829. currentMenu.removeItem(currentMenu.item(withTitle: "Zoom")!)
  1830. }
  1831. // if(currentMenu.items.count > 6) {
  1832. // let menuItem = NSMenuItem(title: NSLocalizedString("Automatic rolling", comment: ""), action:nil, target: self)!
  1833. // currentMenu.insertItem(menuItem, at: 6)
  1834. // }
  1835. // if(currentMenu.items.count > 7) {
  1836. // let menuItem = NSMenuItem(title: NSLocalizedString("TTS", comment: ""), action:nil, target: self)!
  1837. // currentMenu.insertItem(menuItem, at: 7)
  1838. // }
  1839. // if(currentMenu.items.count > 8) {
  1840. // let menuItem = NSMenuItem(title: NSLocalizedString("menuItem", comment: ""), action:nil, target: self)!
  1841. // currentMenu.insertItem(menuItem, at: 8)
  1842. // }
  1843. if !self.isReadMode {
  1844. if (currentMenu.items.count > 10) {
  1845. currentMenu.insertItem(self.addHighlightLinksStype(), at: 11)
  1846. }
  1847. }
  1848. if self.isReadMode {
  1849. } else {
  1850. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1851. currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
  1852. currentMenu.insertItem(self.printingMenu(), at: currentMenu.items.count)
  1853. }
  1854. } else if listView.activeAnnotation != nil {
  1855. var type : CAnnotationType = .unkown
  1856. if listView.activeAnnotation is CPDFMarkupAnnotation {
  1857. if (listView.activeAnnotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  1858. type = .highlight
  1859. } else if (listView.activeAnnotation as! CPDFMarkupAnnotation).markupType() == .underline {
  1860. type = .underline
  1861. } else {
  1862. type = .strikeOut
  1863. }
  1864. } else if listView.activeAnnotation is CPDFInkAnnotation {
  1865. type = .ink
  1866. } else if listView.activeAnnotation is CPDFFreeTextAnnotation {
  1867. type = .freeText
  1868. } else if listView.activeAnnotation is CPDFTextAnnotation {
  1869. type = .anchored
  1870. } else if listView.activeAnnotation is CPDFCircleAnnotation {
  1871. type = .circle
  1872. } else if listView.activeAnnotation is CPDFSquareAnnotation {
  1873. type = .square
  1874. }
  1875. if ((listView.activeAnnotation is CPDFStampAnnotation) || (listView.activeAnnotation is CPDFSignatureAnnotation)) {
  1876. if listView.activeAnnotations.count == 1 {
  1877. currentMenu.insertItem(self.exportImageStampItem(), at: currentMenu.items.count-2)
  1878. }
  1879. }
  1880. if type != .unkown && listView.activeAnnotations.count == 1{
  1881. currentMenu.insertItem(self.setDefaultAnnotationPorpert(type: type), at: currentMenu.items.count)
  1882. }
  1883. // closeRightPane()
  1884. }
  1885. }
  1886. for item in currentMenu.items {
  1887. if (item.action == NSSelectorFromString("menuItemClick_HidenorShowNote:")) {
  1888. // 显示与隐藏注释 item action 截取
  1889. item.action = #selector(menuItemClick_HidenorShowNote)
  1890. item.target = self
  1891. break
  1892. }
  1893. }
  1894. }
  1895. func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  1896. var addRedact = false
  1897. var saveWatermark = false
  1898. var saveWatermarkType: KMSubscribeWaterMarkType = .none
  1899. for anno in annotations {
  1900. if (anno.isKind(of: CPDFRedactAnnotation.self)) {
  1901. addRedact = true
  1902. // break
  1903. } else if (anno.isKind(of: CPDFLinkAnnotation.self)) { // link 注释
  1904. saveWatermark = true
  1905. saveWatermarkType = .link
  1906. } else if (anno.isKind(of: CPDFListStampAnnotation.self)) { // 图章注释
  1907. saveWatermark = true
  1908. saveWatermarkType = .stamp
  1909. } else if (anno.isKind(of: CPDFListSignatureAnnotation.self)) { // 签名注释
  1910. saveWatermark = true
  1911. saveWatermarkType = .sign
  1912. }
  1913. }
  1914. if (saveWatermark) {
  1915. self.recordSaveWatermarkFlag(type: saveWatermarkType)
  1916. }
  1917. self.hasAddRedact = addRedact
  1918. if self.isReadMode || self.listView.toolMode == .moveToolMode {
  1919. self.listView.toolMode = .textToolMode
  1920. self.listView.annotationType = .unkown
  1921. self.toolbarController.toolbarType = .Annatiton
  1922. }
  1923. if (self.rightMouseEventing) {
  1924. self.rightMouseEventing = false
  1925. if (self.toolbarController.ignoreCurrentAnnotationTypeChange && self.listView.annotationType == .ink) {
  1926. self.listView.toolMode = .textToolMode
  1927. self.listView.annotationType = .unkown
  1928. }
  1929. }
  1930. self.toolbarController.ignoreCurrentAnnotationTypeChange = false
  1931. }
  1932. func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
  1933. if (!self.listView.isEqual(to: pdfListView)) {
  1934. return
  1935. }
  1936. if (self.listView.toolMode != .selectToolMode) {
  1937. return
  1938. }
  1939. if (self.topTipBox.isHidden || self.topTipBox.contentView?.subviews.count == 0) {
  1940. return
  1941. }
  1942. let tipView = self.topTipBox.contentView?.subviews.first
  1943. if (tipView?.isKind(of: KMCropTipView.self) == false) {
  1944. return
  1945. }
  1946. (tipView as! KMCropTipView).setString(string: "请按 Enter 键确定裁剪区域")
  1947. }
  1948. func pdfListViewKeyDowClosePanel(_ speedy: CPDFViewSidebarSpeedMode, event theEvent: NSEvent!) {
  1949. if(speedy == .right) {
  1950. self.toggleRightPane()
  1951. } else if (speedy == .left) {
  1952. self.menuItemAction_hiddenLeftSide(speedy)
  1953. }
  1954. }
  1955. func pdfListViewEventMarkupColor(with annotation: CPDFAnnotation!) -> [NSColor]! {
  1956. if (annotation.isKind(of: CPDFMarkupAnnotation.self)) {
  1957. if (annotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  1958. return KMAnnotationPropertiesColorManager.default().markHighlightColors
  1959. } else {
  1960. return KMAnnotationPropertiesColorManager.default().markOtherColors
  1961. }
  1962. } else {
  1963. return KMAnnotationPropertiesColorManager.default().markOtherColors
  1964. }
  1965. }
  1966. func pdfListViewHaveDocumentAttribute() -> Bool {
  1967. if(!self.listView.document.allowsCopying) {
  1968. KMPasswordInputWindow.openWindow(window: self.view.window!, type: .owner, url: self.listView.document.documentURL) { [weak self] result, password in
  1969. if (result == .cancel) {
  1970. return
  1971. }
  1972. self?.isSaveKeyChain = false
  1973. self?.listView.document.unlock(withPassword: password)
  1974. self?.hiddenSecureLimitTip()
  1975. }
  1976. return false
  1977. }
  1978. return true
  1979. }
  1980. func addTopTip(_ view: NSView?) {
  1981. if (Thread.isMainThread) {
  1982. if (view == nil) {
  1983. let contentView: NSView = self.topTipBox.contentView!
  1984. for subview in contentView.subviews {
  1985. subview.removeFromSuperview()
  1986. }
  1987. self.topTipBox.isHidden = true
  1988. return
  1989. }
  1990. let contentView: NSView = self.topTipBox.contentView!
  1991. for subview in contentView.subviews {
  1992. subview.removeFromSuperview()
  1993. }
  1994. self.topTipBox.isHidden = false
  1995. self.topTipBox.contentView?.addSubview(view!)
  1996. } else {
  1997. DispatchQueue.main.async {
  1998. if (view == nil) {
  1999. let contentView: NSView = self.topTipBox.contentView!
  2000. for subview in contentView.subviews {
  2001. subview.removeFromSuperview()
  2002. }
  2003. self.topTipBox.isHidden = true
  2004. return
  2005. }
  2006. let contentView: NSView = self.topTipBox.contentView!
  2007. for subview in contentView.subviews {
  2008. subview.removeFromSuperview()
  2009. }
  2010. self.topTipBox.isHidden = false
  2011. self.topTipBox.contentView?.addSubview(view!)
  2012. }
  2013. }
  2014. }
  2015. }
  2016. extension KMMainViewController: KMEditImagePropertyViewControllerDelegate {
  2017. func editImagePropertyViewControllerDidChanged(controller: KMEditImagePropertyViewController, type: KMEditImagePropertyViewControllerChangeType) {
  2018. self.isPDFTextImageEdited = true
  2019. }
  2020. }