KMEditPDfHanddler.swift 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129
  1. //
  2. // KMEditPDfHanddler.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2024/6/16.
  6. //
  7. import Cocoa
  8. @objc enum KMRightSideLastState: Int {
  9. case none = 0
  10. case open = 1
  11. case close = 2
  12. }
  13. // EditPDF处理对象
  14. class KMEditPDfHanddler: NSObject {
  15. weak var viewC: KMMainViewController?
  16. static let kRightSideLastStateKey = "KMRightSideLastStateKey"
  17. weak var listView: CPDFListView? {
  18. get {
  19. return self.viewC?.listView
  20. }
  21. }
  22. var annotationType: CAnnotationType {
  23. get {
  24. return self.listView?.annotationType ?? .unkown
  25. }
  26. }
  27. weak var rightViewC: KMRightSideViewController? {
  28. get {
  29. return self.viewC?.rightSideViewController
  30. }
  31. }
  32. var subViewType: RightSubViewType {
  33. get {
  34. return self.rightViewC?.subViewType ?? .None
  35. }
  36. }
  37. // var toolMode: CToolMode {
  38. // get {
  39. // return
  40. // }
  41. // }
  42. var isEditImage: Bool {
  43. get {
  44. return self.listView?.isEditImage ?? false
  45. }
  46. }
  47. var isEditing: Bool {
  48. get {
  49. return self.listView?.isEditing() ?? false
  50. }
  51. }
  52. var editingConfig: CPDFEditingConfig? {
  53. get {
  54. return self.listView?.editingConfig()
  55. }
  56. }
  57. var editingAreas: [CPDFEditArea] {
  58. get {
  59. return self.listView?.editingAreas() as? [CPDFEditArea] ?? []
  60. }
  61. }
  62. var rightSideLastState: KMRightSideLastState {
  63. get {
  64. let state = KMDataManager.ud_integer(forKey: Self.kRightSideLastStateKey)
  65. return KMRightSideLastState(rawValue: state) ?? .none
  66. }
  67. set {
  68. KMDataManager.ud_set(newValue.rawValue, forKey: Self.kRightSideLastStateKey)
  69. }
  70. }
  71. private var startPoint_: NSPoint = .zero
  72. func enterEditPDF() {
  73. let toolMode = self.listView?.toolMode ?? .none
  74. if toolMode != .editPDFToolMode { // 退出
  75. self.listView?.updateActiveAnnotations([])
  76. self.listView?.setNeedsDisplayForVisiblePages()
  77. self.listView?.commitEditFormText()
  78. self.closeRightPane()
  79. self.hiddenPopWindow()
  80. self._removeNotification()
  81. return
  82. }
  83. self._addNotification()
  84. if self.rightSideLastState == .open {
  85. self.openRightPane()
  86. } else {
  87. self.closeRightPane()
  88. }
  89. self.listView?.updateActiveAnnotations([])
  90. self.listView?.setNeedsDisplayForVisiblePages()
  91. self.listView?.commitEditFormText()
  92. self.listView?.annotationType = .editTextImage
  93. // 设置边框颜色
  94. self.editingConfig?.editingBorderColor = .clear
  95. // 设置边框宽度
  96. // self.editingConfig?.editingBorderWidth = 10
  97. // 内容与边框的间距
  98. // self.editingConfig?.editAreaMargin = .init(floatLiteral: 5)
  99. // 设置选中块边框颜色
  100. // self.editingConfig?.editingSelectionBorderColor = .red
  101. // 显示hover边框
  102. self.editingConfig?.isShowMouseAreaHover = true
  103. // hover
  104. // 边框宽度
  105. // self.editingConfig?.mouseHoverBorderWidth = 1
  106. // 边框颜色
  107. self.editingConfig?.mouseHoverBorderColor = NSColor(hex: "#999999")
  108. // 边框虚线设置
  109. self.editingConfig?.mouseHoverBorderDashPattern = [3,3,3]
  110. // 块填充颜色(拖拽中)
  111. // self.editingConfig?.editAreaMoveFillColor = .cyan
  112. // 是否显示位置辅助线
  113. self.editingConfig?.isShowEditingAreaHover = true
  114. // 辅助线颜色
  115. // self.editingConfig?.editingHoverBorderColor = .brown
  116. // 支持多选
  117. self.editingConfig?.isSupportMultipleSelectEditingArea = true
  118. // 图片是否显示8个操作点
  119. self.editingConfig?.isDrawRectWithDot = true
  120. }
  121. func openRightPane() {
  122. let state = self.rightSideLastState
  123. if state == .none || state == .open {
  124. self.viewC?.openRightPane()
  125. }
  126. }
  127. func closeRightPane() {
  128. self.rightViewC?.isHidden = true
  129. self.viewC?.closeRightPane()
  130. }
  131. func showPopWindow(positionRect: NSRect) {
  132. let show = KMPreference.shared.editPDFPopWindowIsShow
  133. if !show {
  134. return
  135. }
  136. let win = KMEditPDFPopToolBarWindow.shared
  137. self._kRemoveChildWindow(win)
  138. let areas = self.editingAreas
  139. win.isMultiple = areas.count > 1
  140. var hasText = false
  141. var hasImage = false
  142. var fontColors: [NSColor] = []
  143. for area in areas {
  144. if let data = area as? CPDFEditTextArea {
  145. hasText = true
  146. if let color = self.listView?.editingSelectionFontColor(with: data) {
  147. fontColors.append(color)
  148. }
  149. }
  150. if area is CPDFEditImageArea {
  151. hasImage = true
  152. }
  153. }
  154. var style: KMEditPDFToolbarStyle = []
  155. if hasText {
  156. style.insert(.text)
  157. }
  158. if hasImage {
  159. style.insert(.image)
  160. }
  161. win.style = style
  162. win.model.editingAreas = areas
  163. win.model.fontColors = fontColors
  164. let area = (self.listView?.editingAreas().first as? CPDFEditArea)
  165. let areaBounds = (self.listView?.convert(area!.bounds, from: area!.page) as? NSRect) ?? .zero
  166. self.startPoint_ = self.listView?.documentView().documentVisibleRect.origin ?? .zero
  167. win.show(relativeTo: areaBounds, of: self.viewC!.listView, preferredEdge: .maxY)
  168. win.animator().alphaValue = 1
  169. self._kAddchildwindow(win)
  170. win.itemClick = { [weak self] itemKey, obj in
  171. if itemKey == .color {
  172. self?.fontColorAction(color: obj as? NSColor)
  173. } else if itemKey == .fontStyle {
  174. self?.fontStyleAction(fontName: obj as? String)
  175. } else if itemKey == .fontAdd {
  176. self?.fontAddAction()
  177. } else if itemKey == .fontReduce {
  178. self?.fontReduceAction()
  179. } else if itemKey == .fontBold {
  180. self?.fontBoldAction()
  181. } else if itemKey == .fontItalic {
  182. self?.fontItalicAction()
  183. } else if itemKey == .textAlignment {
  184. self?.textAlignmentAction(align: obj as? NSTextAlignment ?? .left)
  185. }
  186. // 图片
  187. else if itemKey == .leftRotate {
  188. self?.leftRotateAction()
  189. } else if itemKey == .rightRotate {
  190. self?.rightRotateAction()
  191. } else if itemKey == .reverseX {
  192. self?.reverseXAction()
  193. } else if itemKey == .reverseY {
  194. self?.reverseYAction()
  195. } else if itemKey == .crop {
  196. self?.cropAction()
  197. } else if itemKey == .replace {
  198. self?.replaceAction()
  199. } else if itemKey == .export {
  200. self?.exportAction()
  201. }
  202. // 对齐
  203. else if itemKey == .alignmentLeft {
  204. self?.alignmentAction(align: .Left)
  205. } else if itemKey == .alignmentCenterX {
  206. self?.alignmentAction(align: .Horizontally)
  207. } else if itemKey == .alignmentRight {
  208. self?.alignmentAction(align: .Right)
  209. } else if itemKey == .alignmentjustifiedX {
  210. self?.alignmentAction(align: .DisHorizontally)
  211. } else if itemKey == .alignmentTop {
  212. self?.alignmentAction(align: .Top)
  213. } else if itemKey == .alignmentCenterY {
  214. self?.alignmentAction(align: .Vertical)
  215. } else if itemKey == .alignmentBottom {
  216. self?.alignmentAction(align: .Bottom)
  217. } else if itemKey == .alignmentjustifiedY {
  218. self?.alignmentAction(align: .DisVertical)
  219. }
  220. }
  221. // 显示新手引导
  222. if let toolbarView = (win.contentViewController as? KMEditPDFPopToolBarController)?.toolbarView {
  223. self.showGuideView(toolbarView)
  224. }
  225. }
  226. func hiddenPopWindow() {
  227. let win = KMEditPDFPopToolBarWindow.shared
  228. win.orderOut(nil)
  229. win.setIsVisible(false)
  230. self._kRemoveChildWindow(win)
  231. }
  232. func showCropComfirmWindow() {
  233. let win = KMEditPDFPopToolBarWindow.shared
  234. let winFrame = win.frame
  235. let winC = KMEditPDFCropComfirmWindowController.shared
  236. let x = winFrame.origin.x + (NSWidth(winFrame)-84) * 0.5
  237. let frame = NSMakeRect(x, winFrame.origin.y, 84, 44)
  238. winC.window?.setFrame(frame, display: true)
  239. winC.showWindow(nil)
  240. self._kAddchildwindow(winC.window!)
  241. winC.itemAction = { [weak self] idx, _ in
  242. self?.hiddenCropComfirmWindow()
  243. if idx == 0 { // 确认
  244. self?.listView?.cropEditImageArea(self?.listView?.selectImageAreas, withBounds: self?.listView?.cropAreas.cropRect ?? .zero)
  245. self?.listView?.exitCrop(with: self?.listView?.selectImageAreas)
  246. self?.listView?.cropAreas = nil
  247. self?.listView?.isEditImage = false
  248. } else if idx == 1 { // 取消
  249. self?.listView?.exitCrop(with: self?.listView?.selectImageAreas)
  250. self?.listView?.cropAreas = nil
  251. self?.listView?.isEditImage = false
  252. }
  253. Task { @MainActor [weak self] in
  254. if let data = self?.listView?.selectImageAreas {
  255. self?.showPopWindow(positionRect:data.bounds)
  256. }
  257. }
  258. }
  259. }
  260. func hiddenCropComfirmWindow() {
  261. let winC = KMEditPDFCropComfirmWindowController.shared
  262. winC.window?.orderOut(nil)
  263. winC.window?.setIsVisible(false)
  264. self._kRemoveChildWindow(winC.window)
  265. }
  266. func showGuideView(_ view: NSView) {
  267. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  268. if KMGuideInfoWindowController.availableShow(.editPDFPopWindow) {
  269. var winFrame = self.viewC?.view.window?.frame ?? .zero
  270. winFrame.size.height -= 20
  271. let area = (self.listView?.editingAreas().first as? CPDFEditArea)
  272. let areaBounds = (self.listView?.convert(area!.bounds, from: area!.page) as? NSRect) ?? .zero
  273. let guideWC = KMGuideInfoWindowController.currentWC()
  274. guideWC.type = .editPDFPopWindow
  275. var viewFrame = areaBounds
  276. let tmpY = areaBounds.origin.y+(areaBounds.size.height-KMEditPDFPopGuideView.kHeight+80)
  277. if tmpY < 50 {
  278. guideWC.editPDFPopWindowFlag = true
  279. viewFrame.origin.y += (areaBounds.size.height)
  280. viewFrame.origin.x += (areaBounds.size.width*0.5+KMEditPDFPopGuideView.kWidth*0.5)
  281. } else {
  282. guideWC.editPDFPopWindowFlag = false
  283. viewFrame.origin.y += (areaBounds.size.height-KMEditPDFPopGuideView.kHeight+80)
  284. viewFrame.origin.x += (areaBounds.size.width*0.5+KMEditPDFPopGuideView.kWidth*0.5)
  285. }
  286. guideWC.digitalBoxRect = viewFrame
  287. var beh = view.window?.collectionBehavior ?? []
  288. beh.insert(.canJoinAllSpaces)
  289. guideWC.window?.collectionBehavior = beh
  290. guideWC.window?.setFrame(winFrame, display: false)
  291. guideWC.window?.minSize = winFrame.size
  292. guideWC.window?.maxSize = winFrame.size
  293. self._kAddchildwindow(guideWC.window!)
  294. guideWC.show()
  295. DispatchQueue.main.async {
  296. guideWC.interfaceThemeDidChanged(NSApp.appearance?.name ?? .aqua)
  297. }
  298. guideWC.settingCallback = {
  299. KMPreferenceController.shared.showWindow(nil)
  300. }
  301. }
  302. }
  303. }
  304. }
  305. // MARK: - Private Methods
  306. extension KMEditPDfHanddler {
  307. private func _kAddchildwindow(_ childW: NSWindow?) {
  308. guard let win = childW else {
  309. return
  310. }
  311. self.viewC?.view.window?.addChildWindow(win, ordered: .above)
  312. }
  313. private func _kRemoveChildWindow(_ childW: NSWindow?) {
  314. guard let win = childW else {
  315. return
  316. }
  317. let contains = self.viewC?.view.window?.childWindows?.contains(win) ?? false
  318. if contains {
  319. self.viewC?.view.window?.removeChildWindow(win)
  320. }
  321. }
  322. private func _addNotification() {
  323. NotificationCenter.default.addObserver(self, selector: #selector(_scrollViewDidScroll), name: NSScrollView.didLiveScrollNotification, object: self.listView?.documentView())
  324. }
  325. private func _removeNotification() {
  326. NotificationCenter.default.removeObserver(self, name: NSScrollView.didLiveScrollNotification, object: self.listView?.documentView())
  327. }
  328. @objc private func _scrollViewDidScroll(_ noti: Notification) {
  329. if let data = self.listView?.documentView().isEqual(to: noti.object), data {
  330. let win = KMEditPDFPopToolBarWindow.shared
  331. if win.isVisible == false {
  332. return
  333. }
  334. guard let area = (self.listView?.editingAreas().first as? CPDFEditArea) else {
  335. self.hiddenPopWindow()
  336. return
  337. }
  338. let areaBounds = (self.listView?.convert(area.bounds, from: area.page) as? NSRect) ?? .zero
  339. let winFrame = self.listView?.window?.frame ?? .zero
  340. let view: NSView? = nil
  341. var position = self.listView?.convert(areaBounds.origin, to: view) ?? .zero
  342. position.x += winFrame.origin.x
  343. position.y += winFrame.origin.y
  344. position.y += areaBounds.size.height
  345. position.y += 26
  346. let wframe = NSMakeRect(position.x, position.y, win.frame.size.width, 44)
  347. win.setFrame(wframe, display: true)
  348. }
  349. }
  350. }
  351. // MARK: - Action
  352. extension KMEditPDfHanddler {
  353. func fontColorAction(color: NSColor?) {
  354. guard let theColor = color else {
  355. return
  356. }
  357. let editingAreas = self.editingAreas
  358. for area in editingAreas {
  359. if let data = area as? CPDFEditTextArea {
  360. self.listView?.setEditingSelectionFontColor(theColor, with: data)
  361. }
  362. }
  363. }
  364. func fontStyleAction(fontName: String?) {
  365. guard let font = CPDFFont.mappingFont(withFontString: fontName) else {
  366. return
  367. }
  368. let editingAreas = self.editingAreas
  369. for area in editingAreas {
  370. if let data = area as? CPDFEditTextArea {
  371. self.listView?.setEditSelectionCFont(font, with: data)
  372. }
  373. }
  374. }
  375. func fontAddAction() {
  376. let editingAreas = self.editingAreas
  377. if editingAreas.isEmpty {
  378. return
  379. }
  380. guard let area = editingAreas.last else {
  381. return
  382. }
  383. if area.isTextArea() == false {
  384. return
  385. }
  386. if let fontSize = self.listView?.editingSelectionFontSize(with: area as! CPDFEditTextArea) {
  387. self.listView?.setEditingSelectionFontSize(fontSize+1, with: area as! CPDFEditTextArea, isAutoSize: false)
  388. }
  389. }
  390. func fontReduceAction() {
  391. let editingAreas = self.editingAreas
  392. if editingAreas.isEmpty {
  393. return
  394. }
  395. guard let area = editingAreas.last else {
  396. return
  397. }
  398. if area.isTextArea() == false {
  399. return
  400. }
  401. if let fontSize = self.listView?.editingSelectionFontSize(with: area as! CPDFEditTextArea) {
  402. self.listView?.setEditingSelectionFontSize(fontSize-1, with: area as! CPDFEditTextArea, isAutoSize: false)
  403. }
  404. }
  405. func fontBoldAction() {
  406. let editingAreas = self.editingAreas
  407. if editingAreas.isEmpty {
  408. return
  409. }
  410. guard let area = editingAreas.last else {
  411. return
  412. }
  413. if area.isTextArea() == false {
  414. return
  415. }
  416. self.listView?.setCurrentSelectionIsBold(true, with: area as! CPDFEditTextArea)
  417. }
  418. func fontItalicAction() {
  419. let editingAreas = self.editingAreas
  420. if editingAreas.isEmpty {
  421. return
  422. }
  423. guard let area = editingAreas.last else {
  424. return
  425. }
  426. if area.isTextArea() == false {
  427. return
  428. }
  429. self.listView?.setCurrentSelectionIsItalic(true, with: area as! CPDFEditTextArea)
  430. }
  431. func textAlignmentAction(align: NSTextAlignment) {
  432. let editingAreas = self.editingAreas
  433. for area in editingAreas {
  434. if let data = area as? CPDFEditTextArea {
  435. self.listView?.setCurrentSelectionAlignment(align, with: data)
  436. }
  437. }
  438. }
  439. func leftRotateAction() {
  440. let editingAreas = self.editingAreas
  441. if editingAreas.isEmpty {
  442. return
  443. }
  444. guard let area = editingAreas.last as? CPDFEditImageArea else {
  445. return
  446. }
  447. // if let ang = self.listView?.getRotateWith(area) {
  448. // self.listView?.rotate(with: area, rotate: ang-90)
  449. // }
  450. // FMTrackEventManager.defaultManager.trackEvent(event: "SubTbr_PageEdit", withProperties: ["SubTbr_Btn": "Btn_SubTbr_PageEdit_Rotate"])
  451. self.listView?.rotate(with: area, rotate: -90)
  452. // var frame = area.bounds
  453. // frame.size.width += 100
  454. // self.listView?.setBoundsEditArea(area, withBounds: frame)
  455. // 文档拖拽、tooltip、多选场景、暗黑场景
  456. // if self.listView.editingAreas()!.count == 1 && (self.listView.editingAreas()!.first is CPDFEditImageArea) {
  457. // self.listView.selectImageAreas = self.listView.editingAreas()!.first as? CPDFEditImageArea
  458. // }
  459. // self.editImageView.image = self.listView.selectImageAreas.thumbnailImage
  460. // self.delegate?.editImagePropertyViewControllerDidChanged(controller: self, type: .rotate)
  461. }
  462. func rightRotateAction() {
  463. let editingAreas = self.editingAreas
  464. if editingAreas.isEmpty {
  465. return
  466. }
  467. guard let area = editingAreas.last as? CPDFEditImageArea else {
  468. return
  469. }
  470. self.listView?.rotate(with: area, rotate: 90)
  471. }
  472. func reverseXAction() {
  473. let editingAreas = self.editingAreas
  474. if editingAreas.isEmpty {
  475. return
  476. }
  477. for area in editingAreas {
  478. if let data = area as? CPDFEditImageArea {
  479. self.listView?.horizontalMirror(with: data)
  480. }
  481. }
  482. }
  483. func reverseYAction() {
  484. let editingAreas = self.editingAreas
  485. if editingAreas.isEmpty {
  486. return
  487. }
  488. for area in editingAreas {
  489. if let data = area as? CPDFEditImageArea {
  490. self.listView?.verticalMirror(with: data)
  491. }
  492. }
  493. }
  494. func cropAction() {
  495. self.listView?.isEditImage = true
  496. let editingAreas = self.editingAreas
  497. if editingAreas.isEmpty {
  498. return
  499. }
  500. for area in editingAreas {
  501. if let data = area as? CPDFEditImageArea {
  502. self.listView?.enterCrop(with: data)
  503. }
  504. }
  505. self.hiddenPopWindow()
  506. Task { @MainActor in
  507. self.showCropComfirmWindow()
  508. }
  509. }
  510. func replaceAction() {
  511. let editingAreas = self.editingAreas
  512. if editingAreas.isEmpty {
  513. return
  514. }
  515. let panel = NSOpenPanel()
  516. panel.allowsMultipleSelection = false
  517. panel.allowedFileTypes = ["png","jpg"]
  518. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  519. if response == .OK {
  520. let openPath = panel.url?.path
  521. for area in editingAreas {
  522. if let data = area as? CPDFEditImageArea {
  523. // self.listView?.replace(data, imagePath: openPath!)
  524. self.listView?.replace(data, imagePath: openPath!, rect: data.bounds)
  525. }
  526. }
  527. }
  528. }
  529. }
  530. func exportAction() {
  531. let editingAreas = self.editingAreas
  532. if editingAreas.isEmpty {
  533. return
  534. }
  535. var imagesAreas: [CPDFEditImageArea] = []
  536. for area in editingAreas {
  537. if let data = area as? CPDFEditImageArea {
  538. imagesAreas.append(data)
  539. }
  540. }
  541. if imagesAreas.count == 1 {
  542. let panel = NSSavePanel()
  543. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).jpg"
  544. panel.isExtensionHidden = true
  545. let response = panel.runModal()
  546. if response == .OK {
  547. let url = panel.url
  548. if FileManager.default.fileExists(atPath: url!.path) {
  549. try?FileManager.default.removeItem(atPath: url!.path)
  550. }
  551. let result = self.listView?.extractImage(with: imagesAreas.first, toImagePath: url!.path) ?? false
  552. if result {
  553. NSWorkspace.shared.activateFileViewerSelecting([url!])
  554. }
  555. }
  556. } else if imagesAreas.count > 1 {
  557. let panel = NSOpenPanel()
  558. panel.canChooseFiles = false
  559. panel.canChooseDirectories = true
  560. panel.canCreateDirectories = true
  561. panel.allowsMultipleSelection = false
  562. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  563. if response == .OK {
  564. let outputURL = panel.url
  565. let s = self.listView?.document?.documentURL.lastPathComponent
  566. let folderPath = (self.listView?.document?.documentURL.deletingPathExtension().lastPathComponent ?? "") + "_extract"
  567. var filePath = outputURL?.path.stringByAppendingPathComponent(folderPath)
  568. var i = 1
  569. let testFilePath = filePath
  570. while FileManager.default.fileExists(atPath: filePath!) {
  571. filePath = testFilePath! + "\(i)"
  572. i = i + 1
  573. }
  574. try? FileManager.default.createDirectory(atPath: filePath!, withIntermediateDirectories: false, attributes: nil)
  575. var saveURLs : [URL] = []
  576. for j in 0 ... imagesAreas.count-1 {
  577. let documentFileName = self.listView?.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  578. var outPath = filePath!
  579. outPath = outPath.stringByAppendingPathComponent(documentFileName)
  580. outPath = outPath + "page \(j+1)"
  581. outPath = outPath.stringByAppendingPathExtension("jpg")
  582. let result = self.listView?.extractImage(with: imagesAreas[j], toImagePath: outPath) ?? false
  583. if result {
  584. saveURLs.append(URL(fileURLWithPath: outPath))
  585. }
  586. }
  587. NSWorkspace.shared.activateFileViewerSelecting(saveURLs)
  588. }
  589. }
  590. }
  591. }
  592. func alignmentAction(align: CPDFActiveAreasAlignType) {
  593. KMPrint("updateFormAearsAlignMangent")
  594. let stype = align
  595. let editingAreas = self.editingAreas
  596. if editingAreas.count >= 2 {
  597. var zeroRect = NSRect.null
  598. var highestRect = NSZeroRect
  599. var widthestRect = NSZeroRect
  600. let fristArea : CPDFEditArea = editingAreas.first as! CPDFEditArea
  601. var leftestRect = fristArea.bounds
  602. var rightestRect = fristArea.bounds
  603. var topestRect = fristArea.bounds
  604. var bottomestRect = fristArea.bounds
  605. var leftestArea : CPDFEditArea = fristArea
  606. var rightestArea : CPDFEditArea = fristArea
  607. var topestArea : CPDFEditArea = fristArea
  608. var bottomestArea : CPDFEditArea = fristArea
  609. var totalWidth = 0.0
  610. var totalHeight = 0.0
  611. for i in 0 ... editingAreas.count-1 {
  612. let area : CPDFEditArea = editingAreas[i] as! CPDFEditArea
  613. zeroRect = zeroRect.union(area.bounds)
  614. totalWidth = totalWidth + area.bounds.width
  615. totalHeight = totalHeight + area.bounds.height
  616. if area.bounds.height > highestRect.height {
  617. highestRect = area.bounds
  618. }
  619. if area.bounds.width > widthestRect.width {
  620. widthestRect = area.bounds
  621. }
  622. if leftestRect.minX > area.bounds.minX {
  623. leftestRect = area.bounds
  624. leftestArea = area
  625. }
  626. if area.bounds.maxX > rightestRect.maxX {
  627. rightestRect = area.bounds
  628. rightestArea = area
  629. }
  630. if area.bounds.maxY > topestRect.maxY {
  631. topestRect = area.bounds
  632. topestArea = area
  633. }
  634. if bottomestRect.minY > area.bounds.minY {
  635. bottomestRect = area.bounds
  636. bottomestArea = area
  637. }
  638. }
  639. var resultAreasArray: [Any] = []
  640. var newBoundsArray: [String] = []
  641. if stype == .Left {
  642. for i in 0 ... editingAreas.count-1 {
  643. let areas = editingAreas[i] as! CPDFEditArea
  644. var bounds = areas.bounds
  645. bounds.origin.x = zeroRect.origin.x
  646. newBoundsArray.append(NSStringFromRect(bounds))
  647. }
  648. resultAreasArray = editingAreas
  649. } else if stype == .Right {
  650. for i in 0 ... editingAreas.count-1 {
  651. let areas = editingAreas[i] as! CPDFEditArea
  652. var bounds = areas.bounds
  653. bounds.origin.x = zeroRect.maxX - bounds.size.width
  654. newBoundsArray.append(NSStringFromRect(bounds))
  655. }
  656. resultAreasArray = editingAreas
  657. } else if stype == .Top {
  658. for i in 0 ... editingAreas.count-1 {
  659. let areas = editingAreas[i] as! CPDFEditArea
  660. var bounds = areas.bounds
  661. bounds.origin.y = zeroRect.maxY - bounds.size.height
  662. newBoundsArray.append(NSStringFromRect(bounds))
  663. }
  664. resultAreasArray = editingAreas
  665. } else if stype == .Bottom {
  666. for i in 0 ... editingAreas.count-1 {
  667. let areas = editingAreas[i] as! CPDFEditArea
  668. var bounds = areas.bounds
  669. bounds.origin.y = zeroRect.minY
  670. newBoundsArray.append(NSStringFromRect(bounds))
  671. }
  672. resultAreasArray = editingAreas
  673. } else if stype == .Horizontally {
  674. for i in 0 ... editingAreas.count-1 {
  675. let areas = editingAreas[i] as! CPDFEditArea
  676. var bounds = areas.bounds
  677. bounds.origin.y = highestRect.midY - bounds.height/2
  678. newBoundsArray.append(NSStringFromRect(bounds))
  679. }
  680. resultAreasArray = editingAreas
  681. } else if stype == .Vertical {
  682. for i in 0 ... editingAreas.count-1 {
  683. let areas = editingAreas[i] as! CPDFEditArea
  684. var bounds = areas.bounds
  685. bounds.origin.x = widthestRect.midX - bounds.width/2
  686. newBoundsArray.append(NSStringFromRect(bounds))
  687. }
  688. resultAreasArray = editingAreas
  689. } else if stype == .DisHorizontally {
  690. let middleGap = zeroRect.width - leftestRect.width - rightestRect.width
  691. let otherAreasTotalWidth = totalWidth - leftestRect.width - rightestRect.width
  692. let gap = (middleGap - otherAreasTotalWidth)/CGFloat(editingAreas.count - 1)
  693. var areasCopyArray : [CPDFEditArea] = editingAreas as! [CPDFEditArea]
  694. areasCopyArray.sorted(by: { obj1, obj2 in
  695. let area1 = obj1
  696. let area2 = obj2
  697. if area1.bounds.origin.x < area2.bounds.origin.x {
  698. return true
  699. } else {
  700. return false
  701. }
  702. })
  703. if let index = areasCopyArray.firstIndex(of: leftestArea) {
  704. areasCopyArray.remove(at: index)
  705. }
  706. if let index = areasCopyArray.firstIndex(of: rightestArea) {
  707. areasCopyArray.remove(at: index)
  708. }
  709. var leftStartX = leftestRect.maxX + gap
  710. for i in 0 ... areasCopyArray.count-1 {
  711. let areas = areasCopyArray[i]
  712. var bounds = areas.bounds
  713. bounds.origin.x = leftStartX
  714. newBoundsArray.append(NSStringFromRect(bounds))
  715. leftStartX = leftStartX + bounds.width + gap
  716. }
  717. resultAreasArray = areasCopyArray
  718. } else if stype == .DisVertical {
  719. let middleGap = zeroRect.height - topestRect.height - bottomestRect.height
  720. let otherAreasTotalHeight = totalHeight - topestRect.height - bottomestRect.height
  721. let gap = (middleGap - otherAreasTotalHeight)/CGFloat(editingAreas.count - 1)
  722. var areasCopyArray : [CPDFEditArea] = editingAreas as! [CPDFEditArea]
  723. areasCopyArray.sorted(by: { obj1, obj2 in
  724. let area1 = obj1
  725. let area2 = obj2
  726. if area1.bounds.origin.x < area2.bounds.origin.x {
  727. return true
  728. } else {
  729. return false
  730. }
  731. })
  732. if let index = areasCopyArray.firstIndex(of: topestArea) {
  733. areasCopyArray.remove(at: index)
  734. }
  735. if let index = areasCopyArray.firstIndex(of: bottomestArea) {
  736. areasCopyArray.remove(at: index)
  737. }
  738. var bottomStartY = bottomestRect.maxY + gap
  739. for i in 0 ... areasCopyArray.count-1 {
  740. let areas = areasCopyArray[i]
  741. var bounds = areas.bounds
  742. bounds.origin.y = bottomStartY
  743. newBoundsArray.append(NSStringFromRect(bounds))
  744. bottomStartY = bottomStartY + bounds.height + gap
  745. }
  746. resultAreasArray = areasCopyArray
  747. }
  748. var oldBounds : [String] = []
  749. for i in 0 ... resultAreasArray.count-1 {
  750. let area : CPDFEditArea = resultAreasArray[i] as! CPDFEditArea
  751. oldBounds.append(NSStringFromRect(area.bounds))
  752. self.listView?.setBoundsEditArea(area, withBounds: NSRectFromString(newBoundsArray[i]))
  753. }
  754. self.listView?.setNeedsDisplayForVisiblePages()
  755. }
  756. }
  757. }
  758. // MARK: - CPDFViewDelegate
  759. extension KMEditPDfHanddler: CPDFViewDelegate {
  760. // 编辑区块已经改变
  761. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  762. let isEdited = self.listView?.isEdited() ?? false
  763. if isEdited {
  764. // 记录编辑状态
  765. self.viewC?.recordIsPDFDocumentEdited(type: .editText)
  766. }
  767. if annotationType != .addText {
  768. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView?.document)
  769. }
  770. let areas = self.listView?.editingAreas() as? [CPDFEditArea] ?? []
  771. if areas.isEmpty {
  772. self.hiddenPopWindow()
  773. let toolMode = self.listView?.toolMode ?? .none
  774. let annotationType = self.annotationType
  775. if toolMode == .editPDFToolMode {
  776. if annotationType == .addImage || annotationType == .addText {
  777. if self.isEditImage {
  778. self.viewC?.menuItemEditingClick_CropImage(sender: NSMenuItem())
  779. } else {
  780. // if self.listView.annotationType == .addImage {
  781. // self.closeRightPane()
  782. // }
  783. if annotationType == .addImage {
  784. if self.rightViewC?.eidtPDFImageProperty != nil {
  785. self.rightViewC?.eidtPDFImageProperty.reloadData()
  786. }
  787. }
  788. // self.openRightPane()
  789. }
  790. } else {
  791. // self.viewC?.closeRightPane()
  792. self.rightViewC?.isHidden = true
  793. }
  794. } else {
  795. self.rightViewC?.isHidden = true
  796. self.viewC?.closeRightPane()
  797. if self.subViewType == .EditPDFAddText && annotationType == .addText {
  798. self.rightViewC?.eidtPDFTextProperty.initData()
  799. }
  800. }
  801. return
  802. }
  803. self.viewC?.model.isPDFTextImageEdited = true
  804. let subViewType = self.rightViewC?.subViewType ?? .None
  805. if self.annotationType == .addImage {
  806. var isImageArea = false
  807. for i in 0 ..< areas.count {
  808. if areas[i] is CPDFEditImageArea {
  809. isImageArea = true
  810. }
  811. }
  812. if isImageArea {
  813. self.rightViewC?.isHidden = false
  814. if self.subViewType == .EditPDFAddImage {
  815. self.rightViewC?.subViewType = .EditPDFAddImage
  816. self.rightViewC?.eidtPDFImageProperty.reloadData()
  817. }
  818. self.openRightPane()
  819. } else {
  820. self.rightViewC?.isHidden = true
  821. // self.viewC?.closeRightPane()
  822. }
  823. } else if self.subViewType == .EditPDFAddText && annotationType == .addText {
  824. self.rightViewC?.isHidden = false
  825. let count = self.listView?.editingSelectionString()?.count ?? 0
  826. if count != 0 {
  827. self.rightViewC?.eidtPDFTextProperty.reloadData()
  828. } else {
  829. self.rightViewC?.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  830. }
  831. self.openRightPane()
  832. } else {
  833. var textsAreas : [CPDFEditTextArea] = []
  834. var imagesAreas : [CPDFEditImageArea] = []
  835. let count = self.listView?.editingAreas()?.count ?? 0
  836. if count < 1 {
  837. return
  838. }
  839. for i in 0 ..< areas.count {
  840. if areas[i] is CPDFEditTextArea {
  841. textsAreas.append(areas[i] as! CPDFEditTextArea)
  842. }
  843. if areas[i] is CPDFEditImageArea {
  844. imagesAreas.append(areas[i] as! CPDFEditImageArea)
  845. }
  846. }
  847. if textsAreas.count > 0 && textsAreas.count == areas.count {
  848. self.rightViewC?.isHidden = false
  849. self.rightViewC?.subViewType = .EditPDFAddText
  850. self.rightViewC?.eidtPDFTextProperty?.reloadData()
  851. self.openRightPane()
  852. } else if imagesAreas.count > 0 {
  853. self.rightViewC?.isHidden = false
  854. self.rightViewC?.subViewType = .EditPDFAddImage
  855. self.rightViewC?.eidtPDFImageProperty?.reloadData()
  856. self.openRightPane()
  857. }
  858. }
  859. var flag: CPDFEditArea?
  860. for area in areas {
  861. if flag == nil {
  862. flag = area
  863. continue
  864. }
  865. if let data = flag, data.bounds.maxY < area.bounds.maxY {
  866. flag = area
  867. }
  868. }
  869. if let data = flag {
  870. self.showPopWindow(positionRect: data.bounds)
  871. }
  872. }
  873. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  874. if editArea != nil && (editArea is CPDFEditImageArea){
  875. self.listView?.cropAreas = editArea as? CPDFEditImageArea
  876. }
  877. }
  878. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  879. if self.isEditImage {
  880. self.viewC?.menuItemEditingClick_CropImage(sender: NSMenuItem())
  881. } else {
  882. let panel = NSOpenPanel()
  883. panel.allowsMultipleSelection = false
  884. panel.allowedFileTypes = ["png","jpg"]
  885. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  886. if response == .OK {
  887. var filePath = panel.url?.path
  888. var image = NSImage.init(contentsOf: panel.url!)
  889. //图片自适应范围
  890. if image != nil {
  891. var imageRect = rect
  892. let imageSize = image!.size
  893. var previewSize = rect.size
  894. var isChangeSize = false
  895. if previewSize.width == 0 && previewSize.height == 0 {
  896. previewSize = CGSize(width: 500, height: 500)
  897. isChangeSize = true
  898. }
  899. let scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  900. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  901. if isChangeSize {
  902. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  903. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  904. } else {
  905. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  906. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  907. }
  908. imageRect.size = newSize
  909. let limitWidth = 1920.0
  910. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  911. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  912. targetSize: CGSize(width: limitWidth, height: limitWidth),
  913. maxSizeInBytes: 1024 * 1024 * 5,
  914. targetCompression: 1.0)
  915. }
  916. //自适应page
  917. let pageRect = self.listView?.currentPage().bounds ?? .zero
  918. if imageRect.width > pageRect.width ||
  919. imageRect.height > pageRect.height {
  920. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  921. imageRect = CGRect(x: imageRect.origin.x,
  922. y: imageRect.origin.y,
  923. width: imageRect.width * pageScale,
  924. height: imageRect.height * pageScale)
  925. }
  926. if imageRect.origin.x < 0 {
  927. imageRect.origin.x = 5
  928. }
  929. if imageRect.origin.y < 0 {
  930. imageRect.origin.y = 5
  931. }
  932. if imageRect.origin.x + imageRect.width > pageRect.width ||
  933. imageRect.origin.y + imageRect.height > pageRect.height {
  934. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  935. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  936. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  937. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  938. }
  939. DispatchQueue.main.async {
  940. self.listView?.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  941. self.viewC?.model.isPDFTextImageEdited = true
  942. self.viewC?.recordIsPDFDocumentEdited(type: .editImage)
  943. self.showPopWindow(positionRect: imageRect)
  944. }
  945. }
  946. }
  947. }
  948. }
  949. }
  950. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  951. let window = KMEditPDFPopToolBarWindow.shared
  952. if (window.isVisible) {
  953. self.hiddenPopWindow()
  954. let areas = self.listView?.editingAreas() as? [CPDFEditArea] ?? []
  955. if let area = areas.last {
  956. if let data = area as? CPDFEditTextArea {
  957. if let str = data.editTextAreaString(), str.isEmpty {
  958. self.listView?.remove(with: [area])
  959. }
  960. }
  961. }
  962. return
  963. }
  964. var newRect = rect
  965. if CGSizeEqualToSize(rect.size, .zero) {
  966. newRect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  967. } else {
  968. newRect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  969. }
  970. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  971. let fontName = KMEditPDFTextManager.manager.fetchFontName(fontName: model.fontName)
  972. let fontSize = model.fontSize
  973. let fontColor = model.color
  974. let fontAlign = model.alignment
  975. let fontStyle = KMEditPDFTextManager.manager.fetchFontStyle(fontName: model.fontName)
  976. NSColorPanel.shared.color = fontColor
  977. let font = KMEditPDFTextManager.manager.fetchFont(fontName: fontName, style: fontStyle, size: fontSize)
  978. let attri = CEditAttributes()
  979. attri.font = font
  980. attri.fontColor = fontColor
  981. attri.alignment = fontAlign
  982. self.listView?.createStringBounds(newRect, with: attri, page: page)
  983. // self.rightViewC != nil &&
  984. if self.subViewType == .EditPDFAddText && self.annotationType == .addText {
  985. self.rightViewC?.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  986. }
  987. self.showPopWindow(positionRect: newRect)
  988. }
  989. // 文本区块 选中文本已经变化
  990. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  991. // self.viewC?.rightSideViewController != nil &&
  992. if self.subViewType == .EditPDFAddText {
  993. self.rightViewC?.eidtPDFTextProperty.reloadData()
  994. self.rightViewC?.eidtPDFTextProperty.updateTextTextPresuppositionState()
  995. }
  996. }
  997. func pdfViewMobileEditingBegan(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  998. self.hiddenPopWindow()
  999. }
  1000. func pdfViewMobileEditingMove(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  1001. }
  1002. func pdfViewMobileEditingEnd(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  1003. self.showPopWindow(positionRect: .zero)
  1004. }
  1005. }