KMMainViewController+UI.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. self.listView.annotationType = .editTextImage
  253. toggleCloseRightSide()
  254. } else if self.listView.annotationType == .addText {
  255. if !viewManager.isPDFReadMode {
  256. toggleOpenRightSide()
  257. }
  258. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_EditPDF", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_EditPDF_AddText"])
  259. self.listView.setShouAddEdit(.text)
  260. self.listView.change(.text)
  261. } else if self.listView.annotationType == .addImage {
  262. if !viewManager.isPDFReadMode {
  263. toggleOpenRightSide()
  264. }
  265. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_EditPDF", withProperties: ["SubTbr_Btn" : "Btn_SubTbr_EditPDF_AddImage"])
  266. self.listView.setShouAddEdit(.image)
  267. self.listView.change(.image)
  268. }
  269. } else {
  270. toggleCloseRightSide()
  271. }
  272. }
  273. func refreshListViewToolMode () {
  274. }
  275. func showPDFLayoutModeAction(show: Bool) {
  276. self.listView.annotationType = .unkown
  277. self.showOrHideNotes()
  278. }
  279. }
  280. // MARK: - KMLeftSideViewControllerDelegate
  281. extension KMMainViewController: KMLeftSideViewControllerDelegate {
  282. func controlStateChange(_ obj: KMLeftSideViewController, show: Bool) {
  283. if show {
  284. self.openLeftPane()
  285. } else {
  286. self.closeLeftPane()
  287. }
  288. }
  289. func enterEditMode(_ obj: KMLeftSideViewController, _ pages: [Int]) {
  290. }
  291. func searchAction(searchString: String,isCase:Bool) {
  292. self.search(searchString: searchString,isCase: isCase)
  293. }
  294. func controller(controller: KMLeftSideViewController, itemClick item: Any?, itemKey: KMItemKey, params: Any?) {
  295. if (itemKey == .print) { // 打印
  296. if params is NSImage {
  297. KMPrintWindowController.cpdf_printImage(image: params as! NSImage)
  298. return
  299. }
  300. var pageRange: KMPrintPageRange = KMPrintPageRange(type: .allPage, selectPages: [], reversePrintOrder: false)
  301. if (params != nil) {
  302. pageRange.type = .custom
  303. pageRange.selectPages = params as! [Int]
  304. }
  305. self.showPrintWindow(pageRange: pageRange)
  306. } else if (itemKey == .cut || itemKey == .paste || itemKey == .delete || itemKey == .leftRotate || itemKey == .rightRotate) {
  307. self.recordIsPDFDocumentEdited(type: itemKey.toSubscribeWaterMarkType())
  308. } else if itemKey == .pageEdit {
  309. } else if itemKey == .demote { // 大纲降级
  310. guard let currentOutline: CPDFOutline = controller.tocOutlineView.km.clickedItem() else {
  311. return
  312. }
  313. self.listView.demote(outline: currentOutline)
  314. } else if itemKey == .promote { // 大纲升级
  315. guard let currentOutline: CPDFOutline = controller.tocOutlineView.km.clickedItem() else {
  316. return
  317. }
  318. self.listView.promote(outline: currentOutline)
  319. } else if itemKey == .tts {
  320. FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageDisplay", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageDisplay_TTS"])
  321. self.listView.annotationType = .unkown
  322. self.showTTSWindow()
  323. }
  324. }
  325. func controller(controller: KMLeftSideViewController, bookMarkDidChange bookMarks: [KMBookMarkItem]) {
  326. self.needSave = true
  327. self.recordIsPDFDocumentEdited()
  328. }
  329. func controller(controller: KMLeftSideViewController, rotateType: KMRotateType) {
  330. if rotateType == .clockwise {
  331. self.menuItemAction_rotateRight((Any).self)
  332. } else if rotateType == .anticlockwise {
  333. self.menuItemAction_rotateLeft((Any).self)
  334. }
  335. }
  336. func controller(controller: KMLeftSideViewController, listViewSelectionDidChange object: Any?, info: [String : Any]?) {
  337. if controller.thumbnailTableView.isEqual(to: object) {
  338. let row = controller.thumbnailTableView.selectedRow
  339. let curIndex = self.listView.currentPageIndex
  340. if (row != -1 && row != curIndex) {
  341. self.listView.go(toPageIndex: row, animated: true)
  342. }
  343. }
  344. }
  345. }
  346. //MARK: - ReadModel
  347. extension KMMainViewController {
  348. @objc func addOutLineItemAction() {
  349. let labelString = "\(KMLocalizedString("Page")) \((self.listView.currentPageIndex ?? 0) + 1)"
  350. let label = self.listView.currentSelection?.string() ?? labelString
  351. let dest = self.listView.currentDestination
  352. if let row = self.leftSideViewController.selectedRowIndexes().last {
  353. if let ol = self.leftSideViewController.tocOutlineView.item(atRow: row) as? CPDFOutline {
  354. _ = self.listView.addOutline(for: ol.parent, label: label, dest: dest, at: ol.index+1)
  355. } else {
  356. let idx = self.listView.document?.outlineRoot()?.numberOfChildren ?? 0
  357. _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
  358. }
  359. } else {
  360. let idx = self.listView.document?.outlineRoot()?.numberOfChildren ?? 0
  361. _ = self.listView.addOutlineForRoot(label: label, dest:dest, at: idx)
  362. }
  363. }
  364. @objc func showTTSView() {
  365. FMTrackEventManager.defaultManager.trackEvent(event: "RightClickBar", withProperties: ["RightClickBar_Btn": "Btn_RightClickBar_TTS"])
  366. self.showTTSWindow()
  367. }
  368. @objc func showShareAction() {
  369. }
  370. @objc func lookUpAction() {
  371. let label = self.listView.currentSelection?.string() ?? ""
  372. }
  373. @objc func searchBaiduAction() {
  374. let label = self.listView.currentSelection?.string() ?? ""
  375. let query = label.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""
  376. if let url = URL(string: "https://www.baidu.com/s?wd=\(query)") {
  377. NSWorkspace.shared.open(url)
  378. }
  379. }
  380. @objc func showInfoInFinder() {
  381. }
  382. @objc func NextPageAction() {
  383. }
  384. @objc func PreviousPageAction() {
  385. }
  386. @objc func TranslateItemAction() {
  387. // 获取选中的文本
  388. if let selection = self.listView.currentSelection?.string() {
  389. // 进行翻译
  390. let escapedText = selection.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!
  391. let urlStr = "https://translate.google.com/?sl=auto&amp;tl=zh-CN&amp;text=\(escapedText)"
  392. if let url = URL(string: urlStr) {
  393. NSWorkspace.shared.open(url)
  394. }
  395. } else {
  396. print("No text selected.")
  397. }
  398. }
  399. @objc func AutoScrollItemAction() {
  400. //增加判断,如果是正在滚动,就停止,否则就开始滚动
  401. self.listView.autoFlow()
  402. }
  403. @objc func cutAction(sender: NSMenuItem) {
  404. }
  405. @objc func deleteAction(sender: NSMenuItem) {
  406. }
  407. @objc func ColorsItemAction(sender: NSMenuItem) {
  408. }
  409. @objc func LinesItemAction(sender: NSMenuItem) {
  410. }
  411. @objc func EditNoteItemAction(sender: NSMenuItem) {
  412. }
  413. @objc func AITranslateItemAction(sender: NSMenuItem) {
  414. self.showAITypeChooseView(aiConfigType: .translate)
  415. }
  416. @objc func AIProofreadItemAction(sender: NSMenuItem) {
  417. self.showAITypeChooseView(aiConfigType: .proofreading)
  418. }
  419. @objc func AIRewriteItemAction(sender: NSMenuItem) {
  420. self.showAITypeChooseView(aiConfigType: .reWriting)
  421. }
  422. }
  423. // MARK: - KMSnapshotWindowControllerDelegate
  424. extension KMMainViewController: KMSnapshotWindowControllerDelegate {
  425. func snapshotControllerWillClose(_ controller: KMSnapshotWindowController) {
  426. self.leftSideViewController.snapshotControllerWillClose(controller)
  427. }
  428. func snapshotController(_ controller: KMSnapshotWindowController, miniaturizedRect isMiniaturize: Bool) -> NSRect {
  429. if isMiniaturize && self.interactionMode != .presentation {
  430. if self.interactionMode != .legacyFullScreen && self.model.leftPanelOpen == false {
  431. self.toggleLeftPane()
  432. } else if self.interactionMode == .legacyFullScreen {
  433. }
  434. var row = NSNotFound
  435. for (i,sp) in self.leftSideViewController.snapshots.enumerated() {
  436. if controller.isEqual(sp.windowC) {
  437. row = i
  438. }
  439. }
  440. if (row != NSNotFound) {
  441. if self.leftSideViewController.type.methodType != .snapshot {
  442. self.leftSideViewController.leftView.segmentedControl.selectedSegment = 5
  443. } else {
  444. self.leftSideViewController.refreshUIOfSnapshotIfNeed()
  445. }
  446. self.leftSideViewController.snapshotTableView.scrollRowToVisible(row)
  447. }
  448. }
  449. return self.leftSideViewController.snapshotController(controller, miniaturizedRect: isMiniaturize)
  450. }
  451. func snapshotControllerDidFinishSetup(_ controller: KMSnapshotWindowController) {
  452. self.leftSideViewController.snapshotControllerDidFinishSetup(controller)
  453. }
  454. }
  455. // MARK: - CPDFDocumentDelegate
  456. extension KMMainViewController: CPDFDocumentDelegate {
  457. func documentDidBeginDocumentFind(_ document: CPDFDocument!) {
  458. self.leftSideViewController.documentDidBeginFind()
  459. }
  460. func documentDidEndDocumentFind(_ document: CPDFDocument!) {
  461. self.leftSideViewController.documentDidEndFind()
  462. }
  463. }
  464. // MAKR: - CPDFViewDelegate,CPDFListViewDelegate