KMMainViewController.swift 73 KB

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