KMMainViewController+UI.swift 91 KB

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