KMMainViewController+UI.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. extension KMMainViewController {
  156. func changeAnnotationModeAction(item: KMToolbarClickButton) {
  157. if self.listView.toolMode == .formToolMode {
  158. if !IAPProductsManager.default().isAvailableAllFunction(){
  159. let winC = KMPurchaseCompareWindowController.sharedInstance()
  160. if let type = CAnnotationType(rawValue: item.tag) {
  161. if type == .textField {
  162. winC?.kEventName = "Reading_TextField_BuyNow"
  163. } else if type == .checkBox {
  164. winC?.kEventName = "Reading_CheckBox_BuyNow"
  165. } else if type == .radioButton {
  166. winC?.kEventName = "Reading_RadioButton_BuyNow"
  167. } else if type == .listMenu {
  168. winC?.kEventName = "Reading_ListBox_BuyNow"
  169. } else if type == .comboBox {
  170. winC?.kEventName = "Reading_ComboBox_BuyNow"
  171. } else if type == .actionButton {
  172. winC?.kEventName = "Reading_Button_BuyNow"
  173. }
  174. }
  175. winC?.showWindow(nil)
  176. return
  177. }
  178. } else {
  179. let type = CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown
  180. if type == .signature {
  181. if !IAPProductsManager.default().isAvailableAllFunction(){
  182. let winC = KMPurchaseCompareWindowController.sharedInstance()
  183. winC?.kEventName = "Reading_ElectronicSign_BuyNow"
  184. winC?.showWindow(nil)
  185. return
  186. }
  187. }
  188. }
  189. if (self.model.rightMouseEventing) {
  190. self.model.rightMouseEventing = false
  191. }
  192. var currentType = self.listView.annotationType
  193. let isSelected = (currentType == CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown) && ((self.listView.toolMode == .noteToolMode) || (self.listView.toolMode == .selfSignMode) || (self.listView.toolMode == .formToolMode))
  194. var editSelectd = false
  195. if self.listView.annotationType == CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown && self.listView.toolMode == .editPDFToolMode {
  196. editSelectd = true
  197. }
  198. if isSelected {
  199. if self.listView.toolMode == .formToolMode {
  200. } else {
  201. self.listView.toolMode = .textToolMode
  202. }
  203. let type = CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown
  204. if type == .signature {
  205. if self.listView.toolMode == .formToolMode {
  206. self.listView.toolMode = .noteToolMode
  207. }
  208. }
  209. self.listView.annotationType = .unkown
  210. toggleCloseRightSide()
  211. } else {
  212. let type = CAnnotationType(rawValue: item.tag) ?? CAnnotationType.unkown
  213. self.trackEvent(annotationType: type)
  214. if type == .signature {
  215. if self.listView.toolMode != .formToolMode {
  216. self.listView.toolMode = .formToolMode
  217. }
  218. }
  219. self.listView.annotationType = type
  220. if self.listView.currentSelection != nil {
  221. 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)
  222. if((annotation != nil) &&
  223. !self.listView.activeAnnotations.contains(annotation ?? self.listView.activeAnnotation)) {
  224. var newAnnonations : [CPDFAnnotation] = []
  225. newAnnonations.append(annotation!)
  226. self.listView.updateActiveAnnotations(newAnnonations)
  227. self.listView.setNeedsDisplayAnnotationViewFor(annotation?.page)
  228. }
  229. }
  230. if self.listView.toolMode == .formToolMode {
  231. } else {
  232. self.refreshListViewToolMode()
  233. }
  234. }
  235. if self.listView.toolMode != .editPDFToolMode && self.listView.annotationType != .unkown {
  236. let toolMode = self.listView.toolMode ?? .none
  237. if !viewManager.isPDFReadMode {
  238. toggleOpenRightSide()
  239. }
  240. } else if self.listView.toolMode == .editPDFToolMode {
  241. if editSelectd {
  242. self.listView.setShouAddEdit([])
  243. self.listView.change([.text, .image])
  244. toggleCloseRightSide()
  245. } else if self.listView.shouAddEditAreaType() == .text {
  246. if !viewManager.isPDFReadMode {
  247. toggleOpenRightSide()
  248. }
  249. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_EditPDF", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_EditPDF_AddText"])
  250. self.listView.setShouAddEdit(.text)
  251. self.listView.change(.text)
  252. } else if self.listView.shouAddEditAreaType() == .image {
  253. if !viewManager.isPDFReadMode {
  254. toggleOpenRightSide()
  255. }
  256. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_EditPDF", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_EditPDF_AddImage"])
  257. self.listView.setShouAddEdit(.image)
  258. self.listView.change(.image)
  259. }
  260. } else {
  261. toggleCloseRightSide()
  262. }
  263. }
  264. func refreshListViewToolMode () {
  265. }
  266. func showPDFLayoutModeAction(show: Bool) {
  267. self.listView.annotationType = .unkown
  268. self.showOrHideNotes()
  269. }
  270. }
  271. // MARK: - KMLeftSideViewControllerDelegate
  272. extension KMMainViewController: KMLeftSideViewControllerDelegate {
  273. func controlStateChange(_ obj: KMLeftSideViewController, show: Bool) {
  274. if show {
  275. self.openLeftPane()
  276. } else {
  277. self.closeLeftPane()
  278. }
  279. }
  280. func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int]) {
  281. }
  282. func searchAction(searchString: String,isCase:Bool) {
  283. self.search(searchString: searchString,isCase: isCase)
  284. }
  285. func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?) {
  286. if (itemKey == .print) { // 打印
  287. if params is NSImage {
  288. KMPrintWindowController.cpdf_printImage(image: params as! NSImage)
  289. return
  290. }
  291. var pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [], reversePrintOrder: false)
  292. if (params != nil) {
  293. pageRange.type = .custom
  294. pageRange.selectPages = params as! [Int]
  295. }
  296. self.showPrintWindow(pageRange: pageRange)
  297. } else if (itemKey == .cut || itemKey == .paste || itemKey == .delete || itemKey == .leftRotate || itemKey == .rightRotate) {
  298. self.recordIsPDFDocumentEdited(type: itemKey.toSubscribeWaterMarkType())
  299. } else if itemKey == .pageEdit {
  300. } else if itemKey == .demote { // 大纲降级
  301. guard let currentOutline: CPDFOutline = controller.tocOutlineView.km.clickedItem() else {
  302. return
  303. }
  304. self.listView.demote(outline: currentOutline)
  305. } else if itemKey == .promote { // 大纲升级
  306. guard let currentOutline: CPDFOutline = controller.tocOutlineView.km.clickedItem() else {
  307. return
  308. }
  309. self.listView.promote(outline: currentOutline)
  310. } else if itemKey == .tts {
  311. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  312. self.listView.annotationType = .unkown
  313. self.showTTSWindow()
  314. }
  315. }
  316. func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookmarkItem]) {
  317. self.needSave = true
  318. self.recordIsPDFDocumentEdited()
  319. }
  320. func controller(controller: KMLeftSideViewController, rotateType: KMRotateType) {
  321. if rotateType == .clockwise {
  322. self.menuItemAction_rotateRight((Any).self)
  323. } else if rotateType == .anticlockwise {
  324. self.menuItemAction_rotateLeft((Any).self)
  325. }
  326. }
  327. func controller(controller: KMLeftSideViewController, listViewSelectionDidChange object: Any?, info: [String : Any]?) {
  328. if controller.thumbnailTableView.isEqual(to: object) {
  329. let row = controller.thumbnailTableView.selectedRow
  330. let curIndex = self.listView.currentPageIndex
  331. if (row != -1 && row != curIndex) {
  332. self.listView.go(toPageIndex: row, animated: true)
  333. }
  334. }
  335. }
  336. }
  337. //MARK: - ReadModel
  338. extension KMMainViewController {
  339. @objc func addOutLineItemAction() {
  340. let labelString = "\(KMLocalizedString("Page")) \((self.listView.currentPageIndex ?? 0) + 1)"
  341. let label = self.listView.currentSelection?.string() ?? labelString
  342. let dest = self.listView.currentDestination
  343. if let row = self.leftSideViewController.selectedRowIndexes().last {
  344. if let ol = self.leftSideViewController.tocOutlineView.item(atRow: row) as? CPDFOutline {
  345. _ = self.listView.addOutline(for: ol.parent, label: label, dest: dest, at: ol.index+1)
  346. } else {
  347. let idx = self.listView.document?.outlineRoot()?.numberOfChildren ?? 0
  348. _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
  349. }
  350. } else {
  351. let idx = self.listView.document?.outlineRoot()?.numberOfChildren ?? 0
  352. _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
  353. }
  354. }
  355. @objc func showTTSView() {
  356. FMTrackEventManager.defaultManager.trackEvent(event: "RightClickBar", withProperties: ["RightClickBar_Btn": "Btn_RightClickBar_TTS"])
  357. self.showTTSWindow()
  358. }
  359. @objc func showShareAction() {
  360. }
  361. @objc func lookUpAction() {
  362. let label = self.listView.currentSelection?.string() ?? ""
  363. }
  364. @objc func searchBaiduAction() {
  365. let label = self.listView.currentSelection?.string() ?? ""
  366. let query = label.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
  367. if let url = URL(string: "https://www.baidu.com/s?wd=\(query)") {
  368. NSWorkspace.shared.open(url)
  369. }
  370. }
  371. @objc func showInfoInFinder() {
  372. }
  373. @objc func NextPageAction() {
  374. }
  375. @objc func PreviousPageAction() {
  376. }
  377. @objc func TranslateItemAction() {
  378. // 获取选中的文本
  379. if let selection = self.listView.currentSelection?.string() {
  380. // 进行翻译
  381. let escapedText = selection.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
  382. let urlStr = "https://translate.google.com/?sl=auto&amp;tl=zh-CN&amp;text=\(escapedText)"
  383. if let url = URL(string: urlStr) {
  384. NSWorkspace.shared.open(url)
  385. }
  386. } else {
  387. print("No text selected.")
  388. }
  389. }
  390. @objc func AutoScrollItemAction() {
  391. //增加判断,如果是正在滚动,就停止,否则就开始滚动
  392. self.listView.autoFlow()
  393. }
  394. @objc func cutAction(sender: NSMenuItem) {
  395. }
  396. @objc func deleteAction(sender: NSMenuItem) {
  397. }
  398. @objc func ColorsItemAction(sender: NSMenuItem) {
  399. }
  400. @objc func LinesItemAction(sender: NSMenuItem) {
  401. }
  402. @objc func EditNoteItemAction(sender: NSMenuItem) {
  403. }
  404. @objc func AITranslateItemAction(sender: NSMenuItem) {
  405. self.showAITypeChooseView(aiConfigType: .translate)
  406. }
  407. @objc func AIProofreadItemAction(sender: NSMenuItem) {
  408. self.showAITypeChooseView(aiConfigType: .proofreading)
  409. }
  410. @objc func AIRewriteItemAction(sender: NSMenuItem) {
  411. self.showAITypeChooseView(aiConfigType: .reWriting)
  412. }
  413. }
  414. // MARK: - KMSnapshotWindowControllerDelegate
  415. extension KMMainViewController: KMSnapshotWindowControllerDelegate {
  416. func snapshotControllerWillClose(_ controller: KMSnapshotWindowController) {
  417. self.leftSideViewController.snapshotControllerWillClose(controller)
  418. }
  419. func snapshotController(_ controller: KMSnapshotWindowController, miniaturizedRect isMiniaturize: Bool) -> NSRect {
  420. if isMiniaturize && self.interactionMode != .presentation {
  421. if self.interactionMode != .legacyFullScreen && self.model.leftPanelOpen == false {
  422. self.toggleLeftPane()
  423. } else if self.interactionMode == .legacyFullScreen {
  424. }
  425. var row = NSNotFound
  426. for (i,sp) in self.leftSideViewController.snapshots.enumerated() {
  427. if controller.isEqual(sp.windowC) {
  428. row = i
  429. }
  430. }
  431. if (row != NSNotFound) {
  432. if self.leftSideViewController.type.methodType != .snapshot {
  433. self.leftSideViewController.leftView.segmentedControl.selectedSegment = 5
  434. } else {
  435. self.leftSideViewController.refreshUIOfSnapshotIfNeed()
  436. }
  437. self.leftSideViewController.snapshotTableView.scrollRowToVisible(row)
  438. }
  439. }
  440. return self.leftSideViewController.snapshotController(controller, miniaturizedRect: isMiniaturize)
  441. }
  442. func snapshotControllerDidFinishSetup(_ controller: KMSnapshotWindowController) {
  443. self.leftSideViewController.snapshotControllerDidFinishSetup(controller)
  444. }
  445. }
  446. // MARK: - CPDFDocumentDelegate
  447. extension KMMainViewController: CPDFDocumentDelegate {
  448. func documentDidBeginDocumentFind(_ document: CPDFDocument!) {
  449. self.leftSideViewController.documentDidBeginFind()
  450. }
  451. func documentDidEndDocumentFind(_ document: CPDFDocument!) {
  452. self.leftSideViewController.documentDidEndFind()
  453. }
  454. }
  455. // MAKR: - CPDFViewDelegate,CPDFListViewDelegate