KMMainViewController+UI.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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 startSpeaking(_ sender: Any) {
  11. self.showTTSWindow()
  12. let ttsView = KMTTSWindowController.share
  13. ttsView.buttonItemClick_Play(ttsView.playButton)
  14. }
  15. @IBAction func stopSpeaking(_ sender: Any) {
  16. let ttsWindowC = KMTTSWindowController.share
  17. if ttsWindowC.pdfView?.document?.documentURL.path == self.listView.document?.documentURL.path {
  18. if let data = ttsWindowC.window?.isVisible, data {
  19. ttsWindowC.stopSpeaking()
  20. ttsWindowC.close()
  21. }
  22. }
  23. }
  24. }
  25. extension KMMainViewController {
  26. //通知
  27. func preferenceDidChangeNotification(notification:Notification) {
  28. let info : [AnyHashable : Any] = notification.userInfo ?? [:]
  29. if info.keys.contains(KMPreference.viewZoomScaleTypeKey) {
  30. self.selectZoom(KMPreferenceManager.shared.viewZoomScaleType)
  31. }
  32. if notification.name.rawValue == "pdfViewDocumentDidLoaded" || info.keys.contains(KMPreference.viewPageDisplayTypeKey) {
  33. }
  34. if info.keys.contains(KMPreference.displayBackgroundNormalColorKey) || notification.name.rawValue == "pdfViewDocumentDidLoaded" {
  35. self.listView.backgroundColor = KMPreferenceManager.shared.displayBackgroundNormalColor
  36. self.listView.layoutDocumentView()
  37. }
  38. if (info.keys.contains(KMPreference.generalAuthorNameKey)) { // 作者名称
  39. CPDFKitConfig.sharedInstance().setAnnotationAuthor((info[KMPreference.generalAuthorNameKey] as! String))
  40. }
  41. if (info.keys.contains(KMPreference.highlightLinksKey)) {
  42. let hlLink = info[KMPreference.highlightLinksKey] as? Bool
  43. CPDFKitConfig.sharedInstance().setEnableLinkFieldHighlight(hlLink == nil ? false : hlLink!)
  44. self.listView.setNeedsDisplayForVisiblePages()
  45. }
  46. if info.keys.contains(KMPreference.thumbPageSizeKey) {
  47. self.leftSideViewController.refreshUIOfThumbnailIfNeed(preference: true)
  48. }
  49. if info.keys.contains(KMPreference.thumbSnapshotSizeKey) {
  50. self.leftSideViewController.refreshUIOfSnapshotIfNeed(preference: true)
  51. }
  52. if info.keys.contains(KMPreference.outlineFontSizeKey) {
  53. self.leftSideViewController.updateTableFont()
  54. }
  55. if info.keys.contains(KMPreference.greekThresholdKey) {
  56. let value = KMPreference.shared.greekThreshold.cgFloat
  57. self.listView.setGreekingThreshold(value)
  58. }
  59. if info.keys.contains(KMPreference.antiAliasTextKey) {
  60. self.listView.setShouldAntiAlias(KMPreference.shared.antiAliasText)
  61. self.listView.applyDefaultInterpolationQuality()
  62. }
  63. if info.keys.contains(KMPreference.markupColorHighlightKey) {
  64. }
  65. if info.keys.contains(KMPreference.markupColorUnderlineKey) {
  66. }
  67. if info.keys.contains(KMPreference.markupColorStrikthroughKey) {
  68. }
  69. if info.keys.contains(KMPreference.markupColorPenKey) {
  70. }
  71. if info.keys.contains(KMPreference.editPDFPopWindowShowKey) {
  72. let show = KMPreference.shared.editPDFPopWindowIsShow
  73. }
  74. }
  75. func showConvertNotesProgress() {
  76. guard let pdfDocument = self.document else {
  77. return
  78. }
  79. guard let _ = self.listView.document else {
  80. return
  81. }
  82. guard let _ = self.view.window else {
  83. return
  84. }
  85. let isNewCreated = (self.myDocument as? KMMainDocument)?.isNewCreated ?? false
  86. if isNewCreated {
  87. return
  88. }
  89. self.model.needConvertNotes = false
  90. Task { @MainActor in
  91. self.convertNotesUsingPDFDocument(pdfDocument)
  92. }
  93. }
  94. func convertNotesUsingPDFDocument(_ pdfDocument: CPDFDocument, callback: (()->Void)? = nil) {
  95. guard let doc = self.listView.document else {
  96. return
  97. }
  98. DispatchQueue.main.async {
  99. self.beginProgressSheet(withMessage: "", maxValue: 0)
  100. let count = pdfDocument.pageCount
  101. DispatchQueue.global().async {
  102. self.model.addAnnotations.removeAll()
  103. self.model.removeAnnotations.removeAll()
  104. for i in 0..<count {
  105. let page = pdfDocument.page(at: i)
  106. for annotation in page?.annotations ?? [] {
  107. var newAnnotation: CPDFAnnotation?
  108. if let inkAnnotation = annotation as? CPDFInkAnnotation, inkAnnotation.contents.hasPrefix("<?xml version=\"1.0\" encoding=\"utf-8\"?>") {
  109. let table = KMTableAnnotation(KMNoteBounds: inkAnnotation.bounds, document: doc)
  110. table.border = inkAnnotation.border
  111. table.color = inkAnnotation.color
  112. table.createForm(withList: inkAnnotation.contents, andPaths: inkAnnotation.bezierPaths())
  113. table.updateAppearanceInk(withIsAdd: false)
  114. table.contents = annotation.contents
  115. newAnnotation = table
  116. }
  117. if let newAnnotation = newAnnotation {
  118. self.model.addAnnotations.append(newAnnotation)
  119. self.model.removeAnnotations.append(annotation)
  120. }
  121. }
  122. }
  123. DispatchQueue.main.async {
  124. for i in 0..<self.model.addAnnotations.count {
  125. let newAnnotation = self.model.addAnnotations[i]
  126. let annotation = self.model.removeAnnotations[i]
  127. let page = annotation.page
  128. // this is only to make sure markup annotations generate the lineRects, for thread safety
  129. self.listView.addAnnotation(with: newAnnotation, to: page)
  130. self.listView.remove(annotation)
  131. if newAnnotation.contents != nil {
  132. if newAnnotation.contents.count == 0 {
  133. newAnnotation.autoUpdateString()
  134. }
  135. }
  136. }
  137. self.dismissProgressSheet()
  138. self.listView.undoManager?.removeAllActions()
  139. self.undoManager?.removeAllActions()
  140. // 清空数据
  141. self.model.addAnnotations.removeAll()
  142. self.model.removeAnnotations.removeAll()
  143. callback?()
  144. }
  145. }
  146. }
  147. }
  148. // MARK: - KMInterfaceThemeChangedProtocol
  149. override func interfaceThemeDidChanged(_ appearance: NSAppearance.Name) {
  150. super.interfaceThemeDidChanged(appearance)
  151. self.leftSideViewController.interfaceThemeDidChanged(appearance)
  152. self.pdfEditController?.interfaceThemeDidChanged(appearance)
  153. }
  154. }
  155. // MARK: - KMToolbarControllerDelegate
  156. extension KMMainViewController: KMToolbarControllerDelegate {
  157. func toolbarController(_ viewController: KMToolbarController, heightOffsetChange heightOffset: Float, animated: Bool) {
  158. }
  159. func changeAnnotationModeAction(item: KMToolbarClickButton) {
  160. if self.listView.toolMode == .formToolMode {
  161. if !IAPProductsManager.default().isAvailableAllFunction(){
  162. let winC = KMPurchaseCompareWindowController.sharedInstance()
  163. if let type = CAnnotationType(rawValue: item.tag) {
  164. if type == .textField {
  165. winC?.kEventName = "Reading_TextField_BuyNow"
  166. } else if type == .checkBox {
  167. winC?.kEventName = "Reading_CheckBox_BuyNow"
  168. } else if type == .radioButton {
  169. winC?.kEventName = "Reading_RadioButton_BuyNow"
  170. } else if type == .listMenu {
  171. winC?.kEventName = "Reading_ListBox_BuyNow"
  172. } else if type == .comboBox {
  173. winC?.kEventName = "Reading_ComboBox_BuyNow"
  174. } else if type == .actionButton {
  175. winC?.kEventName = "Reading_Button_BuyNow"
  176. }
  177. }
  178. winC?.showWindow(nil)
  179. return
  180. }
  181. } else {
  182. let type = CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown
  183. if type == .signature {
  184. if !IAPProductsManager.default().isAvailableAllFunction(){
  185. let winC = KMPurchaseCompareWindowController.sharedInstance()
  186. winC?.kEventName = "Reading_ElectronicSign_BuyNow"
  187. winC?.showWindow(nil)
  188. return
  189. }
  190. }
  191. }
  192. if (self.model.rightMouseEventing) {
  193. self.model.rightMouseEventing = false
  194. }
  195. var currentType = self.listView.annotationType
  196. let isSelected = (currentType == CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown) && ((self.listView.toolMode == .noteToolMode) || (self.listView.toolMode == .selfSignMode) || (self.listView.toolMode == .formToolMode))
  197. var editSelectd = false
  198. if self.listView.annotationType == CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown && self.listView.toolMode == .editPDFToolMode {
  199. editSelectd = true
  200. }
  201. if isSelected {
  202. if self.listView.toolMode == .formToolMode {
  203. } else {
  204. self.listView.toolMode = .textToolMode
  205. }
  206. let type = CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown
  207. if type == .signature {
  208. if self.listView.toolMode == .formToolMode {
  209. self.listView.toolMode = .noteToolMode
  210. }
  211. }
  212. self.listView.annotationType = .unkown
  213. toggleCloseRightSide()
  214. } else {
  215. let type = CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown
  216. self.trackEvent(annotationType: type)
  217. if type == .signature {
  218. if self.listView.toolMode != .formToolMode {
  219. self.listView.toolMode = .formToolMode
  220. }
  221. }
  222. self.listView.annotationType = type
  223. if self.listView.currentSelection != nil {
  224. 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)
  225. if((annotation != nil) &&
  226. !self.listView.activeAnnotations.contains(annotation ?? self.listView.activeAnnotation)) {
  227. var newAnnonations : [CPDFAnnotation] = []
  228. newAnnonations.append(annotation!)
  229. self.listView.updateActiveAnnotations(newAnnonations)
  230. self.listView.setNeedsDisplayAnnotationViewFor(annotation?.page)
  231. }
  232. }
  233. if self.listView.toolMode == .formToolMode {
  234. } else {
  235. self.refreshListViewToolMode()
  236. }
  237. }
  238. if self.listView.toolMode != .editPDFToolMode && self.listView.annotationType != .unkown {
  239. let toolMode = self.listView.toolMode ?? .none
  240. if !viewManager.isPDFReadMode {
  241. toggleOpenRightSide()
  242. }
  243. } else if self.listView.toolMode == .editPDFToolMode {
  244. if editSelectd {
  245. self.listView.setShouAddEdit([])
  246. self.listView.change([.text, .image])
  247. toggleCloseRightSide()
  248. } else if self.listView.shouAddEditAreaType() == .text {
  249. if !viewManager.isPDFReadMode {
  250. toggleOpenRightSide()
  251. }
  252. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_EditPDF", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_EditPDF_AddText"])
  253. self.listView.setShouAddEdit(.text)
  254. self.listView.change(.text)
  255. } else if self.listView.shouAddEditAreaType() == .image {
  256. if !viewManager.isPDFReadMode {
  257. toggleOpenRightSide()
  258. }
  259. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_EditPDF", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_EditPDF_AddImage"])
  260. self.listView.setShouAddEdit(.image)
  261. self.listView.change(.image)
  262. }
  263. } else {
  264. toggleCloseRightSide()
  265. }
  266. }
  267. func refreshListViewToolMode () {
  268. }
  269. func showPDFLayoutModeAction(show: Bool) {
  270. self.listView.annotationType = .unkown
  271. self.showOrHideNotes()
  272. }
  273. }
  274. // MARK: - KMLeftSideViewControllerDelegate
  275. extension KMMainViewController: KMLeftSideViewControllerDelegate {
  276. func controlStateChange(_ obj: KMLeftSideViewController, show: Bool) {
  277. if show {
  278. self.openLeftPane()
  279. } else {
  280. self.closeLeftPane()
  281. }
  282. }
  283. func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int]) {
  284. }
  285. func searchAction(searchString: String,isCase:Bool) {
  286. self.search(searchString: searchString,isCase: isCase)
  287. }
  288. func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?) {
  289. if (itemKey == .print) { // 打印
  290. if params is NSImage {
  291. KMPrintWindowController.cpdf_printImage(image: params as! NSImage)
  292. return
  293. }
  294. var pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [], reversePrintOrder: false)
  295. if (params != nil) {
  296. pageRange.type = .custom
  297. pageRange.selectPages = params as! [Int]
  298. }
  299. self.showPrintWindow(pageRange: pageRange)
  300. } else if (itemKey == .cut || itemKey == .paste || itemKey == .delete || itemKey == .leftRotate || itemKey == .rightRotate) {
  301. self.recordIsPDFDocumentEdited(type: itemKey.toSubscribeWaterMarkType())
  302. } else if itemKey == .pageEdit {
  303. } else if itemKey == .demote { // 大纲降级
  304. guard let currentOutline: CPDFOutline = controller.tocOutlineView.km.clickedItem() else {
  305. return
  306. }
  307. self.listView.demote(outline: currentOutline)
  308. } else if itemKey == .promote { // 大纲升级
  309. guard let currentOutline: CPDFOutline = controller.tocOutlineView.km.clickedItem() else {
  310. return
  311. }
  312. self.listView.promote(outline: currentOutline)
  313. } else if itemKey == .tts {
  314. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  315. self.listView.annotationType = .unkown
  316. self.showTTSWindow()
  317. }
  318. }
  319. func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookmarkItem]) {
  320. self.needSave = true
  321. self.recordIsPDFDocumentEdited()
  322. }
  323. func controller(controller: KMLeftSideViewController, rotateType: KMRotateType) {
  324. if rotateType == .clockwise {
  325. self.menuItemAction_rotateRight((Any).self)
  326. } else if rotateType == .anticlockwise {
  327. self.menuItemAction_rotateLeft((Any).self)
  328. }
  329. }
  330. func controller(controller: KMLeftSideViewController, listViewSelectionDidChange object: Any?, info: [String : Any]?) {
  331. if controller.thumbnailTableView.isEqual(to: object) {
  332. let row = controller.thumbnailTableView.selectedRow
  333. let curIndex = self.listView.currentPageIndex
  334. if (row != -1 && row != curIndex) {
  335. self.listView.go(toPageIndex: row, animated: true)
  336. }
  337. }
  338. }
  339. }
  340. //MARK: - ReadModel
  341. extension KMMainViewController {
  342. @objc func addOutLineItemAction() {
  343. let labelString = "\(KMLocalizedString("Page")) \((self.listView.currentPageIndex ?? 0) + 1)"
  344. let label = self.listView.currentSelection?.string() ?? labelString
  345. let dest = self.listView.currentDestination
  346. if let row = self.leftSideViewController.selectedRowIndexes().last {
  347. if let ol = self.leftSideViewController.tocOutlineView.item(atRow: row) as? CPDFOutline {
  348. _ = self.listView.addOutline(for: ol.parent, label: label, dest: dest, at: ol.index+1)
  349. } else {
  350. let idx = self.listView.document?.outlineRoot()?.numberOfChildren ?? 0
  351. _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
  352. }
  353. } else {
  354. let idx = self.listView.document?.outlineRoot()?.numberOfChildren ?? 0
  355. _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
  356. }
  357. }
  358. @objc func showTTSView() {
  359. FMTrackEventManager.defaultManager.trackEvent(event: "RightClickBar", withProperties: ["RightClickBar_Btn": "Btn_RightClickBar_TTS"])
  360. self.showTTSWindow()
  361. }
  362. @objc func showShareAction() {
  363. }
  364. @objc func lookUpAction() {
  365. let label = self.listView.currentSelection?.string() ?? ""
  366. }
  367. @objc func searchBaiduAction() {
  368. let label = self.listView.currentSelection?.string() ?? ""
  369. let query = label.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
  370. if let url = URL(string: "https://www.baidu.com/s?wd=\(query)") {
  371. NSWorkspace.shared.open(url)
  372. }
  373. }
  374. @objc func showInfoInFinder() {
  375. }
  376. @objc func NextPageAction() {
  377. }
  378. @objc func PreviousPageAction() {
  379. }
  380. @objc func TranslateItemAction() {
  381. // 获取选中的文本
  382. if let selection = self.listView.currentSelection?.string() {
  383. // 进行翻译
  384. let escapedText = selection.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
  385. let urlStr = "https://translate.google.com/?sl=auto&amp;tl=zh-CN&amp;text=\(escapedText)"
  386. if let url = URL(string: urlStr) {
  387. NSWorkspace.shared.open(url)
  388. }
  389. } else {
  390. print("No text selected.")
  391. }
  392. }
  393. @objc func AutoScrollItemAction() {
  394. //增加判断,如果是正在滚动,就停止,否则就开始滚动
  395. self.listView.autoFlow()
  396. }
  397. @objc func cutAction(sender: NSMenuItem) {
  398. }
  399. @objc func deleteAction(sender: NSMenuItem) {
  400. }
  401. @objc func ColorsItemAction(sender: NSMenuItem) {
  402. }
  403. @objc func LinesItemAction(sender: NSMenuItem) {
  404. }
  405. @objc func EditNoteItemAction(sender: NSMenuItem) {
  406. }
  407. @objc func AITranslateItemAction(sender: NSMenuItem) {
  408. self.showAITypeChooseView(aiConfigType: .translate)
  409. }
  410. @objc func AIProofreadItemAction(sender: NSMenuItem) {
  411. self.showAITypeChooseView(aiConfigType: .proofreading)
  412. }
  413. @objc func AIRewriteItemAction(sender: NSMenuItem) {
  414. self.showAITypeChooseView(aiConfigType: .reWriting)
  415. }
  416. }
  417. // MARK: - KMSnapshotWindowControllerDelegate
  418. extension KMMainViewController: KMSnapshotWindowControllerDelegate {
  419. func snapshotControllerWillClose(_ controller: KMSnapshotWindowController) {
  420. self.leftSideViewController.snapshotControllerWillClose(controller)
  421. }
  422. func snapshotController(_ controller: KMSnapshotWindowController, miniaturizedRect isMiniaturize: Bool) -> NSRect {
  423. if isMiniaturize && self.interactionMode != .presentation {
  424. if self.interactionMode != .legacyFullScreen && self.model.leftPanelOpen == false {
  425. self.toggleLeftPane()
  426. } else if self.interactionMode == .legacyFullScreen {
  427. }
  428. var row = NSNotFound
  429. for (i,sp) in self.leftSideViewController.snapshots.enumerated() {
  430. if controller.isEqual(sp.windowC) {
  431. row = i
  432. }
  433. }
  434. if (row != NSNotFound) {
  435. if self.leftSideViewController.type.methodType != .snapshot {
  436. self.leftSideViewController.leftView.segmentedControl.selectedSegment = 5
  437. } else {
  438. self.leftSideViewController.refreshUIOfSnapshotIfNeed()
  439. }
  440. self.leftSideViewController.snapshotTableView.scrollRowToVisible(row)
  441. }
  442. }
  443. return self.leftSideViewController.snapshotController(controller, miniaturizedRect: isMiniaturize)
  444. }
  445. func snapshotControllerDidFinishSetup(_ controller: KMSnapshotWindowController) {
  446. self.leftSideViewController.snapshotControllerDidFinishSetup(controller)
  447. }
  448. }
  449. // MARK: - CPDFDocumentDelegate
  450. extension KMMainViewController: CPDFDocumentDelegate {
  451. func documentDidBeginDocumentFind(_ document: CPDFDocument!) {
  452. self.leftSideViewController.documentDidBeginFind()
  453. }
  454. func documentDidEndDocumentFind(_ document: CPDFDocument!) {
  455. self.leftSideViewController.documentDidEndFind()
  456. }
  457. }
  458. // MAKR: - CPDFViewDelegate,CPDFListViewDelegate