KMMainViewController+UI.swift 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899
  1. //
  2. // KMMainViewController+UI.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by wanjun on 2022/12/15.
  6. //
  7. import Foundation
  8. extension KMMainViewController {
  9. // MARK: - 退出全屏
  10. @IBAction func exitFullScreen(_ sender: Any) {
  11. if (self.view.window == nil) {
  12. return
  13. }
  14. if (KMTools.isFullScreen(self.view.window!)) {
  15. self.view.window?.toggleFullScreen(nil)
  16. }
  17. }
  18. @IBAction func startSpeaking(_ sender: Any) {
  19. self.showTTSWindow()
  20. let ttsView = KMTTSWindowController.share
  21. ttsView.buttonItemClick_Play(ttsView.playButton)
  22. }
  23. @IBAction func stopSpeaking(_ sender: Any) {
  24. let ttsWindowC = KMTTSWindowController.share
  25. if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document.documentURL.path {
  26. if let data = ttsWindowC.window?.isVisible, data {
  27. ttsWindowC.stopSpeaking()
  28. ttsWindowC.close()
  29. }
  30. }
  31. }
  32. }
  33. extension KMMainViewController {
  34. //通知
  35. func preferenceDidChangeNotification(notification:Notification) {
  36. let info : [AnyHashable : Any] = notification.userInfo ?? [:]
  37. if info.keys.contains(KMPreference.viewZoomScaleTypeKey) {
  38. self.selectZoom(KMPreferenceManager.shared.viewZoomScaleType)
  39. }
  40. if notification.name.rawValue == "pdfViewDocumentDidLoaded" || info.keys.contains(KMPreference.viewPageDisplayTypeKey) {
  41. self.selectDisplay(display: KMPreferenceManager.shared.viewPageDisplayType)
  42. }
  43. if info.keys.contains(KMPreference.displayBackgroundNormalColorKey) || notification.name.rawValue == "pdfViewDocumentDidLoaded" {
  44. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
  45. self.listView.layoutDocumentView()
  46. }
  47. self.updatePageIndicatoreType()
  48. if (info.keys.contains(KMPreference.generalAuthorNameKey)) { // 作者名称
  49. CPDFKitConfig.sharedInstance().setAnnotationAuthor((info[KMPreference.generalAuthorNameKey] as! String))
  50. }
  51. if (info.keys.contains(KMPreference.highlightLinksKey)) {
  52. let hlLink = info[KMPreference.highlightLinksKey] as? Bool
  53. CPDFKitConfig.sharedInstance().setEnableLinkFieldHighlight(hlLink == nil ? false : hlLink!)
  54. self.listView.setNeedsDisplayForVisiblePages()
  55. }
  56. if info.keys.contains(KMPreference.thumbPageSizeKey) {
  57. self.leftSideViewController.refreshUIOfThumbnailIfNeed(preference: true)
  58. }
  59. if info.keys.contains(KMPreference.thumbSnapshotSizeKey) {
  60. self.leftSideViewController.refreshUIOfSnapshotIfNeed(preference: true)
  61. }
  62. if info.keys.contains(KMPreference.outlineFontSizeKey) {
  63. self.leftSideViewController.updateTableFont()
  64. }
  65. if info.keys.contains(KMPreference.greekThresholdKey) {
  66. let value = KMPreference.shared.greekThreshold.cgFloat
  67. self.listView.setGreekingThreshold(value)
  68. self.secondaryPdfView?.setGreekingThreshold(value)
  69. }
  70. if info.keys.contains(KMPreference.antiAliasTextKey) {
  71. self.listView.setShouldAntiAlias(KMPreference.shared.antiAliasText)
  72. self.listView.applyDefaultInterpolationQuality()
  73. self.secondaryPdfView?.setShouldAntiAlias(KMPreference.shared.antiAliasText)
  74. self.secondaryPdfView?.applyDefaultInterpolationQuality()
  75. }
  76. if info.keys.contains(KMPreference.markupColorHighlightKey) {
  77. if let item = self.toolbarController.findItem(KMToolbarHighlightAnnotationItemIdentifier) {
  78. if item.isSelected {
  79. let color = KMPreference.shared.markupHighlightColor
  80. let imageV = KMNoteTypeImageView()
  81. item.image = imageV.noteTypeImage(withType: SKNHighlightString, color: color)
  82. }
  83. }
  84. }
  85. if info.keys.contains(KMPreference.markupColorUnderlineKey) {
  86. if let item = self.toolbarController.findItem(KMToolbarUnderlineAnnotationItemIdentifier) {
  87. if item.isSelected {
  88. let color = KMPreference.shared.markupUnderlineColor
  89. let imageV = KMNoteTypeImageView()
  90. item.image = imageV.noteTypeImage(withType: SKNUnderlineString, color: color)
  91. }
  92. }
  93. }
  94. if info.keys.contains(KMPreference.markupColorStrikthroughKey) {
  95. if let item = self.toolbarController.findItem(KMToolbarStrikeOutAnnotationItemIdentifier) {
  96. if item.isSelected {
  97. let color = KMPreference.shared.markupStrikthroughColor
  98. let imageV = KMNoteTypeImageView()
  99. item.image = imageV.noteTypeImage(withType: SKNStrikeOutString, color: color)
  100. }
  101. }
  102. }
  103. if info.keys.contains(KMPreference.markupColorPenKey) {
  104. if let item = self.toolbarController.findItem(KMToolbarInkAnnotationItemIdentifier) {
  105. if item.isSelected {
  106. let color = KMPreference.shared.markupPenColor
  107. let imageV = KMNoteTypeImageView()
  108. item.image = imageV.noteTypeImage(withType: SKNInkString, color: color)
  109. }
  110. }
  111. }
  112. }
  113. //刷新页面显示器
  114. func updatePageIndicatoreType () {
  115. if self.isReadMode {
  116. self.pageNumberDisplayView.dismiss()
  117. } else {
  118. if self.listView.document != nil {
  119. self.pageNumberDisplayView.totalPagesCount = Int(self.listView.document.pageCount)
  120. }
  121. self.pageNumberDisplayView.currentPageIndex = self.listView.currentPageIndex
  122. self.pageNumberDisplayView.displayType = KMPreferenceManager.shared.pageIndicatorType
  123. self.readContentView.addSubview(self.tipCurrentPageBox, positioned: .above, relativeTo: self.readContentView)
  124. }
  125. }
  126. func convertNotesUsingPDFDocument(_ pdfDocument: CPDFDocument) {
  127. beginProgressSheet(withMessage: NSLocalizedString("Converting notes", comment: "Message for progress sheet").appending("..."), maxValue: 0)
  128. let count = pdfDocument.pageCount
  129. let pdfView = listView
  130. for i in 0..<count {
  131. let page = pdfDocument.page(at: i)
  132. var addAnnotations = [CPDFAnnotation]()
  133. var removeAnnotations = [CPDFAnnotation]()
  134. for annotation in page?.annotations ?? [] {
  135. var newAnnotation: CPDFAnnotation?
  136. if let inkAnnotation = annotation as? CPDFInkAnnotation, inkAnnotation.contents.hasPrefix("<?xml version=\"1.0\" encoding=\"utf-8\"?>") {
  137. let table = KMTableAnnotation(KMNoteBounds: inkAnnotation.bounds, document: pdfView!.document)
  138. table.border = inkAnnotation.border
  139. table.color = inkAnnotation.color
  140. table.createForm(withList: inkAnnotation.contents, andPaths: inkAnnotation.bezierPaths())
  141. table.updateAppearanceInk(withIsAdd: false)
  142. table.contents = annotation.contents
  143. newAnnotation = table
  144. }
  145. if let newAnnotation = newAnnotation {
  146. addAnnotations.append(newAnnotation)
  147. removeAnnotations.append(annotation)
  148. }
  149. }
  150. for i in 0..<addAnnotations.count {
  151. let newAnnotation = addAnnotations[i]
  152. let annotation = removeAnnotations[i]
  153. // this is only to make sure markup annotations generate the lineRects, for thread safety
  154. pdfView!.addAnnotation(with: newAnnotation, to: page)
  155. pdfView!.remove(annotation)
  156. if newAnnotation.contents != nil {
  157. if newAnnotation.contents.count == 0 {
  158. newAnnotation.autoUpdateString()
  159. }
  160. }
  161. }
  162. }
  163. dismissProgressSheet()
  164. pdfView?.undoManager?.removeAllActions()
  165. undoManager?.removeAllActions()
  166. }
  167. // MARK: - KMInterfaceThemeChangedProtocol
  168. override func interfaceThemeDidChanged(_ appearance: NSAppearance.Name) {
  169. super.interfaceThemeDidChanged(appearance)
  170. self.toolbarController.interfaceThemeDidChanged(appearance)
  171. self.leftSideViewController.interfaceThemeDidChanged(appearance)
  172. self.rightSideViewController.interfaceThemeDidChanged(appearance)
  173. self.pdfEditController?.interfaceThemeDidChanged(appearance)
  174. self.mianSplitView.superview?.wantsLayer = true
  175. // let sView = self.listView.documentView()
  176. if KMAppearance.isDarkMode() {
  177. self.mianSplitView.superview?.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
  178. // sView?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1)
  179. } else {
  180. self.mianSplitView.superview?.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1).cgColor
  181. // sView?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1, alpha: 1)
  182. }
  183. }
  184. }
  185. // MARK: - KMToolbarControllerDelegate
  186. extension KMMainViewController: KMToolbarControllerDelegate {
  187. func toolbarController(_ viewController: KMToolbarController, heightOffsetChange heightOffset: Float, animated: Bool) {
  188. let heightConst = (animated ? self.heightOffset.animator() : self.heightOffset)
  189. if self.isReadMode {
  190. if self.toolbarController.toolbarType == .Annatiton {
  191. heightConst?.constant = CGFloat(heightOffset)
  192. } else {
  193. heightConst?.constant = CGFloat(0)
  194. }
  195. } else {
  196. heightConst?.constant = CGFloat(heightOffset)
  197. }
  198. self.refreshListViewToolMode()
  199. self.trackEvent(toolMode: self.listView.toolMode)
  200. if self.listView.annotationType == .editTextImage ||
  201. self.listView.annotationType == .addText ||
  202. self.listView.annotationType == .addImage {
  203. self.closeRightPane()
  204. }
  205. self.listView.annotationType = .unkown
  206. }
  207. func changeAnnotationModeAction(item: KMToolbarClickButton) {
  208. if self.listView.toolMode == .formToolMode {
  209. if !IAPProductsManager.default().isAvailableAllFunction(){
  210. KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
  211. return
  212. }
  213. }
  214. if (self.model.rightMouseEventing) {
  215. self.model.rightMouseEventing = false
  216. }
  217. if (self.toolbarController.ignoreCurrentAnnotationTypeChange) {
  218. self.toolbarController.ignoreCurrentAnnotationTypeChange = false
  219. }
  220. var currentType = self.listView.annotationType
  221. if (currentType == .eraser) {
  222. currentType = .ink
  223. }
  224. let isSelected = (currentType == CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown) && ((self.listView.toolMode == .noteToolMode) || (self.listView.toolMode == .selfSignMode) || (self.listView.toolMode == .formToolMode))
  225. var editSelectd = false
  226. if self.listView.annotationType == CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown && self.listView.toolMode == .editPDFToolMode {
  227. editSelectd = true
  228. }
  229. if isSelected {
  230. self.listView.toolMode = .textToolMode
  231. self.listView.annotationType = .unkown
  232. self.closeRightPane()
  233. } else {
  234. if let type = CAnnotationType(rawValue: item.tag) {
  235. self.trackEvent(annotationType: type)
  236. }
  237. if self.listView.currentSelection != nil {
  238. let annotation = self.listView.addAnnotation(with: CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown, selection: self.listView.currentSelection, page: self.listView.currentSelection.page, bounds: self.listView.currentSelection.bounds)
  239. if((annotation != nil) &&
  240. !self.listView.activeAnnotations.contains(annotation ?? self.listView.activeAnnotation)) {
  241. var newAnnonations : [CPDFAnnotation] = []
  242. newAnnonations.append(annotation!)
  243. self.listView.updateActiveAnnotations(newAnnonations)
  244. self.listView.setNeedsDisplayAnnotationViewFor(annotation?.page)
  245. }
  246. }
  247. self.refreshListViewToolMode()
  248. let type = CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown
  249. var annotations: [CPDFAnnotation] = []
  250. if (type == .link) {
  251. for annotation in self.listView.activeAnnotations {
  252. if ((annotation is CPDFLinkAnnotation) == false) {
  253. continue
  254. }
  255. annotations.append(annotation as! CPDFAnnotation)
  256. }
  257. }
  258. self.listView.annotationType = type
  259. if (type == .link && annotations.count > 0) {
  260. self.listView.updateActiveAnnotations(annotations)
  261. }
  262. }
  263. if self.listView.toolMode != .editPDFToolMode && self.listView.annotationType != .unkown {
  264. self.rightSideViewController.isHidden = false
  265. self.rightSideViewController.subViewType = .AnnotationProperts
  266. if !self.isReadMode {
  267. self.openRightPane()
  268. }
  269. } else if self.listView.toolMode == .editPDFToolMode {
  270. if editSelectd {
  271. self.rightSideViewController.isHidden = true
  272. self.listView.setShouAddEdit([])
  273. self.listView.change([.text, .image])
  274. self.listView.annotationType = .editTextImage
  275. self.closeRightPane()
  276. } else if self.listView.annotationType == .addText {
  277. self.rightSideViewController.isHidden = false
  278. if !self.isReadMode {
  279. self.openRightPane()
  280. }
  281. self.rightSideViewController.subViewType = .EditPDFAddText
  282. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_EditPDF", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_EditPDF_AddText"])
  283. self.listView.setShouAddEdit(.text)
  284. self.listView.change(.text)
  285. } else if self.listView.annotationType == .addImage {
  286. self.rightSideViewController.isHidden = false
  287. if !self.isReadMode {
  288. self.openRightPane()
  289. }
  290. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_EditPDF", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_EditPDF_AddImage"])
  291. // self.closeRightPane()
  292. self.rightSideViewController.subViewType = .EditPDFAddImage
  293. self.listView.setShouAddEdit(.image)
  294. self.listView.change(.image)
  295. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  296. }
  297. } else {
  298. self.rightSideViewController.isHidden = true
  299. self.closeRightPane()
  300. }
  301. }
  302. func refreshListViewToolMode () {
  303. if self.toolbarController.toolbarType == .Annatiton {
  304. self.listView.toolMode = .noteToolMode
  305. } else if self.toolbarController.toolbarType == .Move {
  306. self.listView.toolMode = .moveToolMode
  307. } else if self.toolbarController.toolbarType == .Magnify {
  308. self.listView.toolMode = .magnifyToolMode
  309. } else if self.toolbarController.toolbarType == .Select {
  310. self.listView.toolMode = .selectToolMode
  311. } else if self.toolbarController.toolbarType == .SelectZoom {
  312. self.listView.toolMode = .selectZoomToolMode
  313. } else if self.toolbarController.toolbarType == .Page {
  314. } else if self.toolbarController.toolbarType == .Form {
  315. self.listView.toolMode = .formToolMode
  316. self.rightSideViewController.subViewType = .AnnotationProperts
  317. } else if self.toolbarController.toolbarType == .FillSign {
  318. self.listView.toolMode = .selfSignMode
  319. self.rightSideViewController.subViewType = .AnnotationProperts
  320. } else if self.toolbarController.toolbarType == .editPDF {
  321. self.listView.toolMode = .editPDFToolMode
  322. // self.listView.editingConfig().isShowEditingAreaHover = true
  323. // self.listView.editingConfig().editingBorderWidth = 1
  324. // self.listView.editingConfig().editingCenterRadius = 5
  325. // self.listView.editingConfig().editAreaMargin = 2
  326. // self.listView.editingConfig().editingHoverBorderColor = NSColor.init(red: 0, green: 136.0/255.0, blue: 1.0, alpha: 0.5)
  327. // self.listView.editingConfig().editingBorderColor = NSColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
  328. // self.listView.editingConfig().addEditAreaColor = NSColor.init(red: 23.0/255.0, green: 112.0/255.0, blue: 244.0/255.0, alpha: 0.5)
  329. // self.listView.editingConfig().editAreaMoveFillColor = NSColor.init(red: 23.0/255.0, green: 112.0/255.0, blue: 244.0/255.0, alpha: 0.1)
  330. self.listView.setShouAddEdit([])
  331. }else if self.toolbarController.toolbarType == .LeftPanel {
  332. self.toggleLeftPane()
  333. self.leftSideViewController.showPanelView(show: true)
  334. }else {
  335. self.listView.toolMode = .textToolMode
  336. }
  337. }
  338. func showPDFLayoutModeAction(show: Bool) {
  339. self.listView.annotationType = .unkown
  340. self.showOrHideNotes()
  341. }
  342. }
  343. // MARK: - NSSplitViewDelegate
  344. extension KMMainViewController : NSSplitViewDelegate {
  345. func splitView(_ splitView: NSSplitView, canCollapseSubview subview: NSView) -> Bool {
  346. if splitView == self.mianSplitView {
  347. // return (subview == self.listView) == false
  348. } else if splitView == self.newPDFSplitView {
  349. return subview.isEqual(to: self.secondaryPdfContentView)
  350. }
  351. return false
  352. }
  353. func splitView(_ splitView: NSSplitView, shouldCollapseSubview subview: NSView, forDoubleClickOnDividerAt dividerIndex: Int) -> Bool {
  354. if splitView == self.newPDFSplitView {
  355. if subview.isEqual(to: self.secondaryPdfContentView) {
  356. var position = self.newPDFSplitView.maxPossiblePositionOfDivider(at: dividerIndex)
  357. if self.newPDFSplitView.isSubviewCollapsed(subview) {
  358. if self.lastSplitPDFHeight <= 0.0 {
  359. let DEFAULT_SPLIT_PANE_HEIGHT: Float = 200.0
  360. self.lastSplitPDFHeight = DEFAULT_SPLIT_PANE_HEIGHT
  361. }
  362. if self.lastSplitPDFHeight.cgFloat > NSHeight(self.pdfContentView.frame) {
  363. self.lastSplitPDFHeight = floorf(0.5 * Float(NSHeight(self.pdfContentView.frame)))
  364. }
  365. position += self.lastSplitPDFHeight.cgFloat
  366. } else {
  367. self.lastSplitPDFHeight = Float(NSHeight(subview.frame))
  368. }
  369. self.pdfSplitView.setPosition(position, ofDividerAt: dividerIndex, animate: true)
  370. }
  371. return false
  372. }
  373. return false
  374. }
  375. func splitView(_ splitView: NSSplitView, shouldHideDividerAt dividerIndex: Int) -> Bool {
  376. if splitView == self.mianSplitView {
  377. return splitView == self.mianSplitView
  378. } else if splitView == self.newPDFSplitView {
  379. return false
  380. }
  381. return false
  382. }
  383. func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  384. if splitView == mianSplitView {
  385. let splitViewWidth = splitView.frame.width
  386. let dividerIndexX0 = self.model.panelWidth + functionWidth
  387. if dividerIndex == 0 {
  388. if self.model.leftPanelOpen {
  389. return CGFloat(dividerIndexX0 * 1.5)
  390. } else {
  391. return functionWidth
  392. }
  393. } else if dividerIndex == 1 {
  394. return splitViewWidth
  395. }
  396. } else if splitView == self.newPDFSplitView {
  397. if dividerIndex == 0 {
  398. let MIN_SIDE_PANE_WIDTH = 270
  399. return proposedMaximumPosition + MIN_SIDE_PANE_WIDTH.cgFloat
  400. }
  401. }
  402. return proposedMaximumPosition
  403. }
  404. func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  405. if splitView == mianSplitView {
  406. let splitViewWidth = splitView.frame.width
  407. let dividerIndexX1 = splitViewWidth - self.model.defaultRightWidth
  408. if dividerIndex == 0 {
  409. return functionWidth
  410. } else if dividerIndex == 1 {
  411. return dividerIndexX1
  412. }
  413. } else if splitView == self.newPDFSplitView {
  414. }
  415. return proposedMinimumPosition
  416. }
  417. func splitView(_ splitView: NSSplitView, resizeSubviewsWithOldSize oldSize: NSSize) {
  418. if splitView.isEqual(to: mianSplitView) {
  419. let leftView = splitView.subviews[0]
  420. let centerView = splitView.subviews[1]
  421. let rightView = splitView.subviews[2]
  422. // let centerView = self.pdfSplitView ?? splitView.subviews[1]
  423. // let rightView = self.rightView ?? splitView.subviews[2]
  424. // 左边是否收起
  425. let leftCollapsed = splitView.isSubviewCollapsed(leftView)
  426. // 右边是否收起
  427. let rightCollapsed = splitView.isSubviewCollapsed(rightView)
  428. var leftSize = leftView.frame.size
  429. var mainSize = centerView.frame.size
  430. var rightSize = rightView.frame.size
  431. var contentWidth = splitView.frame.width
  432. if leftCollapsed {
  433. leftSize.width = 0.0
  434. } else {
  435. contentWidth = contentWidth - splitView.dividerThickness
  436. }
  437. if rightCollapsed {
  438. rightSize.width = 0.0
  439. } else {
  440. contentWidth = contentWidth - splitView.dividerThickness
  441. }
  442. if contentWidth < leftSize.width + rightSize.width {
  443. var oldContentWidth = oldSize.width
  444. if leftCollapsed == false {
  445. oldContentWidth = oldContentWidth - splitView.dividerThickness
  446. }
  447. if rightCollapsed == false {
  448. oldContentWidth = oldContentWidth - splitView.dividerThickness
  449. }
  450. let resizeFactor = contentWidth / oldContentWidth
  451. leftSize.width = floor(resizeFactor*leftSize.width)
  452. rightSize.width = floor(resizeFactor*rightSize.width)
  453. }
  454. mainSize.width = contentWidth - leftSize.width - rightSize.width
  455. leftSize.height = splitView.frame.height
  456. rightSize.height = splitView.frame.height
  457. mainSize.height = splitView.frame.height
  458. if leftCollapsed == false {
  459. leftView.setFrameSize(leftSize)
  460. }
  461. if rightCollapsed == false {
  462. rightView.setFrameSize(rightSize)
  463. }
  464. centerView.setFrameSize(mainSize)
  465. } else if splitView == self.newPDFSplitView {
  466. // let firstV = splitView.subviews.first
  467. // let lastV = splitView.subviews.last
  468. // if firstV == lastV{
  469. // splitView.adjustSubviews()
  470. // return
  471. // }
  472. // if self.newPDFSplitView.isVertical { // 横向
  473. // // 左边是否收起
  474. // let leftCollapsed = splitView.isSubviewCollapsed(firstV!)
  475. // // 右边是否收起
  476. // let rightCollapsed = splitView.isSubviewCollapsed(lastV!)
  477. //
  478. // var contentSize = splitView.frame.size
  479. // firstV?.setFrameSize(NSMakeSize(contentSize.width * 0.5, contentSize.height))
  480. // lastV?.setFrameSize(NSMakeSize(contentSize.width * 0.5, contentSize.height))
  481. // } else { // 纵向
  482. // // 左边是否收起
  483. // let leftCollapsed = splitView.isSubviewCollapsed(firstV!)
  484. // // 右边是否收起
  485. // let rightCollapsed = splitView.isSubviewCollapsed(lastV!)
  486. //
  487. // var contentSize = splitView.frame.size
  488. // firstV?.setFrameSize(NSMakeSize(contentSize.width, contentSize.height * 0.5))
  489. // lastV?.setFrameSize(NSMakeSize(contentSize.width, contentSize.height * 0.5))
  490. // }
  491. }
  492. splitView.adjustSubviews()
  493. }
  494. func splitViewWillResizeSubviews(_ notification: Notification) {
  495. let defaultView = KMSplitView()
  496. let sender : NSSplitView = notification.object as? NSSplitView ?? defaultView
  497. if (sender == self.mianSplitView || sender == defaultView) && self.view.window?.frameAutosaveName != nil{
  498. // let leftWidth = self.mianSplitView.isSubviewCollapsed(self.leftView) ? 0.0 : leftSideViewController.view.frame.width
  499. // if leftPanelOpen {
  500. // if leftWidth < 100 && lastLeftPanWidth > functionWidth{
  501. // self.closeLeftPane()
  502. // }
  503. // }
  504. } else {
  505. if sender == self.pdfSplitView {
  506. KMPrint("")
  507. }
  508. }
  509. }
  510. func splitViewDidResizeSubviews(_ notification: Notification) {
  511. self.locationPageView.frame = CGRect(x: 0, y: self.listView.frame.maxY-32, width: self.listView.frame.width, height: 32)
  512. let defaultView = KMSplitView()
  513. let sender : NSSplitView = notification.object as? NSSplitView ?? defaultView
  514. if (sender == self.mianSplitView || sender == defaultView) && self.view.window?.frameAutosaveName != nil{
  515. let leftWidth = self.mianSplitView.isSubviewCollapsed(self.leftView) ? 0.0 : leftSideViewController.view.frame.width
  516. let rightWidth = self.mianSplitView.isSubviewCollapsed(self.rightView) ? 0.0 : rightSideViewController.view.frame.width
  517. UserDefaults.standard.set(leftWidth, forKey: CPDFOfficeLeftSidePaneWidthKey)
  518. UserDefaults.standard.set(rightWidth, forKey: CPDFOfficeRightSidePaneWidthKey)
  519. } else {
  520. if sender == self.pdfSplitView {
  521. KMPrint("")
  522. }
  523. }
  524. }
  525. func splitView(_ splitView: NSSplitView, constrainSplitPosition proposedPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat {
  526. if splitView == self.mianSplitView {
  527. if dividerIndex == 0 {
  528. if self.model.leftPanelOpen {
  529. //当左边栏开启式,拖拽时不改变宽度,当宽度达到原宽度的一半时关闭窗口
  530. //如果 isShowPanel 为 true 那么将不会收缩
  531. if (proposedPosition < functionWidth + self.model.panelWidth * 0.5) && !self.leftSideViewController.isShowPanel {
  532. self.closeLeftPane()
  533. self.leftSideViewController.refreshMethodType(methodType: .None)
  534. return functionWidth
  535. } else if proposedPosition > self.model.panelWidth + functionWidth {
  536. return proposedPosition
  537. } else {
  538. return self.model.panelWidth + functionWidth
  539. }
  540. } else {
  541. return functionWidth
  542. }
  543. }
  544. } else if splitView == self.newPDFSplitView {
  545. }
  546. return proposedPosition
  547. }
  548. }
  549. // MARK: - KMLeftSideViewControllerDelegate
  550. extension KMMainViewController: KMLeftSideViewControllerDelegate {
  551. func controlStateChange(_ obj: KMLeftSideViewController, show: Bool) {
  552. if show {
  553. self.openLeftPane()
  554. } else {
  555. self.closeLeftPane()
  556. }
  557. }
  558. func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int]) {
  559. let item : KMToolbarItemView = (self.toolbarController.mainToolBarView?.toolbarItemFindItemIdentifiers(value: KMDocumentPageToolbarItemIdentifier))!
  560. self.toolbarController.mainToolBarView?.delegate?.toolbarViewController?(self.toolbarController.mainToolBarView!, clickMode: .Page, toolbar: item, pages)
  561. }
  562. func searchAction(searchString: String,isCase:Bool) {
  563. self.search(searchString: searchString,isCase: isCase)
  564. }
  565. func controller(_ controller: KMLeftSideViewController, dispayDidChange dispay: KMPDFDisplayType) {
  566. self.selectDisplay(display: dispay, viewSettingIsReload: false)
  567. }
  568. func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?) {
  569. if (itemKey == .print) { // 打印
  570. if params is NSImage {
  571. KMPrintWindowController.cpdf_printImage(image: params as! NSImage)
  572. return
  573. }
  574. var pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [], reversePrintOrder: false)
  575. if (params != nil) {
  576. pageRange.type = .custom
  577. pageRange.selectPages = params as! [Int]
  578. }
  579. self.showPrintWindow(pageRange: pageRange)
  580. } else if (itemKey == .cut || itemKey == .paste || itemKey == .delete || itemKey == .leftRotate || itemKey == .rightRotate) {
  581. self.recordIsPDFDocumentEdited(type: itemKey.toSubscribeWaterMarkType())
  582. } else if itemKey == .pageEdit {
  583. self.toolbarController.clickItem(KMDocumentPageToolbarItemIdentifier)
  584. } else if itemKey == .demote { // 大纲降级
  585. guard let currentOutline: CPDFOutline = controller.tocOutlineView.km.clickedItem() else {
  586. return
  587. }
  588. self.listView?.demote(outline: currentOutline)
  589. } else if itemKey == .promote { // 大纲升级
  590. guard let currentOutline: CPDFOutline = controller.tocOutlineView.km.clickedItem() else {
  591. return
  592. }
  593. self.listView?.promote(outline: currentOutline)
  594. }
  595. }
  596. func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookMarkItem]) {
  597. self.needSave = true
  598. self.recordIsPDFDocumentEdited()
  599. }
  600. func controller(controller: KMLeftSideViewController, rotateType: KMRotateType) {
  601. if rotateType == .clockwise {
  602. self.menuItemAction_rotateRight((Any).self)
  603. } else if rotateType == .anticlockwise {
  604. self.menuItemAction_rotateLeft((Any).self)
  605. }
  606. }
  607. func controller(controller: KMLeftSideViewController, listViewSelectionDidChange object: Any?, info: [String : Any]?) {
  608. if controller.thumbnailTableView.isEqual(to: object) {
  609. let row = controller.thumbnailTableView.selectedRow
  610. let curIndex = self.listView.currentPageIndex
  611. if (row != -1 && row != curIndex) {
  612. self.listView?.go(toPageIndex: row, animated: true)
  613. }
  614. }
  615. }
  616. }
  617. //MARK: - ReadModel
  618. extension KMMainViewController {
  619. @objc func openReadModel() {
  620. //保存进入阅读模式之前的状态
  621. readLeftMethodType = self.leftSideViewController.type.methodType
  622. readLeftPanelOpen = self.model.leftPanelOpen
  623. readLastLeftPanWidth = self.model.lastLeftPanWidth
  624. readLeftViewShowPanel = self.leftSideViewController.isShowPanel
  625. readRightPanelOpen = self.model.rightPanelIsOpen
  626. readToolbarType = self.toolbarController.toolbarType
  627. readToolMode = self.listView.toolMode
  628. readAnnotationType = self.listView.annotationType
  629. readSubViewType = self.rightSideViewController.subViewType ?? .None
  630. if self.toolbarController.lastItemBox.isSelected {
  631. readToolbarItemIdentifier = self.toolbarController.lastItemBox.itemIdentifier ?? ""
  632. } else {
  633. readToolbarItemIdentifier = ""
  634. }
  635. //设置阅读模式
  636. self.isReadMode = true
  637. self.readModelView.isHidden = false
  638. //
  639. //顶部菜单栏状态清空
  640. self.toolbarController.toolbarType = .None
  641. // self.toolbarController.view.isHidden = true
  642. self.toolbarController.cancelSelected(KMLeftControlToolbarItemIdentifier)
  643. self.toolbarController.cancelSelected(KMRightControlToolbarItemIdentifier)
  644. self.toolbarController.lastItemBox.isSelected = false
  645. //左侧菜单栏情况
  646. self.model.leftPanelOpen = false
  647. self.model.lastLeftPanWidth = 0
  648. self.leftSideViewController.refreshMethodType(methodType: .None)
  649. //阅读界面初始化
  650. self.readModelView.isHidden = false
  651. self.readModelView.currentPageIndex = self.listView.currentPageIndex
  652. self.readModelView.totalPagesCount = Int(self.listView.document.pageCount)
  653. self.readModelView.beginTimer()
  654. // self.listView.autoScales = true
  655. // self.readModelView.scaleType = .autoSize
  656. self.readModelView.zoomButton.stringValue = (NSString(format: "%.0f", self.listView.scaleFactor * 100) as String) + "%"
  657. //关闭左侧右侧菜单栏
  658. self.closeLeftPane()
  659. self.closeRightPane()
  660. self.leftSideViewController.showPanelView(show: false)
  661. self.leftView.isHidden = true
  662. //弹出提示框
  663. if readAlertView != nil {
  664. readAlertView?.removeFromSuperview()
  665. }
  666. readAlertView = CustomAlertView.alertView(message: NSLocalizedString("Read Mode On", comment: ""), fromView: self.view, withStyle: .blue, backgroundColor: NSColor.km_init(hex: "#36383B"))
  667. UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
  668. UserDefaults.standard.synchronize()
  669. }
  670. @objc func closeReadModel() {
  671. if self.isReadMode {
  672. self.model.isShowBOTA = false
  673. self.readModelView.isHidden = true
  674. self.isReadMode = false
  675. self.readModelView.isHidden = true
  676. self.leftSideViewController.refreshMethodType(methodType: readLeftMethodType)
  677. self.model.leftPanelOpen = readLeftPanelOpen
  678. self.model.rightPanelIsOpen = readRightPanelOpen
  679. self.model.lastLeftPanWidth = readLastLeftPanWidth
  680. if self.model.leftPanelOpen {
  681. self.openLeftPane()
  682. }
  683. self.closeRightPane()
  684. self.toolbarController.toolbarType = .None
  685. self.toolbarController.cancelSelected(KMDocumentViewDisplayToolbarItemIdentifier)
  686. // if self.rightPanelIsOpen {
  687. // self.rightPanelIsOpen = false
  688. //// self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  689. // self.openRightPane()
  690. // }
  691. //
  692. // if readToolbarItemIdentifier.count == 0 {
  693. // self.toolbarController.toolbarType = .None
  694. // } else {
  695. // self.toolbarController.selectItem(readToolbarItemIdentifier)
  696. // }
  697. // self.toolbarController.selectItem(KMDocumentViewDisplayToolbarItemIdentifier)
  698. self.leftSideViewController.showPanelView(show: readLeftViewShowPanel)
  699. if readLeftViewShowPanel {
  700. self.toolbarController.selectItem(KMLeftControlToolbarItemIdentifier)
  701. }
  702. self.toolbarController.view.isHidden = false
  703. self.listView.toolMode = readToolMode
  704. self.listView.annotationType = readAnnotationType
  705. // self.toolbarController.toolbarType = .viewSetting
  706. } else {
  707. self.toolbarController.toolbarType = .None
  708. }
  709. if readAlertView != nil {
  710. readAlertView?.removeFromSuperview()
  711. }
  712. readAlertView = CustomAlertView.alertView(message: NSLocalizedString("Read Mode Off", comment: ""), fromView: self.view, withStyle: .blue, backgroundColor: NSColor.km_init(hex: "#36383B"))
  713. UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
  714. UserDefaults.standard.synchronize()
  715. }
  716. @objc func addOutLineItemAction() {
  717. let labelString = "\(KMLocalizedString("Page", nil)) \((self.listView?.currentPageIndex ?? 0) + 1)"
  718. let label = self.listView?.currentSelection?.string() ?? labelString
  719. let dest = self.listView?.currentDestination
  720. if let row = self.leftSideViewController.selectedRowIndexes().last {
  721. if let ol = self.leftSideViewController.tocOutlineView.item(atRow: row) as? CPDFOutline {
  722. _ = self.listView.addOutline(for: ol.parent, label: label, dest: dest, at: ol.index+1)
  723. } else {
  724. let idx = self.listView?.document?.outlineRoot()?.numberOfChildren ?? 0
  725. _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
  726. }
  727. } else {
  728. let idx = self.listView?.document?.outlineRoot()?.numberOfChildren ?? 0
  729. _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
  730. }
  731. }
  732. @objc func showTTSView() {
  733. self.showTTSWindow()
  734. }
  735. @objc func showShareAction() {
  736. }
  737. @objc func lookUpAction() {
  738. }
  739. @objc func searchBaiduAction() {
  740. }
  741. @objc func showInfoInFinder() {
  742. }
  743. @objc func NextPageAction() {
  744. }
  745. @objc func PreviousPageAction() {
  746. }
  747. @objc func TranslateItemAction() {
  748. }
  749. @objc func AutoScrollItemAction() {
  750. //增加判断,如果是正在滚动,就停止,否则就开始滚动
  751. self.listView.autoFlow()
  752. }
  753. @objc func shareFromService(sender: NSMenuItem) {
  754. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  755. return
  756. }
  757. var string = ""
  758. if let freeTextAnnotation = listView.activeAnnotation as? CPDFFreeTextAnnotation {
  759. string = freeTextAnnotation.contents ?? ""
  760. } else if let markupAnnotation = listView.activeAnnotation as? CPDFMarkupAnnotation {
  761. if let page = markupAnnotation.page {
  762. if let selection = page.selection(for: markupAnnotation.bounds) {
  763. string = selection.string()
  764. }
  765. }
  766. } else {
  767. string = listView.currentSelection.string()
  768. }
  769. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  770. let model = windowControler.browser?.tabStripModel
  771. if let cnt = model?.count(), cnt <= 0 {
  772. return
  773. }
  774. if let data = model?.activeTabContents().isHome, data {
  775. return
  776. }
  777. let document: KMMainDocument = model?.activeTabContents() as! KMMainDocument
  778. if string.count > 0 {
  779. let represent : NSSharingService = sender.representedObject as! NSSharingService
  780. represent.perform(withItems: [string])
  781. return
  782. }
  783. let represent = sender.representedObject as? NSSharingService
  784. represent?.perform(withItems: [string])
  785. }
  786. @objc func cutAction(sender: NSMenuItem) {
  787. }
  788. @objc func deleteAction(sender: NSMenuItem) {
  789. }
  790. @objc func ColorsItemAction(sender: NSMenuItem) {
  791. }
  792. @objc func LinesItemAction(sender: NSMenuItem) {
  793. }
  794. @objc func EditNoteItemAction(sender: NSMenuItem) {
  795. }
  796. @objc func AITranslateItemAction(sender: NSMenuItem) {
  797. self.showAITypeChooseView(aiConfigType: .translate)
  798. }
  799. @objc func AIProofreadItemAction(sender: NSMenuItem) {
  800. self.showAITypeChooseView(aiConfigType: .proofreading)
  801. }
  802. @objc func AIRewriteItemAction(sender: NSMenuItem) {
  803. self.showAITypeChooseView(aiConfigType: .reWriting)
  804. }
  805. // @objc func highlightLinks() {
  806. // let highlightLinks = KMPreferenceManager.shared.highlightLinks
  807. // KMPreferenceManager.shared.highlightLinks = !highlightLinks
  808. // }
  809. }
  810. // MARK: - KMEditImagePropertyViewControllerDelegate
  811. extension KMMainViewController: KMEditImagePropertyViewControllerDelegate {
  812. func editImagePropertyViewControllerDidChanged(controller: KMEditImagePropertyViewController, type: KMEditImagePropertyViewControllerChangeType) {
  813. self.model.isPDFTextImageEdited = true
  814. }
  815. }
  816. // MARK: - KMSnapshotWindowControllerDelegate
  817. extension KMMainViewController: KMSnapshotWindowControllerDelegate {
  818. func snapshotControllerWillClose(_ controller: KMSnapshotWindowController) {
  819. self.leftSideViewController.snapshotControllerWillClose(controller)
  820. }
  821. func snapshotController(_ controller: KMSnapshotWindowController, miniaturizedRect isMiniaturize: Bool) -> NSRect {
  822. if isMiniaturize && self.interactionMode != .presentation {
  823. if self.interactionMode != .legacyFullScreen && self.model.leftPanelOpen == false {
  824. self.toggleLeftPane()
  825. } else if self.interactionMode == .legacyFullScreen {
  826. // else if ([self interactionMode] == SKLegacyFullScreenMode && ([rightSideWindow state] == NSDrawerClosedState || [rightSideWindow state] == NSDrawerClosingState)) {
  827. // [rightSideWindow expand];
  828. // [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(hideRightSideWindow:) userInfo:NULL repeats:NO];
  829. }
  830. var row = NSNotFound
  831. for (i,sp) in self.leftSideViewController.snapshots.enumerated() {
  832. if controller.isEqual(sp.windowC) {
  833. row = i
  834. }
  835. }
  836. if (row != NSNotFound) {
  837. self.leftSideViewController.leftView.segmentedControl.selectedSegment = 3
  838. self.leftSideViewController.snapshotTableView.scrollRowToVisible(row)
  839. }
  840. }
  841. return self.leftSideViewController.snapshotController(controller, miniaturizedRect: isMiniaturize)
  842. }
  843. func snapshotControllerDidFinishSetup(_ controller: KMSnapshotWindowController) {
  844. self.leftSideViewController.snapshotControllerDidFinishSetup(controller)
  845. }
  846. }
  847. // MARK: - CPDFDocumentDelegate
  848. extension KMMainViewController: CPDFDocumentDelegate {
  849. func documentDidBeginDocumentFind(_ document: CPDFDocument!) {
  850. self.leftSideViewController.documentDidBeginFind()
  851. // [statusBar setProgressIndicatorStyle:SKProgressIndicatorBarStyle];
  852. // [[statusBar progressIndicator] setMaxValue:[[note object] pageCount]];
  853. // [[statusBar progressIndicator] setDoubleValue:0.0];
  854. // [statusBar startAnimation:self];
  855. // [self willChangeValueForKey:SEARCHRESULTS_KEY];
  856. // [self willChangeValueForKey:GROUPEDSEARCHRESULTS_KEY];
  857. }
  858. func documentDidEndDocumentFind(_ document: CPDFDocument!) {
  859. self.leftSideViewController.documentDidEndFind()
  860. // [self didChangeValueForKey:GROUPEDSEARCHRESULTS_KEY];
  861. // [self didChangeValueForKey:SEARCHRESULTS_KEY];
  862. // [statusBar stopAnimation:self];
  863. // [statusBar setProgressIndicatorStyle:SKProgressIndicatorNone];
  864. // NSArray *highlights = [[NSArray alloc] initWithArray:searchResults copyItems:YES];
  865. // [highlights setValue:[NSColor yellowColor] forKey:@"color"];
  866. // [self.pdfView setHighlightedSelections:highlights];
  867. // [highlights release];
  868. }
  869. }
  870. // MAKR: - CPDFViewDelegate,CPDFListViewDelegate
  871. extension KMMainViewController: CPDFViewDelegate,CPDFListViewDelegate {
  872. func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  873. self.dealDocumentDidLoaded()
  874. let notification = Notification(name: Notification.Name(rawValue: "pdfViewDocumentDidLoaded"))
  875. self.preferenceDidChangeNotification(notification:notification)
  876. let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) as? NSNumber ?? NSNumber(value: self.model.panelWidth + functionWidth)
  877. let rightWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) as? NSNumber ?? NSNumber(value: self.model.defaultRightWidth)
  878. applyLeftSideWidth(leftWidthNumber.doubleValue, rightSideWidth: rightWidthNumber.doubleValue)
  879. self.updatePageIndicatoreType()
  880. }
  881. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  882. self.updatePageIndicatoreType()
  883. NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: self.document)
  884. // KMPrint("KMPDFViewCurrentPageDidChanged")
  885. }
  886. func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
  887. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor * 100))%"
  888. self.updateZoomInOutButtonState()
  889. // KMPrint("pdfViewScaleDidChanged")
  890. }
  891. func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
  892. if let urlString = url, urlString == kKMPurchaseProductURLString {
  893. //跳转订阅比较表
  894. let _ = KMComparativeTableViewController.show(window: NSApp.mainWindow ?? NSWindow())
  895. return
  896. }
  897. KMTools.openURL(urlString: url)
  898. }
  899. func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  900. KMPrint("pdfViewPerformURL")
  901. if content != nil {
  902. NSWorkspace.shared.open(URL(string: content)!)
  903. } else {
  904. let alert = NSAlert()
  905. alert.alertStyle = .critical
  906. alert.informativeText = NSLocalizedString("The hyperlink is invalid.", comment: "")
  907. alert.messageText = ""
  908. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  909. alert.runModal()
  910. return
  911. }
  912. }
  913. func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  914. KMPrint("pdfViewPerformPrint")
  915. self.showPrintWindow()
  916. }
  917. func pdfViewPerformGo(toPage pdfView: CPDFView!) {
  918. KMPrint("pdfViewPerformGo")
  919. }
  920. func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
  921. KMPrint("pdfViewOpenPDF")
  922. }
  923. func pdfViewPerformReset(_ pdfView: CPDFView!) {
  924. KMPrint("pdfViewPerformReset")
  925. // self.listView.resetFormAnnotation()
  926. pdfView.document.resetForm()
  927. }
  928. func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
  929. KMPrint("pdfViewEditingBlockDidChanged")
  930. }
  931. func pdfViewAsBookBookmark() -> NSImage! {
  932. return NSImage(named: "KMImageNameUXIconPDFViewBookMark")!
  933. }
  934. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  935. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText {
  936. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  937. self.rightSideViewController.eidtPDFTextProperty.updateTextTextPresuppositionState()
  938. }
  939. }
  940. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  941. let areas = self.listView.editingAreas()
  942. if areas == nil || areas?.count ?? 0 == 0 {
  943. if self.listView.toolMode == .editPDFToolMode {
  944. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  945. if self.listView.isEditImage {
  946. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  947. } else {
  948. // if self.listView.annotationType == .addImage {
  949. // self.closeRightPane()
  950. // }
  951. if self.listView.annotationType == .addImage {
  952. if self.rightSideViewController.eidtPDFImageProperty != nil {
  953. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  954. }
  955. }
  956. // self.openRightPane()
  957. }
  958. } else {
  959. self.closeRightPane()
  960. }
  961. } else {
  962. self.rightSideViewController.isHidden = true
  963. self.closeRightPane()
  964. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  965. self.rightSideViewController.eidtPDFTextProperty.initData()
  966. }
  967. }
  968. if self.listView.isEdited() {
  969. self.recordIsPDFDocumentEdited(type: .editText)
  970. }
  971. if self.listView.annotationType != .addText {
  972. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  973. }
  974. return
  975. }
  976. self.model.isPDFTextImageEdited = true
  977. if (self.listView.annotationType == .addImage) && areas!.count > 0 {
  978. var isImageArea = false
  979. for i in 0 ... areas!.count-1 {
  980. if areas![i] is CPDFEditImageArea {
  981. isImageArea = true
  982. }
  983. }
  984. if isImageArea {
  985. // self.rightSideViewController.view.isHidden = false
  986. self.rightSideViewController.isHidden = false
  987. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddImage {
  988. self.rightSideViewController.subViewType = .EditPDFAddImage
  989. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  990. }
  991. self.openRightPane()
  992. } else {
  993. // self.rightSideViewController.view.isHidden = true
  994. self.rightSideViewController.isHidden = true
  995. self.closeRightPane()
  996. }
  997. } else if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  998. // self.rightSideViewController.view.isHidden = false
  999. self.rightSideViewController.isHidden = false
  1000. if self.listView.editingSelectionString().count != 0 {
  1001. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  1002. } else {
  1003. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1004. }
  1005. self.openRightPane()
  1006. } else {
  1007. var textsAreas : [CPDFEditTextArea] = []
  1008. var imagesAreas : [CPDFEditImageArea] = []
  1009. if self.listView.editingAreas()?.count ?? 0 < 1 {
  1010. return
  1011. }
  1012. for i in 0 ... areas!.count-1 {
  1013. if areas![i] is CPDFEditTextArea {
  1014. textsAreas.append(areas![i] as! CPDFEditTextArea)
  1015. }
  1016. if areas![i] is CPDFEditImageArea {
  1017. imagesAreas.append(areas![i] as! CPDFEditImageArea)
  1018. }
  1019. }
  1020. if textsAreas.count > 0 && textsAreas.count == areas!.count {
  1021. // self.rightSideViewController.view.isHidden = false
  1022. self.rightSideViewController.isHidden = false
  1023. self.rightSideViewController.subViewType = .EditPDFAddText
  1024. self.rightSideViewController.eidtPDFTextProperty?.reloadData()
  1025. self.openRightPane()
  1026. } else if imagesAreas.count > 0 {
  1027. // self.rightSideViewController.view.isHidden = false
  1028. self.rightSideViewController.isHidden = false
  1029. self.rightSideViewController.subViewType = .EditPDFAddImage
  1030. self.rightSideViewController.eidtPDFImageProperty?.reloadData()
  1031. self.openRightPane()
  1032. }
  1033. }
  1034. if self.listView.isEdited() {
  1035. self.recordIsPDFDocumentEdited(type: .editText)
  1036. if self.listView.annotationType != .addText {
  1037. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  1038. }
  1039. }
  1040. }
  1041. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  1042. if editArea != nil && (editArea is CPDFEditImageArea){
  1043. self.listView.cropAreas = editArea as? CPDFEditImageArea
  1044. }
  1045. }
  1046. //编辑PDF 创建图片区域回调
  1047. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1048. if self.listView.isEditImage {
  1049. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1050. } else {
  1051. let panel = NSOpenPanel()
  1052. panel.allowsMultipleSelection = false
  1053. panel.allowedFileTypes = ["png","jpg"]
  1054. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  1055. if response == .OK {
  1056. var filePath = panel.url?.path
  1057. var image = NSImage.init(contentsOf: panel.url!)
  1058. //图片自适应范围
  1059. if image != nil {
  1060. var imageRect = rect
  1061. let imageSize = image!.size
  1062. var previewSize = rect.size
  1063. var isChangeSize = false
  1064. if previewSize.width == 0 && previewSize.height == 0 {
  1065. previewSize = CGSize(width: 500, height: 500)
  1066. isChangeSize = true
  1067. }
  1068. let scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  1069. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  1070. if isChangeSize {
  1071. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  1072. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  1073. } else {
  1074. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  1075. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  1076. }
  1077. imageRect.size = newSize
  1078. let limitWidth = 1920.0
  1079. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  1080. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  1081. targetSize: CGSize(width: limitWidth, height: limitWidth),
  1082. maxSizeInBytes: 1024 * 1024 * 5,
  1083. targetCompression: 1.0)
  1084. }
  1085. //自适应page
  1086. let pageRect = self.listView.currentPage().bounds
  1087. if imageRect.width > pageRect.width ||
  1088. imageRect.height > pageRect.height {
  1089. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  1090. imageRect = CGRect(x: imageRect.origin.x,
  1091. y: imageRect.origin.y,
  1092. width: imageRect.width * pageScale,
  1093. height: imageRect.height * pageScale)
  1094. }
  1095. if imageRect.origin.x < 0 {
  1096. imageRect.origin.x = 5
  1097. }
  1098. if imageRect.origin.y < 0 {
  1099. imageRect.origin.y = 5
  1100. }
  1101. if imageRect.origin.x + imageRect.width > pageRect.width ||
  1102. imageRect.origin.y + imageRect.height > pageRect.height {
  1103. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  1104. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  1105. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  1106. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  1107. }
  1108. DispatchQueue.main.async {
  1109. self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  1110. self.model.isPDFTextImageEdited = true
  1111. self.recordIsPDFDocumentEdited(type: .editImage)
  1112. // self.asyncSaveDocument { params in
  1113. //
  1114. // }
  1115. }
  1116. }
  1117. }
  1118. }
  1119. }
  1120. }
  1121. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1122. // print(rect)
  1123. var newrect = CGRect(x: rect.origin.x, y: rect.origin.y, width: rect.size.width, height: rect.size.height)
  1124. if __CGSizeEqualToSize(rect.size, CGSize.zero) {
  1125. newrect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  1126. } else {
  1127. newrect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  1128. }
  1129. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  1130. let fontName = KMEditPDFTextManager.manager.fetchFontName(fontName: model.fontName)
  1131. let fontSize = model.fontSize
  1132. let fontColor = model.color
  1133. let fontAlign = model.alignment
  1134. let fontStyle = KMEditPDFTextManager.manager.fetchFontStyle(fontName: model.fontName)
  1135. NSColorPanel.shared.color = fontColor
  1136. let font = KMEditPDFTextManager.manager.fetchFont(fontName: fontName, style: fontStyle, size: fontSize)
  1137. let style = NSMutableParagraphStyle()
  1138. style.alignment = fontAlign
  1139. let attributes = [NSAttributedString.Key.font:font, NSAttributedString.Key.foregroundColor:fontColor,NSAttributedString.Key.paragraphStyle:style] as [NSAttributedString.Key : Any]
  1140. self.listView.createEmptyStringBounds(newrect,withAttributes: attributes as [NSAttributedString.Key : Any], page: page)
  1141. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1142. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1143. }
  1144. // self.asyncSaveDocument { params in
  1145. //
  1146. // }
  1147. }
  1148. func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
  1149. let command = theEvent.modifierFlags.contains(.command)
  1150. let control = theEvent.modifierFlags.contains(.control)
  1151. KMPrint(theEvent.keyCode)
  1152. if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
  1153. self.menuItemBookMarkClick_add(sender: NSMenuItem())
  1154. return false
  1155. } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
  1156. return false
  1157. } else if (theEvent.keyCode == 123) { // 向左
  1158. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1159. return false
  1160. } else {
  1161. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  1162. self.listView.goToPreviousPage(nil)
  1163. return false
  1164. }
  1165. }
  1166. } else if (theEvent.keyCode == 126) { // 向上
  1167. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1168. return false
  1169. } else {
  1170. if (self.listView.isContinousScroll()) {
  1171. return true
  1172. }
  1173. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  1174. self.listView.goToPreviousPage(nil)
  1175. return false
  1176. }
  1177. }
  1178. } else if (theEvent.keyCode == 124) { // 向右
  1179. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1180. return false
  1181. } else {
  1182. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  1183. self.listView.goToNextPage(nil)
  1184. return false
  1185. }
  1186. }
  1187. } else if (theEvent.keyCode == 125) { // 向下
  1188. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1189. return false
  1190. } else {
  1191. if (self.listView.isContinousScroll()) {
  1192. return true
  1193. }
  1194. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  1195. self.listView.goToNextPage(nil)
  1196. return false
  1197. }
  1198. }
  1199. } else if (theEvent.keyCode == 36) {
  1200. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  1201. if self.listView.isEditImage {
  1202. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1203. }
  1204. }
  1205. }
  1206. if theEvent.keyCode == 53 {
  1207. self.exitFullScreen(Any.self)
  1208. if self.isReadMode {
  1209. self.closeReadModel()
  1210. }
  1211. self.leftSideViewCancelSelect()
  1212. if (self.toolbarController.toolbarType.isToolMode()) {
  1213. self.toolbarController.selectItem(self.toolbarController.toolbarType.itemIdentifier())
  1214. }
  1215. }
  1216. return true
  1217. }
  1218. func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
  1219. guard let action = menuItem.action else {
  1220. isTakesEffect.pointee = false
  1221. return false
  1222. }
  1223. if (KMSystemMenu.isEditSelector(sel: action)) {
  1224. if (KMSystemMenu.Edit.deleteSelector == action) {
  1225. isTakesEffect.pointee = true
  1226. return self.listView.activeAnnotations.count > 0
  1227. } else if (KMSystemMenu.Edit.copySelector == action) {
  1228. isTakesEffect.pointee = true
  1229. return true//self.listView.canCopy()
  1230. } else if (KMSystemMenu.Edit.cutSelector == action) {
  1231. isTakesEffect.pointee = true
  1232. return self.listView.canCopy()
  1233. } else if (KMSystemMenu.Edit.pasteSelector == action) {
  1234. isTakesEffect.pointee = true
  1235. return self.listView.canPaste()
  1236. }
  1237. }
  1238. isTakesEffect.pointee = false
  1239. return false
  1240. }
  1241. //MARK: -CPDFListViewDelegate
  1242. func cPDFListView(_ pdfListView: CPDFListView, didDelete annotation: CPDFAnnotation, in pdfPage: CPDFPage) {
  1243. self.leftSideViewController.updateThumbnail(at: Int(pdfPage.pageIndex()))
  1244. }
  1245. func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
  1246. self.view.window?.makeFirstResponder(self.listView)
  1247. if isRightMenu {
  1248. } else if annotations.count > 0 {
  1249. if annotations.count > 1 {
  1250. let fristAnnotation = annotations.first
  1251. var isSameAnnotation = true
  1252. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1253. for annotation in annotations {
  1254. let cunrrentClassName = NSStringFromClass(annotation.classForCoder)
  1255. if (className == "CPDFSquareAnnotation") ||
  1256. (className == "CPDFCircleAnnotation") ||
  1257. (className == "CPDFLineAnnotation") {
  1258. if (cunrrentClassName != "CPDFSquareAnnotation") &&
  1259. (cunrrentClassName != "CPDFCircleAnnotation") &&
  1260. (cunrrentClassName != "CPDFLineAnnotation") {
  1261. isSameAnnotation = false
  1262. }
  1263. } else {
  1264. if className != cunrrentClassName {
  1265. isSameAnnotation = false
  1266. }
  1267. }
  1268. }
  1269. if isSameAnnotation == false {
  1270. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1271. // self.closeRightPane()
  1272. } else {
  1273. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1274. self.openRightPane()
  1275. }
  1276. } else {
  1277. let fristAnnotation = annotations.first
  1278. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1279. if self.isReadMode {
  1280. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1281. self.closeRightPane()
  1282. } else {
  1283. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1284. if className != "CPDFStampAnnotation" &&
  1285. className != "CPDFSignatureAnnotation" &&
  1286. className != "CPDFListStampAnnotation" {
  1287. self.openRightPane()
  1288. }
  1289. }
  1290. }
  1291. } else if (annotations.count == 0){
  1292. if pdfListView.annotationType == .unkown {
  1293. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1294. self.closeRightPane()
  1295. } else {
  1296. if self.isReadMode {
  1297. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1298. self.closeRightPane()
  1299. } else {
  1300. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1301. self.openRightPane()
  1302. }
  1303. }
  1304. }
  1305. }
  1306. func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
  1307. if(annotationType == .unkown) {
  1308. // self.rightSideViewController.view.isHidden = true
  1309. self.rightSideViewController.isHidden = true
  1310. self.closeRightPane()
  1311. }
  1312. let aType = annotationType
  1313. if aType.isMarkup() || aType == .anchored || aType == .freeText || aType.isSquare() || aType == .link {
  1314. KMDataManager.ud_set(annotationType.rawValue, forKey: SKLastAnnotationModeKey)
  1315. }
  1316. }
  1317. ///开始定位链接注释
  1318. func pdfListViewLinkDestinationStart(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1319. if self.locationPageView.superview == nil {
  1320. self.locationPageView.frame = CGRect(x: 0, y: pdfListView.frame.maxY-32, width: pdfListView.frame.width, height: 32)
  1321. pdfListView.addSubview(self.locationPageView)
  1322. }
  1323. }
  1324. ///刷新链接注释
  1325. func pdfListViewLinkDestinationEnd(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1326. if self.locationPageView.superview != nil {
  1327. self.locationPageView.removeFromSuperview()
  1328. }
  1329. if self.rightSideViewController.subViewType == .AnnotationProperts && pdfListView.annotationType == .link {
  1330. self.rightSideViewController.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1331. }
  1332. }
  1333. func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
  1334. if (listView.toolMode != CToolMode.editPDFToolMode) {
  1335. return menuItems
  1336. }
  1337. var tMenuItems = menuItems;
  1338. if(listView.isSelectEditCharRange() ||
  1339. listView.isSelecteditArea(with: point)) {
  1340. tMenuItems?.append(NSMenuItem.separator())
  1341. // tMenuItems?.append(self.fontColorMenuItem())
  1342. // tMenuItems?.append(self.fontSizeMenuItem())
  1343. }
  1344. let areas = self.listView.editingAreas() ?? []
  1345. if areas.count == 1 {
  1346. let fristAreas = areas.first
  1347. if fristAreas is CPDFEditImageArea {
  1348. self.listView.selectImageAreas = fristAreas as? CPDFEditImageArea
  1349. if self.listView.isEditImage {
  1350. tMenuItems?.removeAll()
  1351. tMenuItems?.append(self.corpImageMenuItem())
  1352. tMenuItems?.append(self.cancelCorpImageMenuItem())
  1353. tMenuItems?.append(self.restoreCorpImageMenuItem())
  1354. } else {
  1355. tMenuItems?.append(NSMenuItem.separator())
  1356. tMenuItems?.append(self.cutImageArea())
  1357. tMenuItems?.append(self.replaceImageArea())
  1358. tMenuItems?.append(self.exportImageArea())
  1359. }
  1360. } else {
  1361. if tMenuItems?.count != 1 {
  1362. tMenuItems?.swapAt(0, 1)
  1363. }
  1364. }
  1365. } else if areas.count == 0 {
  1366. tMenuItems?.append(NSMenuItem.separator())
  1367. tMenuItems?.append(self.addText())
  1368. tMenuItems?.append(self.addImage())
  1369. }
  1370. return tMenuItems
  1371. }
  1372. func tableMenu(_ menu: NSMenu, withTable table: KMTableAnnotation, point: CGPoint) -> NSMenu {
  1373. if table.currentCell.row >= 0 && table.currentCell.column >= 0 {
  1374. let itemTitles = ["Edit", "", "Add Row Above", "Add Row Below", "", "Add Column Before", "Add Column After", "", "Delete Row", "Delete Column", "Delete Table", "Cut", "Copy", "Paste", "Paste and Match Style", "Delete Cell Contents", "Clear All"]
  1375. let actions = ["formAnnotTextEdit:", "", "addRowAbove:", "addRowBelow:", "", "addColumnBefore:", "addColumnAfter:", "", "deleteRow:", "deleteColumn:", "deleteTabel", "cutCell:", "copyCell:", "pasteCell:", "pasteAndMatchStyle:", "deleteCellContents:", "clearAll:"]
  1376. for i in 0..<itemTitles.count {
  1377. var item: NSMenuItem? = nil
  1378. if itemTitles[i] == "" {
  1379. item = NSMenuItem.separator()
  1380. menu.insertItem(item!, at: i)
  1381. } else {
  1382. item = NSMenuItem(title: itemTitles[i], action: nil, keyEquivalent: "")
  1383. item!.target = self
  1384. item!.action = NSSelectorFromString(actions[i])
  1385. if itemTitles[i] == "Paste" /*&& !_copyCellData*/ {
  1386. item!.action = nil
  1387. } else if itemTitles[i] == "Paste and Match Style" /*&& !_copyCellData */{
  1388. item!.action = nil
  1389. } else if itemTitles[i] == "Add Row Above" {
  1390. let path1 = table.crossLines[table.rowNumber - table.currentCell.row]
  1391. let path2 = table.crossLines[table.rowNumber - table.currentCell.row - 1]
  1392. if (path1 as AnyObject).lineJoinStyle == NSBezierPath.LineJoinStyle.round && table.headerCount() >= 5 {
  1393. item!.action = nil
  1394. } else if (path2 as AnyObject).lineJoinStyle == NSBezierPath.LineJoinStyle.bevel && table.footerCount() >= 5 {
  1395. item!.action = nil
  1396. }
  1397. }
  1398. item!.title = NSLocalizedString(item!.title, comment: "")
  1399. item!.representedObject = NSValue(point: point)
  1400. menu.insertItem(item!, at: i)
  1401. }
  1402. }
  1403. } else {
  1404. let itemTitles = ["Cut", "Copy", "Paste", "Delete"]
  1405. let actions = ["cut:", "copy:", "paste:", "delete:"]
  1406. for i in 0..<itemTitles.count {
  1407. let item = NSMenuItem(title: itemTitles[i], action: nil, keyEquivalent: "")
  1408. item.target = self
  1409. item.action = NSSelectorFromString(actions[i])
  1410. item.title = NSLocalizedString(item.title, comment: "")
  1411. menu.insertItem(item, at: i)
  1412. item.representedObject = NSValue(point: point)
  1413. }
  1414. }
  1415. return menu
  1416. }
  1417. func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!, isMoveSelectAnno: Bool) {
  1418. self.mouseRightMenuEvent = theEvent
  1419. var currentMenu : NSMenu = menu.pointee!
  1420. if let activeAnno = listView.activeAnnotation as? KMTableAnnotation {//Table
  1421. var pagePoint = NSPoint()
  1422. _ = self.listView.pageAndPoint(&pagePoint, for: theEvent, nearest: true)
  1423. currentMenu.removeAllItems()
  1424. let annotation = activeAnno
  1425. annotation.completeEditCellText()
  1426. if !(NSIsEmptyRect(annotation.drawRect)) {
  1427. annotation.drawLine(pagePoint)
  1428. NotificationCenter.default.post(name: NSNotification.Name.KMPDFViewTableAnnotationDidChange, object: self, userInfo: ["point": NSValue(point: pagePoint)])
  1429. }
  1430. if (annotation.rowNumber - annotation.currentCell.row - 1) < 0 {
  1431. return
  1432. }
  1433. currentMenu = tableMenu(currentMenu, withTable: listView.activeAnnotation as! KMTableAnnotation, point: pagePoint)
  1434. listView.needsDisplay = true
  1435. return
  1436. }
  1437. if (listView.toolMode == .selectToolMode){
  1438. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1439. currentMenu.insertItem(self.printingMenu(), at: 3)
  1440. currentMenu.insertItem(self.setTTSStype(), at: 3)
  1441. currentMenu.insertItem(self.setCropStype(), at: 3)
  1442. currentMenu.insertItem(self.setSnapshotStype(), at: 3)
  1443. let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
  1444. export.submenu = self.exportMenu()
  1445. currentMenu.insertItem(export, at: 3)
  1446. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1447. if listView.activeAnnotation == nil{
  1448. currentMenu.insertItem(self.setAnnotationToolStype(), at: 3)
  1449. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1450. }
  1451. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 3)
  1452. currentMenu.insertItem(self.addReadModelStype(), at: currentMenu.items.count - 3)
  1453. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1454. currentMenu.insertItem(self.setAITranslateStype(), at: 0)
  1455. currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
  1456. currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
  1457. return
  1458. }
  1459. if (listView.toolMode == .moveToolMode || listView.toolMode == .magnifyToolMode){
  1460. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1461. currentMenu.insertItem(self.setTTSStype(), at: 0)
  1462. currentMenu.insertItem(self.setCropStype(), at: 0)
  1463. currentMenu.insertItem(self.setSnapshotStype(), at: 0)
  1464. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1465. currentMenu.insertItem(self.addOutlineStype(), at: 0)
  1466. currentMenu.insertItem(self.addBookmarkMenu(), at: 0)
  1467. if listView.activeAnnotation == nil{
  1468. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1469. currentMenu.insertItem(self.setAnnotationToolStype(), at: 0)
  1470. }
  1471. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1472. currentMenu.insertItem(self.setAITranslateStype(), at: 0)
  1473. currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
  1474. currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
  1475. return
  1476. }
  1477. if currentMenu.items.count > 3 {
  1478. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 3)
  1479. currentMenu.insertItem(self.addReadModelStype(), at: currentMenu.items.count - 3)
  1480. }
  1481. if listView.currentSelection != nil{
  1482. if listView.currentSelection.selectionType() == .text {
  1483. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1484. currentMenu.insertItem(self.setSearchBaiduStype(), at: 3)
  1485. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1486. currentMenu.insertItem(self.setLookUpStype(), at: 3)
  1487. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1488. currentMenu.insertItem(self.addOutlineStype(), at: 3)
  1489. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1490. if listView.activeAnnotation == nil{
  1491. currentMenu.insertItem(self.setAnnotationToolStype(), at: 3)
  1492. }
  1493. currentMenu.insertItem(self.setTTSStype(), at: 3)
  1494. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1495. currentMenu.insertItem(self.setShareStype(), at: 3)
  1496. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1497. }
  1498. currentMenu.insertItem(self.enterAnnotationStype(), at: 3)
  1499. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1500. if listView.currentSelection.selectionType() == .image{
  1501. //
  1502. // currentMenu.insertItem(self.setCutStype(), at: 1)
  1503. // }
  1504. if listView.activeAnnotations.count > 0 {
  1505. currentMenu.insertItem(self.setDeleteStype(), at: 3)
  1506. currentMenu.insertItem(NSMenuItem.separator(), at: 6)
  1507. currentMenu.insertItem(self.setEditNoteStype(), at: 6)
  1508. currentMenu.insertItem(self.setRotateStype(), at: 6)
  1509. currentMenu.insertItem(self.setLinesStype(), at: 6)
  1510. currentMenu.insertItem(self.setColorsStype(), at: 6)
  1511. }
  1512. }
  1513. if listView.currentSelection.selectionType() == .text {
  1514. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1515. currentMenu.insertItem(self.setTranslateStype(), at: currentMenu.items.count)
  1516. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1517. // currentMenu.insertItem(self.setServicesStype(), at: currentMenu.items.count)
  1518. }
  1519. }
  1520. if listView.activeAnnotation != nil || isMoveSelectAnno {
  1521. if let data = self.listView?.activeAnnotation?.type?.lowercased(), data == "stamp"{
  1522. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1523. currentMenu.insertItem(self.enterAnnotationStype(), at: currentMenu.items.count - 15)
  1524. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1525. }else{
  1526. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1527. currentMenu.insertItem(self.enterAnnotationStype(), at: currentMenu.items.count - 15)
  1528. // currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1529. // currentMenu.insertItem(self.setAnnotationToolStype(), at: currentMenu.items.count - 15)
  1530. // currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1531. // currentMenu.insertItem(self.addBookmarkMenu(), at: currentMenu.items.count - 15)
  1532. // currentMenu.insertItem(self.addOutlineStype(), at: currentMenu.items.count - 15)
  1533. // currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1534. // currentMenu.insertItem(self.setSnapshotStype(), at: currentMenu.items.count - 15)
  1535. // currentMenu.insertItem(self.setCropStype(), at: currentMenu.items.count - 15)
  1536. // currentMenu.insertItem(self.setTTSStype(), at: currentMenu.items.count - 15)
  1537. if let anno = self.listView.activeAnnotation, anno.isKind(of: CPDFStampAnnotation.self) {
  1538. // currentMenu.insertItem(self.setRotateStype(), at: currentMenu.items.count - 15)
  1539. } else {
  1540. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1541. currentMenu.insertItem(self.setShareStype(), at: currentMenu.items.count - 15)
  1542. }
  1543. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1544. }
  1545. }
  1546. if listView.activeAnnotation == nil && listView.currentSelection == nil{
  1547. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1548. if(listView.toolMode == .selectToolMode) {
  1549. if NSIsEmptyRect(listView.currentSelectionRect()) {
  1550. currentMenu.insertItem(self.zoomSelectionMenuItem(), at: 0)
  1551. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1552. }
  1553. currentMenu.insertItem(self.printingMenu(), at: 0)
  1554. currentMenu.insertItem(self.setTTSStype(), at: 0)
  1555. currentMenu.insertItem(self.setCropStype(), at: 0)
  1556. currentMenu.insertItem(self.setSnapshotStype(), at: 0)
  1557. let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
  1558. export.submenu = self.exportMenu()
  1559. currentMenu.insertItem(export, at: currentMenu.items.count)
  1560. }else{
  1561. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  1562. currentMenu.insertItem(self.setTTSStype(), at: 2)
  1563. currentMenu.insertItem(self.setCropStype(), at: 2)
  1564. currentMenu.insertItem(self.setSnapshotStype(), at: 2)
  1565. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  1566. currentMenu.insertItem(self.addOutlineStype(), at: 2)
  1567. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  1568. currentMenu.insertItem(self.enterAnnotationStype(), at: 2)
  1569. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  1570. if(currentMenu.items.count > 4) {
  1571. currentMenu.insertItem(NSMenuItem.separator(), at: 5)
  1572. }
  1573. if(currentMenu.items.count > 5) {
  1574. currentMenu.insertItem(self.addBookmarkMenu(), at: 6)
  1575. }
  1576. // if (currentMenu.items.count > 6 && self.isReadMode) {
  1577. // currentMenu.removeItem(currentMenu.item(withTitle: "Zoom")!)
  1578. // }
  1579. // currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
  1580. currentMenu.insertItem(self.setAutoScrollStype(), at: currentMenu.items.count)
  1581. }
  1582. currentMenu.insertItem(self.setAnnotationToolStype(), at: 5)
  1583. }
  1584. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1585. currentMenu.insertItem(self.setAITranslateStype(), at: 0)
  1586. currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
  1587. currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
  1588. for item in currentMenu.items {
  1589. if (item.action == NSSelectorFromString("menuItemClick_HidenorShowNote:")) {
  1590. // 显示与隐藏注释 item action 截取
  1591. item.action = #selector(menuItemClick_HidenorShowNote)
  1592. item.target = self
  1593. break
  1594. }
  1595. }
  1596. }
  1597. func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  1598. var addRedact = false
  1599. for anno in annotations {
  1600. if (anno.isKind(of: CPDFRedactAnnotation.self)) {
  1601. addRedact = true
  1602. } else if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  1603. anno.contents = pdfPage?.string(for: anno.bounds) ?? ""
  1604. }
  1605. }
  1606. self.model.hasAddRedact = addRedact
  1607. if /*self.isReadMode || */self.listView.toolMode == .moveToolMode {
  1608. self.listView.toolMode = .textToolMode
  1609. self.listView.annotationType = .unkown
  1610. self.toolbarController.toolbarType = .Annatiton
  1611. }
  1612. if (self.model.rightMouseEventing) {
  1613. self.model.rightMouseEventing = false
  1614. if (self.toolbarController.ignoreCurrentAnnotationTypeChange && self.listView.annotationType == .ink) {
  1615. self.listView.toolMode = .textToolMode
  1616. self.listView.annotationType = .unkown
  1617. }
  1618. }
  1619. self.toolbarController.ignoreCurrentAnnotationTypeChange = false
  1620. self.leftSideViewController.refreshUIForAddAnnotation(annos: annotations, page: pdfPage)
  1621. }
  1622. func pdfListViewRemoveAnnotations(_ pdfListView: CPDFListView!, forRemove annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  1623. self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: annotations, page: pdfPage)
  1624. }
  1625. func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
  1626. if (!self.listView.isEqual(to: pdfListView)) {
  1627. return
  1628. }
  1629. if (self.listView.toolMode != .selectToolMode) {
  1630. return
  1631. }
  1632. if (self.topTipBox.isHidden || self.topTipBox.contentView?.subviews.count == 0) {
  1633. return
  1634. }
  1635. let tipView = self.topTipBox.contentView?.subviews.first
  1636. if (tipView?.isKind(of: KMCropTipView.self) == false) {
  1637. return
  1638. }
  1639. (tipView as! KMCropTipView).setString(string: "请按 Enter 键确定裁剪区域")
  1640. }
  1641. func pdfListViewKeyDowClosePanel(_ speedy: CPDFViewSidebarSpeedMode, event theEvent: NSEvent!) {
  1642. if(speedy == .right) {
  1643. self.toggleRightPane()
  1644. } else if (speedy == .left) {
  1645. self.menuItemAction_hiddenLeftSide(speedy)
  1646. }
  1647. }
  1648. func pdfListViewEventMarkupColor(with annotation: CPDFAnnotation!) -> [NSColor]! {
  1649. if (annotation.isKind(of: CPDFMarkupAnnotation.self)) {
  1650. if (annotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  1651. return KMAnnotationPropertiesColorManager.manager.markHighlightColors
  1652. } else {
  1653. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  1654. }
  1655. } else {
  1656. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  1657. }
  1658. }
  1659. func pdfListViewHaveDocumentAttribute() -> Bool {
  1660. if(!self.listView.document.allowsCopying) {
  1661. self.removeOwnerPassword()
  1662. return false
  1663. }
  1664. return true
  1665. }
  1666. func pdfListView(_ sender: CPDFListView!, showSnapshotAtPageNumber pageNum: Int, for rect: NSRect, scaleFactor: CGFloat, autoFits: Bool) {
  1667. let swc = KMSnapshotWindowController(windowNibName: "SnapshotWindow")
  1668. swc.delegate = self
  1669. swc.setPdfDocument(self.listView.document, goToPageNumber: pageNum, rect: rect, scaleFactor: scaleFactor, autoFits: autoFits)
  1670. swc.forceOnTop = self.interactionMode != .normal
  1671. self.myDocument?.addWindowController(swc)
  1672. }
  1673. func pdfListView(_ pdfView: CPDFListView!, documentDataDidChanged docData: Any!, withInfo info: [AnyHashable : Any]!) {
  1674. if let data = info?[CPDFListView.outlineKey] as? Bool, data { // 大纲改变
  1675. guard let ol = docData as? CPDFOutline else {
  1676. return
  1677. }
  1678. let add = info?[CPDFListView.outlineAddKey] as? Bool ?? false
  1679. let remove = info?[CPDFListView.outlineRemoveKey] as? Bool ?? false
  1680. if add {
  1681. self.leftSideViewController.addOutlineAfter(ol)
  1682. }
  1683. if remove {
  1684. self.leftSideViewController.removeOutlineAfter(ol)
  1685. }
  1686. let demote = info?[CPDFListView.outlineDemoteKey] as? Bool ?? false
  1687. let promote = info?[CPDFListView.outlinePromoteKey] as? Bool ?? false
  1688. if demote {
  1689. self.leftSideViewController.demoteOutlineAfter(ol)
  1690. }
  1691. if promote {
  1692. self.leftSideViewController.promoteOutlineAfter(ol)
  1693. }
  1694. }
  1695. }
  1696. }