KMMainViewController+UI.swift 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902
  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. if self.aiTipView != nil {
  668. self.updateAITipViewShowState()
  669. }
  670. // self.aiTipView.isHidden = true
  671. UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
  672. UserDefaults.standard.synchronize()
  673. }
  674. @objc func closeReadModel() {
  675. if self.isReadMode {
  676. self.model.isShowBOTA = false
  677. self.readModelView.isHidden = true
  678. self.isReadMode = false
  679. self.readModelView.isHidden = true
  680. self.leftSideViewController.refreshMethodType(methodType: readLeftMethodType)
  681. self.model.leftPanelOpen = readLeftPanelOpen
  682. self.model.rightPanelIsOpen = readRightPanelOpen
  683. self.model.lastLeftPanWidth = readLastLeftPanWidth
  684. if self.model.leftPanelOpen {
  685. self.openLeftPane()
  686. }
  687. self.closeRightPane()
  688. self.toolbarController.toolbarType = .None
  689. self.toolbarController.cancelSelected(KMDocumentViewDisplayToolbarItemIdentifier)
  690. // if self.rightPanelIsOpen {
  691. // self.rightPanelIsOpen = false
  692. //// self.toolbarController.selectItem(KMRightControlToolbarItemIdentifier)
  693. // self.openRightPane()
  694. // }
  695. //
  696. // if readToolbarItemIdentifier.count == 0 {
  697. // self.toolbarController.toolbarType = .None
  698. // } else {
  699. // self.toolbarController.selectItem(readToolbarItemIdentifier)
  700. // }
  701. // self.toolbarController.selectItem(KMDocumentViewDisplayToolbarItemIdentifier)
  702. self.leftSideViewController.showPanelView(show: readLeftViewShowPanel)
  703. if readLeftViewShowPanel {
  704. self.toolbarController.selectItem(KMLeftControlToolbarItemIdentifier)
  705. }
  706. self.toolbarController.view.isHidden = false
  707. self.listView.toolMode = readToolMode
  708. self.listView.annotationType = readAnnotationType
  709. // self.toolbarController.toolbarType = .viewSetting
  710. } else {
  711. self.toolbarController.toolbarType = .None
  712. }
  713. if readAlertView != nil {
  714. readAlertView?.removeFromSuperview()
  715. }
  716. readAlertView = CustomAlertView.alertView(message: NSLocalizedString("Read Mode Off", comment: ""), fromView: self.view, withStyle: .blue, backgroundColor: NSColor.km_init(hex: "#36383B"))
  717. self.updateAITipViewShowState()
  718. UserDefaults.standard.set(isReadMode, forKey: "kKMPDFViewIsReadMode")
  719. UserDefaults.standard.synchronize()
  720. }
  721. @objc func addOutLineItemAction() {
  722. let labelString = "\(KMLocalizedString("Page", nil)) \((self.listView?.currentPageIndex ?? 0) + 1)"
  723. let label = self.listView?.currentSelection?.string() ?? labelString
  724. let dest = self.listView?.currentDestination
  725. if let row = self.leftSideViewController.selectedRowIndexes().last {
  726. if let ol = self.leftSideViewController.tocOutlineView.item(atRow: row) as? CPDFOutline {
  727. _ = self.listView.addOutline(for: ol.parent, label: label, dest: dest, at: ol.index+1)
  728. } else {
  729. let idx = self.listView?.document?.outlineRoot()?.numberOfChildren ?? 0
  730. _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
  731. }
  732. } else {
  733. let idx = self.listView?.document?.outlineRoot()?.numberOfChildren ?? 0
  734. _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
  735. }
  736. }
  737. @objc func showTTSView() {
  738. self.showTTSWindow()
  739. }
  740. @objc func showShareAction() {
  741. }
  742. @objc func lookUpAction() {
  743. }
  744. @objc func searchBaiduAction() {
  745. }
  746. @objc func showInfoInFinder() {
  747. }
  748. @objc func NextPageAction() {
  749. }
  750. @objc func PreviousPageAction() {
  751. }
  752. @objc func TranslateItemAction() {
  753. }
  754. @objc func AutoScrollItemAction() {
  755. //增加判断,如果是正在滚动,就停止,否则就开始滚动
  756. self.listView.autoFlow()
  757. }
  758. @objc func shareFromService(sender: NSMenuItem) {
  759. if ((NSApp.mainWindow?.windowController is KMBrowserWindowController) == false) {
  760. return
  761. }
  762. var string = ""
  763. if let freeTextAnnotation = listView.activeAnnotation as? CPDFFreeTextAnnotation {
  764. string = freeTextAnnotation.contents ?? ""
  765. } else if let markupAnnotation = listView.activeAnnotation as? CPDFMarkupAnnotation {
  766. if let page = markupAnnotation.page {
  767. if let selection = page.selection(for: markupAnnotation.bounds) {
  768. string = selection.string()
  769. }
  770. }
  771. } else {
  772. string = listView.currentSelection.string()
  773. }
  774. let windowControler = NSApp.mainWindow?.windowController as! KMBrowserWindowController
  775. let model: CTTabStripModel = windowControler.browser.tabStripModel
  776. if (model.count() <= 0) {
  777. return
  778. }
  779. if (model.activeTabContents().isHome) {
  780. return
  781. }
  782. let document: KMMainDocument = model.activeTabContents() as! KMMainDocument
  783. if string.count > 0 {
  784. let represent : NSSharingService = sender.representedObject as! NSSharingService
  785. represent.perform(withItems: [string])
  786. return
  787. }
  788. let represent = sender.representedObject as? NSSharingService
  789. represent?.perform(withItems: [string])
  790. }
  791. @objc func cutAction(sender: NSMenuItem) {
  792. }
  793. @objc func deleteAction(sender: NSMenuItem) {
  794. }
  795. @objc func ColorsItemAction(sender: NSMenuItem) {
  796. }
  797. @objc func LinesItemAction(sender: NSMenuItem) {
  798. }
  799. @objc func EditNoteItemAction(sender: NSMenuItem) {
  800. }
  801. @objc func AITranslateItemAction(sender: NSMenuItem) {
  802. self.showAITypeChooseView(aiConfigType: .translate)
  803. }
  804. @objc func AIProofreadItemAction(sender: NSMenuItem) {
  805. self.showAITypeChooseView(aiConfigType: .proofreading)
  806. }
  807. @objc func AIRewriteItemAction(sender: NSMenuItem) {
  808. self.showAITypeChooseView(aiConfigType: .reWriting)
  809. }
  810. // @objc func highlightLinks() {
  811. // let highlightLinks = KMPreferenceManager.shared.highlightLinks
  812. // KMPreferenceManager.shared.highlightLinks = !highlightLinks
  813. // }
  814. }
  815. // MARK: - KMEditImagePropertyViewControllerDelegate
  816. extension KMMainViewController: KMEditImagePropertyViewControllerDelegate {
  817. func editImagePropertyViewControllerDidChanged(controller: KMEditImagePropertyViewController, type: KMEditImagePropertyViewControllerChangeType) {
  818. self.model.isPDFTextImageEdited = true
  819. }
  820. }
  821. // MARK: - KMSnapshotWindowControllerDelegate
  822. extension KMMainViewController: KMSnapshotWindowControllerDelegate {
  823. func snapshotControllerWillClose(_ controller: KMSnapshotWindowController) {
  824. self.leftSideViewController.snapshotControllerWillClose(controller)
  825. }
  826. func snapshotController(_ controller: KMSnapshotWindowController, miniaturizedRect isMiniaturize: Bool) -> NSRect {
  827. if isMiniaturize && self.interactionMode != .presentation {
  828. if self.interactionMode != .legacyFullScreen && self.model.leftPanelOpen == false {
  829. self.toggleLeftPane()
  830. } else if self.interactionMode == .legacyFullScreen {
  831. // else if ([self interactionMode] == SKLegacyFullScreenMode && ([rightSideWindow state] == NSDrawerClosedState || [rightSideWindow state] == NSDrawerClosingState)) {
  832. // [rightSideWindow expand];
  833. // [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(hideRightSideWindow:) userInfo:NULL repeats:NO];
  834. }
  835. var row = NSNotFound
  836. for (i,sp) in self.leftSideViewController.snapshots.enumerated() {
  837. if controller.isEqual(sp.windowC) {
  838. row = i
  839. }
  840. }
  841. if (row != NSNotFound) {
  842. self.leftSideViewController.leftView.segmentedControl.selectedSegment = 3
  843. self.leftSideViewController.snapshotTableView.scrollRowToVisible(row)
  844. }
  845. }
  846. return self.leftSideViewController.snapshotController(controller, miniaturizedRect: isMiniaturize)
  847. }
  848. func snapshotControllerDidFinishSetup(_ controller: KMSnapshotWindowController) {
  849. self.leftSideViewController.snapshotControllerDidFinishSetup(controller)
  850. }
  851. }
  852. // MARK: - CPDFDocumentDelegate
  853. extension KMMainViewController: CPDFDocumentDelegate {
  854. func documentDidBeginDocumentFind(_ document: CPDFDocument!) {
  855. self.leftSideViewController.documentDidBeginFind()
  856. // [statusBar setProgressIndicatorStyle:SKProgressIndicatorBarStyle];
  857. // [[statusBar progressIndicator] setMaxValue:[[note object] pageCount]];
  858. // [[statusBar progressIndicator] setDoubleValue:0.0];
  859. // [statusBar startAnimation:self];
  860. // [self willChangeValueForKey:SEARCHRESULTS_KEY];
  861. // [self willChangeValueForKey:GROUPEDSEARCHRESULTS_KEY];
  862. }
  863. func documentDidEndDocumentFind(_ document: CPDFDocument!) {
  864. self.leftSideViewController.documentDidEndFind()
  865. // [self didChangeValueForKey:GROUPEDSEARCHRESULTS_KEY];
  866. // [self didChangeValueForKey:SEARCHRESULTS_KEY];
  867. // [statusBar stopAnimation:self];
  868. // [statusBar setProgressIndicatorStyle:SKProgressIndicatorNone];
  869. // NSArray *highlights = [[NSArray alloc] initWithArray:searchResults copyItems:YES];
  870. // [highlights setValue:[NSColor yellowColor] forKey:@"color"];
  871. // [self.pdfView setHighlightedSelections:highlights];
  872. // [highlights release];
  873. }
  874. }
  875. // MAKR: - CPDFViewDelegate,CPDFListViewDelegate
  876. extension KMMainViewController: CPDFViewDelegate,CPDFListViewDelegate {
  877. func pdfViewDocumentDidLoaded(_ pdfView: CPDFView!) {
  878. self.dealDocumentDidLoaded()
  879. let notification = Notification(name: Notification.Name(rawValue: "pdfViewDocumentDidLoaded"))
  880. self.preferenceDidChangeNotification(notification:notification)
  881. let leftWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeLeftSidePaneWidthKey) as? NSNumber ?? NSNumber(value: self.model.panelWidth + functionWidth)
  882. let rightWidthNumber = UserDefaults.standard.object(forKey: CPDFOfficeRightSidePaneWidthKey) as? NSNumber ?? NSNumber(value: self.model.defaultRightWidth)
  883. applyLeftSideWidth(leftWidthNumber.doubleValue, rightSideWidth: rightWidthNumber.doubleValue)
  884. self.updatePageIndicatoreType()
  885. }
  886. func pdfViewCurrentPageDidChanged(_ pdfView: CPDFView!) {
  887. self.updatePageIndicatoreType()
  888. NotificationCenter.default.post(name: NSNotification.Name.init(rawValue: "KMPDFViewCurrentPageDidChanged"), object: self.document)
  889. // KMPrint("KMPDFViewCurrentPageDidChanged")
  890. }
  891. func pdfViewScaleDidChanged(_ pdfView: CPDFView!) {
  892. self.toolbarController.mainToolBarView?.zoomTextField.stringValue = "\(Int(self.listView.scaleFactor * 100))%"
  893. self.updateZoomInOutButtonState()
  894. // KMPrint("pdfViewScaleDidChanged")
  895. }
  896. func pdfViewDidClick(onLink pdfView: CPDFView!, withURL url: String!) {
  897. if let urlString = url, urlString == kKMPurchaseProductURLString {
  898. //跳转订阅比较表
  899. let _ = KMComparativeTableViewController.show(window: NSApp.mainWindow ?? NSWindow())
  900. return
  901. }
  902. KMTools.openURL(urlString: url)
  903. }
  904. func pdfViewPerformURL(_ pdfView: CPDFView!, withContent content: String!) {
  905. KMPrint("pdfViewPerformURL")
  906. if content != nil {
  907. NSWorkspace.shared.open(URL(string: content)!)
  908. } else {
  909. let alert = NSAlert()
  910. alert.alertStyle = .critical
  911. alert.informativeText = NSLocalizedString("The hyperlink is invalid.", comment: "")
  912. alert.messageText = ""
  913. alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
  914. alert.runModal()
  915. return
  916. }
  917. }
  918. func pdfViewPerformPrint(_ pdfView: CPDFView!) {
  919. KMPrint("pdfViewPerformPrint")
  920. self.showPrintWindow()
  921. }
  922. func pdfViewPerformGo(toPage pdfView: CPDFView!) {
  923. KMPrint("pdfViewPerformGo")
  924. }
  925. func pdfViewOpenPDF(_ pdfView: CPDFView!, forRemoteGoTo action: CPDFAction!) {
  926. KMPrint("pdfViewOpenPDF")
  927. }
  928. func pdfViewPerformReset(_ pdfView: CPDFView!) {
  929. KMPrint("pdfViewPerformReset")
  930. self.listView.resetFormAnnotation()
  931. }
  932. func pdfViewEditingBlockDidChanged(_ pdfView: CPDFView!) {
  933. KMPrint("pdfViewEditingBlockDidChanged")
  934. }
  935. func pdfViewAsBookBookmark() -> NSImage! {
  936. return NSImage(named: "KMImageNameUXIconPDFViewBookMark")!
  937. }
  938. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  939. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText {
  940. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  941. self.rightSideViewController.eidtPDFTextProperty.updateTextTextPresuppositionState()
  942. }
  943. }
  944. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  945. let areas = self.listView.editingAreas()
  946. if areas == nil || areas?.count ?? 0 == 0 {
  947. if self.listView.toolMode == .editPDFToolMode {
  948. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  949. if self.listView.isEditImage {
  950. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  951. } else {
  952. // if self.listView.annotationType == .addImage {
  953. // self.closeRightPane()
  954. // }
  955. if self.listView.annotationType == .addImage {
  956. if self.rightSideViewController.eidtPDFImageProperty != nil {
  957. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  958. }
  959. }
  960. // self.openRightPane()
  961. }
  962. } else {
  963. self.closeRightPane()
  964. }
  965. } else {
  966. self.rightSideViewController.isHidden = true
  967. self.closeRightPane()
  968. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  969. self.rightSideViewController.eidtPDFTextProperty.initData()
  970. }
  971. }
  972. if self.listView.isEdited() {
  973. self.recordIsPDFDocumentEdited(type: .editText)
  974. }
  975. if self.listView.annotationType != .addText {
  976. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  977. }
  978. return
  979. }
  980. self.model.isPDFTextImageEdited = true
  981. if (self.listView.annotationType == .addImage) && areas!.count > 0 {
  982. var isImageArea = false
  983. for i in 0 ... areas!.count-1 {
  984. if areas![i] is CPDFEditImageArea {
  985. isImageArea = true
  986. }
  987. }
  988. if isImageArea {
  989. // self.rightSideViewController.view.isHidden = false
  990. self.rightSideViewController.isHidden = false
  991. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddImage {
  992. self.rightSideViewController.subViewType = .EditPDFAddImage
  993. self.rightSideViewController.eidtPDFImageProperty.reloadData()
  994. }
  995. self.openRightPane()
  996. } else {
  997. // self.rightSideViewController.view.isHidden = true
  998. self.rightSideViewController.isHidden = true
  999. self.closeRightPane()
  1000. }
  1001. } else if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1002. // self.rightSideViewController.view.isHidden = false
  1003. self.rightSideViewController.isHidden = false
  1004. if self.listView.editingSelectionString().count != 0 {
  1005. self.rightSideViewController.eidtPDFTextProperty.reloadData()
  1006. } else {
  1007. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1008. }
  1009. self.openRightPane()
  1010. } else {
  1011. var textsAreas : [CPDFEditTextArea] = []
  1012. var imagesAreas : [CPDFEditImageArea] = []
  1013. if self.listView.editingAreas()?.count ?? 0 < 1 {
  1014. return
  1015. }
  1016. for i in 0 ... areas!.count-1 {
  1017. if areas![i] is CPDFEditTextArea {
  1018. textsAreas.append(areas![i] as! CPDFEditTextArea)
  1019. }
  1020. if areas![i] is CPDFEditImageArea {
  1021. imagesAreas.append(areas![i] as! CPDFEditImageArea)
  1022. }
  1023. }
  1024. if textsAreas.count > 0 && textsAreas.count == areas!.count {
  1025. // self.rightSideViewController.view.isHidden = false
  1026. self.rightSideViewController.isHidden = false
  1027. self.rightSideViewController.subViewType = .EditPDFAddText
  1028. self.rightSideViewController.eidtPDFTextProperty?.reloadData()
  1029. self.openRightPane()
  1030. } else if imagesAreas.count > 0 {
  1031. // self.rightSideViewController.view.isHidden = false
  1032. self.rightSideViewController.isHidden = false
  1033. self.rightSideViewController.subViewType = .EditPDFAddImage
  1034. self.rightSideViewController.eidtPDFImageProperty?.reloadData()
  1035. self.openRightPane()
  1036. }
  1037. }
  1038. if self.listView.isEdited() {
  1039. self.recordIsPDFDocumentEdited(type: .editText)
  1040. if self.listView.annotationType != .addText {
  1041. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView.document)
  1042. }
  1043. }
  1044. }
  1045. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  1046. if editArea != nil && (editArea is CPDFEditImageArea){
  1047. self.listView.cropAreas = editArea as? CPDFEditImageArea
  1048. }
  1049. }
  1050. //编辑PDF 创建图片区域回调
  1051. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1052. if self.listView.isEditImage {
  1053. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1054. } else {
  1055. let panel = NSOpenPanel()
  1056. panel.allowsMultipleSelection = false
  1057. panel.allowedFileTypes = ["png","jpg"]
  1058. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  1059. if response == .OK {
  1060. var filePath = panel.url?.path
  1061. var image = NSImage.init(contentsOf: panel.url!)
  1062. //图片自适应范围
  1063. if image != nil {
  1064. var imageRect = rect
  1065. let imageSize = image!.size
  1066. var previewSize = rect.size
  1067. var isChangeSize = false
  1068. if previewSize.width == 0 && previewSize.height == 0 {
  1069. previewSize = CGSize(width: 500, height: 500)
  1070. isChangeSize = true
  1071. }
  1072. let scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  1073. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  1074. if isChangeSize {
  1075. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  1076. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  1077. } else {
  1078. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  1079. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  1080. }
  1081. imageRect.size = newSize
  1082. let limitWidth = 1920.0
  1083. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  1084. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  1085. targetSize: CGSize(width: limitWidth, height: limitWidth),
  1086. maxSizeInBytes: 1024 * 1024 * 5,
  1087. targetCompression: 1.0)
  1088. }
  1089. //自适应page
  1090. let pageRect = self.listView.currentPage().bounds
  1091. if imageRect.width > pageRect.width ||
  1092. imageRect.height > pageRect.height {
  1093. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  1094. imageRect = CGRect(x: imageRect.origin.x,
  1095. y: imageRect.origin.y,
  1096. width: imageRect.width * pageScale,
  1097. height: imageRect.height * pageScale)
  1098. }
  1099. if imageRect.origin.x < 0 {
  1100. imageRect.origin.x = 5
  1101. }
  1102. if imageRect.origin.y < 0 {
  1103. imageRect.origin.y = 5
  1104. }
  1105. if imageRect.origin.x + imageRect.width > pageRect.width ||
  1106. imageRect.origin.y + imageRect.height > pageRect.height {
  1107. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  1108. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  1109. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  1110. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  1111. }
  1112. DispatchQueue.main.async {
  1113. self.listView.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  1114. self.model.isPDFTextImageEdited = true
  1115. self.recordIsPDFDocumentEdited(type: .editImage)
  1116. // self.asyncSaveDocument { params in
  1117. //
  1118. // }
  1119. }
  1120. }
  1121. }
  1122. }
  1123. }
  1124. }
  1125. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1126. // print(rect)
  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 model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  1134. let fontName = KMEditPDFTextManager.manager.fetchFontName(fontName: model.fontName)
  1135. let fontSize = model.fontSize
  1136. let fontColor = model.color
  1137. let fontAlign = model.alignment
  1138. let fontStyle = KMEditPDFTextManager.manager.fetchFontStyle(fontName: model.fontName)
  1139. NSColorPanel.shared.color = fontColor
  1140. let font = KMEditPDFTextManager.manager.fetchFont(fontName: fontName, style: fontStyle, size: fontSize)
  1141. let style = NSMutableParagraphStyle()
  1142. style.alignment = fontAlign
  1143. let attributes = [NSAttributedString.Key.font:font, NSAttributedString.Key.foregroundColor:fontColor,NSAttributedString.Key.paragraphStyle:style] as [NSAttributedString.Key : Any]
  1144. self.listView.createEmptyStringBounds(newrect,withAttributes: attributes as [NSAttributedString.Key : Any], page: page)
  1145. if self.rightSideViewController != nil && self.rightSideViewController.subViewType == .EditPDFAddText && self.listView.annotationType == .addText {
  1146. self.rightSideViewController.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1147. }
  1148. // self.asyncSaveDocument { params in
  1149. //
  1150. // }
  1151. }
  1152. func pdfListViewKeyDownIsContinue(_ pdfListView: CPDFListView!, theEvent: NSEvent!) -> Bool {
  1153. let command = theEvent.modifierFlags.contains(.command)
  1154. let control = theEvent.modifierFlags.contains(.control)
  1155. KMPrint(theEvent.keyCode)
  1156. if (theEvent.keyCode == 11 && command) { // command + B [添加书签]
  1157. self.menuItemBookMarkClick_add(sender: NSMenuItem())
  1158. return false
  1159. } else if (command && control && theEvent.keyCode == 14) { // command + control + E [注释 橡皮擦]
  1160. return false
  1161. } else if (theEvent.keyCode == 123) { // 向左
  1162. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1163. return false
  1164. } else {
  1165. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToPreviousPage()) {
  1166. self.listView.goToPreviousPage(nil)
  1167. return false
  1168. }
  1169. }
  1170. } else if (theEvent.keyCode == 126) { // 向上
  1171. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1172. return false
  1173. } else {
  1174. if (self.listView.isContinousScroll()) {
  1175. return true
  1176. }
  1177. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToPreviousPage()) {
  1178. self.listView.goToPreviousPage(nil)
  1179. return false
  1180. }
  1181. }
  1182. } else if (theEvent.keyCode == 124) { // 向右
  1183. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1184. return false
  1185. } else {
  1186. if (self.pdfViewCanHorizontalScroll() == false && self.listView.canGoToNextPage()) {
  1187. self.listView.goToNextPage(nil)
  1188. return false
  1189. }
  1190. }
  1191. } else if (theEvent.keyCode == 125) { // 向下
  1192. if(self.listView.isEditing() && !self.listView.isSelecteditAreaNotEdit()) {
  1193. return false
  1194. } else {
  1195. if (self.listView.isContinousScroll()) {
  1196. return true
  1197. }
  1198. if (self.pdfViewCanVerticalScroll() == false && self.listView.canGoToNextPage()) {
  1199. self.listView.goToNextPage(nil)
  1200. return false
  1201. }
  1202. }
  1203. } else if (theEvent.keyCode == 36) {
  1204. if self.listView.annotationType == .addImage || self.listView.annotationType == .addText {
  1205. if self.listView.isEditImage {
  1206. self.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1207. }
  1208. }
  1209. }
  1210. if theEvent.keyCode == 53 {
  1211. if self.isReadMode {
  1212. self.closeReadModel()
  1213. }
  1214. self.leftSideViewCancelSelect()
  1215. if (self.toolbarController.toolbarType.isToolMode()) {
  1216. self.toolbarController.selectItem(self.toolbarController.toolbarType.itemIdentifier())
  1217. }
  1218. }
  1219. return true
  1220. }
  1221. func pdfListViewMenuValidate(_ pdfListView: CPDFListView!, menuItem: NSMenuItem!, isTakesEffect: UnsafeMutablePointer<ObjCBool>!) -> Bool {
  1222. guard let action = menuItem.action else {
  1223. isTakesEffect.pointee = false
  1224. return false
  1225. }
  1226. if (KMSystemMenu.isEditSelector(sel: action)) {
  1227. if (KMSystemMenu.Edit.deleteSelector == action) {
  1228. isTakesEffect.pointee = true
  1229. return self.listView.activeAnnotations.count > 0
  1230. } else if (KMSystemMenu.Edit.copySelector == action) {
  1231. isTakesEffect.pointee = true
  1232. return true//self.listView.canCopy()
  1233. } else if (KMSystemMenu.Edit.cutSelector == action) {
  1234. isTakesEffect.pointee = true
  1235. return self.listView.canCopy()
  1236. } else if (KMSystemMenu.Edit.pasteSelector == action) {
  1237. isTakesEffect.pointee = true
  1238. return self.listView.canPaste()
  1239. }
  1240. }
  1241. isTakesEffect.pointee = false
  1242. return false
  1243. }
  1244. //MARK: -CPDFListViewDelegate
  1245. func cPDFListView(_ pdfListView: CPDFListView, didDelete annotation: CPDFAnnotation, in pdfPage: CPDFPage) {
  1246. self.leftSideViewController.updateThumbnail(at: Int(pdfPage.pageIndex()))
  1247. }
  1248. func pdfListViewChangeatioActiveAnnotations(_ pdfListView: CPDFListView!, forActiveAnnotations annotations: [CPDFAnnotation]!, isRightMenu: Bool) {
  1249. self.view.window?.makeFirstResponder(self.listView)
  1250. if isRightMenu {
  1251. } else if annotations.count > 0 {
  1252. if annotations.count > 1 {
  1253. let fristAnnotation = annotations.first
  1254. var isSameAnnotation = true
  1255. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1256. for annotation in annotations {
  1257. let cunrrentClassName = NSStringFromClass(annotation.classForCoder)
  1258. if (className == "CPDFSquareAnnotation") ||
  1259. (className == "CPDFCircleAnnotation") ||
  1260. (className == "CPDFLineAnnotation") {
  1261. if (cunrrentClassName != "CPDFSquareAnnotation") &&
  1262. (cunrrentClassName != "CPDFCircleAnnotation") &&
  1263. (cunrrentClassName != "CPDFLineAnnotation") {
  1264. isSameAnnotation = false
  1265. }
  1266. } else {
  1267. if className != cunrrentClassName {
  1268. isSameAnnotation = false
  1269. }
  1270. }
  1271. }
  1272. if isSameAnnotation == false {
  1273. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1274. // self.closeRightPane()
  1275. } else {
  1276. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1277. self.openRightPane()
  1278. }
  1279. } else {
  1280. let fristAnnotation = annotations.first
  1281. let className = NSStringFromClass(fristAnnotation!.classForCoder)
  1282. if self.isReadMode {
  1283. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1284. self.closeRightPane()
  1285. } else {
  1286. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1287. if className != "CPDFStampAnnotation" &&
  1288. className != "CPDFSignatureAnnotation" &&
  1289. className != "CPDFListStampAnnotation" {
  1290. self.openRightPane()
  1291. }
  1292. }
  1293. }
  1294. } else if (annotations.count == 0){
  1295. if pdfListView.annotationType == .unkown {
  1296. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1297. self.closeRightPane()
  1298. } else {
  1299. if self.isReadMode {
  1300. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: false)
  1301. self.closeRightPane()
  1302. } else {
  1303. self.rightSideViewController?.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1304. self.openRightPane()
  1305. }
  1306. }
  1307. }
  1308. }
  1309. func pdfListViewChangedAnnotationType(_ pdfListView: CPDFListView!, for annotationType: CAnnotationType) {
  1310. if(annotationType == .unkown) {
  1311. // self.rightSideViewController.view.isHidden = true
  1312. self.rightSideViewController.isHidden = true
  1313. self.closeRightPane()
  1314. }
  1315. let aType = annotationType
  1316. if aType.isMarkup() || aType == .anchored || aType == .freeText || aType.isSquare() || aType == .link {
  1317. KMDataManager.ud_set(annotationType.rawValue, forKey: SKLastAnnotationModeKey)
  1318. }
  1319. }
  1320. ///开始定位链接注释
  1321. func pdfListViewLinkDestinationStart(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1322. if self.locationPageView.superview == nil {
  1323. self.locationPageView.frame = CGRect(x: 0, y: pdfListView.frame.maxY-32, width: pdfListView.frame.width, height: 32)
  1324. pdfListView.addSubview(self.locationPageView)
  1325. }
  1326. }
  1327. ///刷新链接注释
  1328. func pdfListViewLinkDestinationEnd(_ pdfListView: CPDFListView!, withActiveAnnotation annotation: CPDFAnnotation!) {
  1329. if self.locationPageView.superview != nil {
  1330. self.locationPageView.removeFromSuperview()
  1331. }
  1332. if self.rightSideViewController.subViewType == .AnnotationProperts && pdfListView.annotationType == .link {
  1333. self.rightSideViewController.reloadDataWithPDFView(pdfView: pdfListView, isShow: true)
  1334. }
  1335. }
  1336. func pdfListViewMenuItemsEditing(at point: CGPoint, for page: CPDFPage!, menuItems: [NSMenuItem]!) -> [NSMenuItem]! {
  1337. if (listView.toolMode != CToolMode.editPDFToolMode) {
  1338. return menuItems
  1339. }
  1340. var tMenuItems = menuItems;
  1341. if(listView.isSelectEditCharRange() ||
  1342. listView.isSelecteditArea(with: point)) {
  1343. tMenuItems?.append(NSMenuItem.separator())
  1344. // tMenuItems?.append(self.fontColorMenuItem())
  1345. // tMenuItems?.append(self.fontSizeMenuItem())
  1346. }
  1347. let areas = self.listView.editingAreas() ?? []
  1348. if areas.count == 1 {
  1349. let fristAreas = areas.first
  1350. if fristAreas is CPDFEditImageArea {
  1351. self.listView.selectImageAreas = fristAreas as? CPDFEditImageArea
  1352. if self.listView.isEditImage {
  1353. tMenuItems?.removeAll()
  1354. tMenuItems?.append(self.corpImageMenuItem())
  1355. tMenuItems?.append(self.cancelCorpImageMenuItem())
  1356. tMenuItems?.append(self.restoreCorpImageMenuItem())
  1357. } else {
  1358. tMenuItems?.append(NSMenuItem.separator())
  1359. tMenuItems?.append(self.cutImageArea())
  1360. tMenuItems?.append(self.replaceImageArea())
  1361. tMenuItems?.append(self.exportImageArea())
  1362. }
  1363. } else {
  1364. if tMenuItems?.count != 1 {
  1365. tMenuItems?.swapAt(0, 1)
  1366. }
  1367. }
  1368. } else if areas.count == 0 {
  1369. tMenuItems?.append(NSMenuItem.separator())
  1370. tMenuItems?.append(self.addText())
  1371. tMenuItems?.append(self.addImage())
  1372. }
  1373. return tMenuItems
  1374. }
  1375. func tableMenu(_ menu: NSMenu, withTable table: KMTableAnnotation, point: CGPoint) -> NSMenu {
  1376. if table.currentCell.row >= 0 && table.currentCell.column >= 0 {
  1377. 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"]
  1378. let actions = ["formAnnotTextEdit:", "", "addRowAbove:", "addRowBelow:", "", "addColumnBefore:", "addColumnAfter:", "", "deleteRow:", "deleteColumn:", "deleteTabel", "cutCell:", "copyCell:", "pasteCell:", "pasteAndMatchStyle:", "deleteCellContents:", "clearAll:"]
  1379. for i in 0..<itemTitles.count {
  1380. var item: NSMenuItem? = nil
  1381. if itemTitles[i] == "" {
  1382. item = NSMenuItem.separator()
  1383. menu.insertItem(item!, at: i)
  1384. } else {
  1385. item = NSMenuItem(title: itemTitles[i], action: nil, keyEquivalent: "")
  1386. item!.target = self
  1387. item!.action = NSSelectorFromString(actions[i])
  1388. if itemTitles[i] == "Paste" /*&& !_copyCellData*/ {
  1389. item!.action = nil
  1390. } else if itemTitles[i] == "Paste and Match Style" /*&& !_copyCellData */{
  1391. item!.action = nil
  1392. } else if itemTitles[i] == "Add Row Above" {
  1393. let path1 = table.crossLines[table.rowNumber - table.currentCell.row]
  1394. let path2 = table.crossLines[table.rowNumber - table.currentCell.row - 1]
  1395. if (path1 as AnyObject).lineJoinStyle == NSBezierPath.LineJoinStyle.round && table.headerCount() >= 5 {
  1396. item!.action = nil
  1397. } else if (path2 as AnyObject).lineJoinStyle == NSBezierPath.LineJoinStyle.bevel && table.footerCount() >= 5 {
  1398. item!.action = nil
  1399. }
  1400. }
  1401. item!.title = NSLocalizedString(item!.title, comment: "")
  1402. item!.representedObject = NSValue(point: point)
  1403. menu.insertItem(item!, at: i)
  1404. }
  1405. }
  1406. } else {
  1407. let itemTitles = ["Cut", "Copy", "Paste", "Delete"]
  1408. let actions = ["cut:", "copy:", "paste:", "delete:"]
  1409. for i in 0..<itemTitles.count {
  1410. let item = NSMenuItem(title: itemTitles[i], action: nil, keyEquivalent: "")
  1411. item.target = self
  1412. item.action = NSSelectorFromString(actions[i])
  1413. item.title = NSLocalizedString(item.title, comment: "")
  1414. menu.insertItem(item, at: i)
  1415. item.representedObject = NSValue(point: point)
  1416. }
  1417. }
  1418. return menu
  1419. }
  1420. func pdfListViewMenu(forEvent pdfListView: CPDFListView!, for theEvent: NSEvent!, click menu: AutoreleasingUnsafeMutablePointer<NSMenu?>!, isMoveSelectAnno: Bool) {
  1421. self.mouseRightMenuEvent = theEvent
  1422. var currentMenu : NSMenu = menu.pointee!
  1423. if let activeAnno = listView.activeAnnotation as? KMTableAnnotation {//Table
  1424. var pagePoint = NSPoint()
  1425. _ = self.listView.pageAndPoint(&pagePoint, for: theEvent, nearest: true)
  1426. currentMenu.removeAllItems()
  1427. let annotation = activeAnno
  1428. annotation.completeEditCellText()
  1429. if !(NSIsEmptyRect(annotation.drawRect)) {
  1430. annotation.drawLine(pagePoint)
  1431. NotificationCenter.default.post(name: NSNotification.Name.KMPDFViewTableAnnotationDidChange, object: self, userInfo: ["point": NSValue(point: pagePoint)])
  1432. }
  1433. if (annotation.rowNumber - annotation.currentCell.row - 1) < 0 {
  1434. return
  1435. }
  1436. currentMenu = tableMenu(currentMenu, withTable: listView.activeAnnotation as! KMTableAnnotation, point: pagePoint)
  1437. listView.needsDisplay = true
  1438. return
  1439. }
  1440. if (listView.toolMode == .selectToolMode){
  1441. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1442. currentMenu.insertItem(self.printingMenu(), at: 3)
  1443. currentMenu.insertItem(self.setTTSStype(), at: 3)
  1444. currentMenu.insertItem(self.setCropStype(), at: 3)
  1445. currentMenu.insertItem(self.setSnapshotStype(), at: 3)
  1446. let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
  1447. export.submenu = self.exportMenu()
  1448. currentMenu.insertItem(export, at: 3)
  1449. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1450. if listView.activeAnnotation == nil{
  1451. currentMenu.insertItem(self.setAnnotationToolStype(), at: 3)
  1452. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1453. }
  1454. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 3)
  1455. currentMenu.insertItem(self.addReadModelStype(), at: currentMenu.items.count - 3)
  1456. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1457. currentMenu.insertItem(self.setAITranslateStype(), at: 0)
  1458. currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
  1459. currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
  1460. return
  1461. }
  1462. if (listView.toolMode == .moveToolMode || listView.toolMode == .magnifyToolMode){
  1463. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1464. currentMenu.insertItem(self.setTTSStype(), at: 0)
  1465. currentMenu.insertItem(self.setCropStype(), at: 0)
  1466. currentMenu.insertItem(self.setSnapshotStype(), at: 0)
  1467. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1468. currentMenu.insertItem(self.addOutlineStype(), at: 0)
  1469. currentMenu.insertItem(self.addBookmarkMenu(), at: 0)
  1470. if listView.activeAnnotation == nil{
  1471. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1472. currentMenu.insertItem(self.setAnnotationToolStype(), at: 0)
  1473. }
  1474. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1475. currentMenu.insertItem(self.setAITranslateStype(), at: 0)
  1476. currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
  1477. currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
  1478. return
  1479. }
  1480. if currentMenu.items.count > 3 {
  1481. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 3)
  1482. currentMenu.insertItem(self.addReadModelStype(), at: currentMenu.items.count - 3)
  1483. }
  1484. if listView.currentSelection != nil{
  1485. if listView.currentSelection.selectionType() == .text {
  1486. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1487. currentMenu.insertItem(self.setSearchBaiduStype(), at: 3)
  1488. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1489. currentMenu.insertItem(self.setLookUpStype(), at: 3)
  1490. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1491. currentMenu.insertItem(self.addOutlineStype(), at: 3)
  1492. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1493. if listView.activeAnnotation == nil{
  1494. currentMenu.insertItem(self.setAnnotationToolStype(), at: 3)
  1495. }
  1496. currentMenu.insertItem(self.setTTSStype(), at: 3)
  1497. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1498. currentMenu.insertItem(self.setShareStype(), at: 3)
  1499. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1500. }
  1501. currentMenu.insertItem(self.enterAnnotationStype(), at: 3)
  1502. currentMenu.insertItem(NSMenuItem.separator(), at: 3)
  1503. if listView.currentSelection.selectionType() == .image{
  1504. //
  1505. // currentMenu.insertItem(self.setCutStype(), at: 1)
  1506. // }
  1507. if listView.activeAnnotations.count > 0 {
  1508. currentMenu.insertItem(self.setDeleteStype(), at: 3)
  1509. currentMenu.insertItem(NSMenuItem.separator(), at: 6)
  1510. currentMenu.insertItem(self.setEditNoteStype(), at: 6)
  1511. currentMenu.insertItem(self.setRotateStype(), at: 6)
  1512. currentMenu.insertItem(self.setLinesStype(), at: 6)
  1513. currentMenu.insertItem(self.setColorsStype(), at: 6)
  1514. }
  1515. }
  1516. if listView.currentSelection.selectionType() == .text {
  1517. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1518. currentMenu.insertItem(self.setTranslateStype(), at: currentMenu.items.count)
  1519. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1520. // currentMenu.insertItem(self.setServicesStype(), at: currentMenu.items.count)
  1521. }
  1522. }
  1523. if listView.activeAnnotation != nil || isMoveSelectAnno {
  1524. if let data = self.listView?.activeAnnotation?.type?.lowercased(), data == "stamp"{
  1525. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1526. currentMenu.insertItem(self.enterAnnotationStype(), at: currentMenu.items.count - 15)
  1527. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1528. }else{
  1529. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1530. currentMenu.insertItem(self.enterAnnotationStype(), at: currentMenu.items.count - 15)
  1531. // currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1532. // currentMenu.insertItem(self.setAnnotationToolStype(), at: currentMenu.items.count - 15)
  1533. // currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1534. // currentMenu.insertItem(self.addBookmarkMenu(), at: currentMenu.items.count - 15)
  1535. // currentMenu.insertItem(self.addOutlineStype(), at: currentMenu.items.count - 15)
  1536. // currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1537. // currentMenu.insertItem(self.setSnapshotStype(), at: currentMenu.items.count - 15)
  1538. // currentMenu.insertItem(self.setCropStype(), at: currentMenu.items.count - 15)
  1539. // currentMenu.insertItem(self.setTTSStype(), at: currentMenu.items.count - 15)
  1540. if let anno = self.listView.activeAnnotation, anno.isKind(of: CPDFStampAnnotation.self) {
  1541. // currentMenu.insertItem(self.setRotateStype(), at: currentMenu.items.count - 15)
  1542. } else {
  1543. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1544. currentMenu.insertItem(self.setShareStype(), at: currentMenu.items.count - 15)
  1545. }
  1546. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count - 15)
  1547. }
  1548. }
  1549. if listView.activeAnnotation == nil && listView.currentSelection == nil{
  1550. currentMenu.insertItem(NSMenuItem.separator(), at: currentMenu.items.count)
  1551. if(listView.toolMode == .selectToolMode) {
  1552. if NSIsEmptyRect(listView.currentSelectionRect()) {
  1553. currentMenu.insertItem(self.zoomSelectionMenuItem(), at: 0)
  1554. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1555. }
  1556. currentMenu.insertItem(self.printingMenu(), at: 0)
  1557. currentMenu.insertItem(self.setTTSStype(), at: 0)
  1558. currentMenu.insertItem(self.setCropStype(), at: 0)
  1559. currentMenu.insertItem(self.setSnapshotStype(), at: 0)
  1560. let export = NSMenuItem(title: NSLocalizedString("Export", comment: ""), action: nil, target: self)
  1561. export.submenu = self.exportMenu()
  1562. currentMenu.insertItem(export, at: currentMenu.items.count)
  1563. }else{
  1564. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  1565. currentMenu.insertItem(self.setTTSStype(), at: 2)
  1566. currentMenu.insertItem(self.setCropStype(), at: 2)
  1567. currentMenu.insertItem(self.setSnapshotStype(), at: 2)
  1568. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  1569. currentMenu.insertItem(self.addOutlineStype(), at: 2)
  1570. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  1571. currentMenu.insertItem(self.enterAnnotationStype(), at: 2)
  1572. currentMenu.insertItem(NSMenuItem.separator(), at: 2)
  1573. if(currentMenu.items.count > 4) {
  1574. currentMenu.insertItem(NSMenuItem.separator(), at: 5)
  1575. }
  1576. if(currentMenu.items.count > 5) {
  1577. currentMenu.insertItem(self.addBookmarkMenu(), at: 6)
  1578. }
  1579. // if (currentMenu.items.count > 6 && self.isReadMode) {
  1580. // currentMenu.removeItem(currentMenu.item(withTitle: "Zoom")!)
  1581. // }
  1582. // currentMenu.insertItem(self.findStringMenu(), at: currentMenu.items.count)
  1583. currentMenu.insertItem(self.setAutoScrollStype(), at: currentMenu.items.count)
  1584. }
  1585. currentMenu.insertItem(self.setAnnotationToolStype(), at: 5)
  1586. }
  1587. currentMenu.insertItem(NSMenuItem.separator(), at: 0)
  1588. currentMenu.insertItem(self.setAITranslateStype(), at: 0)
  1589. currentMenu.insertItem(self.setAIProofreadStype(), at: 0)
  1590. currentMenu.insertItem(self.setAIRewriteStype(), at: 0)
  1591. for item in currentMenu.items {
  1592. if (item.action == NSSelectorFromString("menuItemClick_HidenorShowNote:")) {
  1593. // 显示与隐藏注释 item action 截取
  1594. item.action = #selector(menuItemClick_HidenorShowNote)
  1595. item.target = self
  1596. break
  1597. }
  1598. }
  1599. }
  1600. func pdfListViewAddAnnotations(_ pdfListView: CPDFListView!, forAdd annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  1601. var addRedact = false
  1602. for anno in annotations {
  1603. if (anno.isKind(of: CPDFRedactAnnotation.self)) {
  1604. addRedact = true
  1605. } else if anno is CPDFSquareAnnotation || anno is CPDFCircleAnnotation {
  1606. anno.contents = pdfPage?.string(for: anno.bounds) ?? ""
  1607. }
  1608. }
  1609. self.model.hasAddRedact = addRedact
  1610. if /*self.isReadMode || */self.listView.toolMode == .moveToolMode {
  1611. self.listView.toolMode = .textToolMode
  1612. self.listView.annotationType = .unkown
  1613. self.toolbarController.toolbarType = .Annatiton
  1614. }
  1615. if (self.model.rightMouseEventing) {
  1616. self.model.rightMouseEventing = false
  1617. if (self.toolbarController.ignoreCurrentAnnotationTypeChange && self.listView.annotationType == .ink) {
  1618. self.listView.toolMode = .textToolMode
  1619. self.listView.annotationType = .unkown
  1620. }
  1621. }
  1622. self.toolbarController.ignoreCurrentAnnotationTypeChange = false
  1623. self.leftSideViewController.refreshUIForAddAnnotation(annos: annotations, page: pdfPage)
  1624. }
  1625. func pdfListViewRemoveAnnotations(_ pdfListView: CPDFListView!, forRemove annotations: [CPDFAnnotation]!, in pdfPage: CPDFPage!) {
  1626. self.leftSideViewController.annoList_refreshUIForDeleteAnnotations(annos: annotations, page: pdfPage)
  1627. }
  1628. func pdfListViewDidSelectionEnd(_ pdfListView: CPDFListView!) {
  1629. if (!self.listView.isEqual(to: pdfListView)) {
  1630. return
  1631. }
  1632. if (self.listView.toolMode != .selectToolMode) {
  1633. return
  1634. }
  1635. if (self.topTipBox.isHidden || self.topTipBox.contentView?.subviews.count == 0) {
  1636. return
  1637. }
  1638. let tipView = self.topTipBox.contentView?.subviews.first
  1639. if (tipView?.isKind(of: KMCropTipView.self) == false) {
  1640. return
  1641. }
  1642. (tipView as! KMCropTipView).setString(string: "请按 Enter 键确定裁剪区域")
  1643. }
  1644. func pdfListViewKeyDowClosePanel(_ speedy: CPDFViewSidebarSpeedMode, event theEvent: NSEvent!) {
  1645. if(speedy == .right) {
  1646. self.toggleRightPane()
  1647. } else if (speedy == .left) {
  1648. self.menuItemAction_hiddenLeftSide(speedy)
  1649. }
  1650. }
  1651. func pdfListViewEventMarkupColor(with annotation: CPDFAnnotation!) -> [NSColor]! {
  1652. if (annotation.isKind(of: CPDFMarkupAnnotation.self)) {
  1653. if (annotation as! CPDFMarkupAnnotation).markupType() == .highlight {
  1654. return KMAnnotationPropertiesColorManager.manager.markHighlightColors
  1655. } else {
  1656. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  1657. }
  1658. } else {
  1659. return KMAnnotationPropertiesColorManager.manager.markOtherColors
  1660. }
  1661. }
  1662. func pdfListViewHaveDocumentAttribute() -> Bool {
  1663. if(!self.listView.document.allowsCopying) {
  1664. self.removeOwnerPassword()
  1665. return false
  1666. }
  1667. return true
  1668. }
  1669. func pdfListView(_ sender: CPDFListView!, showSnapshotAtPageNumber pageNum: Int, for rect: NSRect, scaleFactor: CGFloat, autoFits: Bool) {
  1670. let swc = KMSnapshotWindowController(windowNibName: "SnapshotWindow")
  1671. swc.delegate = self
  1672. swc.setPdfDocument(self.listView.document, goToPageNumber: pageNum, rect: rect, scaleFactor: scaleFactor, autoFits: autoFits)
  1673. swc.forceOnTop = self.interactionMode != .normal
  1674. self.myDocument?.addWindowController(swc)
  1675. }
  1676. func pdfListView(_ pdfView: CPDFListView!, documentDataDidChanged docData: Any!, withInfo info: [AnyHashable : Any]!) {
  1677. if let data = info?[CPDFListView.outlineKey] as? Bool, data { // 大纲改变
  1678. guard let ol = docData as? CPDFOutline else {
  1679. return
  1680. }
  1681. let add = info?[CPDFListView.outlineAddKey] as? Bool ?? false
  1682. let remove = info?[CPDFListView.outlineRemoveKey] as? Bool ?? false
  1683. if add {
  1684. self.leftSideViewController.addOutlineAfter(ol)
  1685. }
  1686. if remove {
  1687. self.leftSideViewController.removeOutlineAfter(ol)
  1688. }
  1689. let demote = info?[CPDFListView.outlineDemoteKey] as? Bool ?? false
  1690. let promote = info?[CPDFListView.outlinePromoteKey] as? Bool ?? false
  1691. if demote {
  1692. self.leftSideViewController.demoteOutlineAfter(ol)
  1693. }
  1694. if promote {
  1695. self.leftSideViewController.promoteOutlineAfter(ol)
  1696. }
  1697. }
  1698. }
  1699. }