KMMainViewController+UI.swift 97 KB

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