KMMainViewController.swift 86 KB

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