KMMainViewController+UI.swift 22 KB

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