KMMainViewController+UI.swift 100 KB

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