KMEditPDfHanddler.swift 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675
  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 editingImageAreas: [CPDFEditImageArea] {
  63. get {
  64. var areas: [CPDFEditImageArea] = []
  65. for area in self.editingAreas {
  66. if let data = area as? CPDFEditImageArea {
  67. areas.append(data)
  68. }
  69. }
  70. return areas
  71. }
  72. }
  73. var editingTextAreas: [CPDFEditTextArea] {
  74. get {
  75. var areas: [CPDFEditTextArea] = []
  76. for area in self.editingAreas {
  77. if let data = area as? CPDFEditTextArea {
  78. areas.append(data)
  79. }
  80. }
  81. return areas
  82. }
  83. }
  84. var rightSideLastState: KMRightSideLastState {
  85. get {
  86. let state = KMDataManager.ud_integer(forKey: Self.kRightSideLastStateKey)
  87. return KMRightSideLastState(rawValue: state) ?? .none
  88. }
  89. set {
  90. KMDataManager.ud_set(newValue.rawValue, forKey: Self.kRightSideLastStateKey)
  91. }
  92. }
  93. private var startPoint_: NSPoint = .zero
  94. func enterEditPDF() {
  95. let toolMode = self.listView?.toolMode ?? .none
  96. if toolMode != .editPDFToolMode { // 退出
  97. self.listView?.updateActiveAnnotations([])
  98. self.listView?.setNeedsDisplayForVisiblePages()
  99. self.listView?.commitEditFormText()
  100. self.closeRightPane()
  101. self.clearData()
  102. return
  103. }
  104. self._addNotification()
  105. if self.rightSideLastState == .open {
  106. self.openRightPane()
  107. } else {
  108. self.closeRightPane()
  109. }
  110. self.listView?.updateActiveAnnotations([])
  111. self.listView?.setNeedsDisplayForVisiblePages()
  112. self.listView?.commitEditFormText()
  113. self.listView?.annotationType = .editTextImage
  114. // 设置边框颜色
  115. self.editingConfig?.editingBorderColor = .clear
  116. // 设置边框宽度
  117. // self.editingConfig?.editingBorderWidth = 10
  118. // 内容与边框的间距
  119. // self.editingConfig?.editAreaMargin = .init(floatLiteral: 5)
  120. // 设置选中块边框颜色
  121. // self.editingConfig?.editingSelectionBorderColor = .red
  122. // 显示hover边框
  123. self.editingConfig?.isShowMouseAreaHover = true
  124. // hover
  125. // 边框宽度
  126. // self.editingConfig?.mouseHoverBorderWidth = 1
  127. // 边框颜色
  128. self.editingConfig?.mouseHoverBorderColor = NSColor(hex: "#999999")
  129. // 边框虚线设置
  130. self.editingConfig?.mouseHoverBorderDashPattern = [3,3,3]
  131. // 块填充颜色(拖拽中)
  132. // self.editingConfig?.editAreaMoveFillColor = .cyan
  133. // 是否显示位置辅助线
  134. self.editingConfig?.isShowEditingAreaHover = true
  135. // 辅助线颜色
  136. // self.editingConfig?.editingHoverBorderColor = .brown
  137. // 支持多选
  138. self.editingConfig?.isSupportMultipleSelectEditingArea = true
  139. // 图片是否显示8个操作点
  140. self.editingConfig?.isDrawRectWithDot = true
  141. // self.editingConfig?.editingMouseSelectionBorderColor
  142. self.editingConfig?.editingMouseSelectionBorderWidth = 1
  143. }
  144. func commitEditing() {
  145. let isEdited = self.listView?.isEdited() ?? false
  146. let isPDFTextImageEdited = self.viewC?.model.isPDFTextImageEdited ?? false
  147. if isEdited || isPDFTextImageEdited {
  148. self.listView?.commitEditing()
  149. }
  150. self.clearData()
  151. }
  152. func openRightPane() {
  153. let state = self.rightSideLastState
  154. if state == .none || state == .open {
  155. self.viewC?.openRightPane()
  156. }
  157. }
  158. func closeRightPane() {
  159. self.rightViewC?.isHidden = true
  160. self.viewC?.closeRightPane()
  161. }
  162. func showPopWindow(positionRect: NSRect) {
  163. if self.editAreasIsEmpty() {
  164. return
  165. }
  166. let show = KMPreference.shared.editPDFPopWindowIsShow
  167. if !show {
  168. return
  169. }
  170. let win = KMEditPDFPopToolBarWindow.shared
  171. self._kRemoveChildWindow(win)
  172. let areas = self.editingAreas
  173. win.isMultiple = areas.count > 1
  174. var hasText = false
  175. var hasImage = false
  176. var fontColors: [NSColor] = []
  177. for area in areas {
  178. if let data = area as? CPDFEditTextArea {
  179. hasText = true
  180. if let color = self.listView?.editingSelectionFontColor(with: data) {
  181. fontColors.append(color)
  182. }
  183. }
  184. if area is CPDFEditImageArea {
  185. hasImage = true
  186. }
  187. }
  188. var style: KMEditPDFToolbarStyle = []
  189. if hasText {
  190. style.insert(.text)
  191. }
  192. if hasImage {
  193. style.insert(.image)
  194. }
  195. win.style = style
  196. win.model.editingAreas = areas
  197. win.model.fontColors = fontColors
  198. win.model.fontNames = self._editAreasFontNames()
  199. win.model.fontSizes = self._editAreasFontSizes()
  200. win.model.fontBolds = self._editAreasFontBolds()
  201. win.model.fontItalics = self._editAreasFontItalics()
  202. win.model.textAlignments = self._editAreasTextAlignments()
  203. win.model.rotates = self._editAreasRotates()
  204. win.model.opacitys = self._editAreasOpacitys()
  205. let area = (self.listView?.editingAreas().first as? CPDFEditArea)
  206. var areaBounds = (self.listView?.convert(area!.bounds, from: area!.page) as? NSRect) ?? .zero
  207. var maxX = NSMaxX(areaBounds)
  208. var maxY = NSMaxY(areaBounds)
  209. for area in self.editingAreas {
  210. // let bounds = area.bounds
  211. var bounds = (self.listView?.convert(area.bounds, from: area.page) as? NSRect) ?? .zero
  212. areaBounds.origin.x = min(areaBounds.origin.x, bounds.origin.x)
  213. areaBounds.origin.y = min(areaBounds.origin.y, bounds.origin.y)
  214. maxX = max(maxX, NSMaxX(bounds))
  215. areaBounds.size.width = maxX-areaBounds.origin.x
  216. maxY = max(maxY, NSMaxY(bounds))
  217. areaBounds.size.height = maxY-areaBounds.origin.y
  218. }
  219. self.startPoint_ = self.listView?.documentView().documentVisibleRect.origin ?? .zero
  220. win.show(relativeTo: areaBounds, of: self.viewC!.listView, preferredEdge: .maxY)
  221. win.animator().alphaValue = 1
  222. self._kAddchildwindow(win)
  223. win.itemClick = { [weak self] itemKey, obj in
  224. if itemKey == .color {
  225. self?.fontColorAction(color: obj as? NSColor)
  226. } else if itemKey == .fontStyle {
  227. self?.fontStyleAction(fontName: obj as? String)
  228. } else if itemKey == .fontAdd {
  229. self?.fontAddAction()
  230. } else if itemKey == .fontReduce {
  231. self?.fontReduceAction()
  232. } else if itemKey == .fontBold {
  233. self?.fontBoldAction()
  234. } else if itemKey == .fontItalic {
  235. self?.fontItalicAction()
  236. } else if itemKey == .textAlignment {
  237. self?.textAlignmentAction(align: obj as? NSTextAlignment ?? .left)
  238. }
  239. // 图片
  240. else if itemKey == .leftRotate {
  241. self?.leftRotateAction()
  242. } else if itemKey == .rightRotate {
  243. self?.rightRotateAction()
  244. } else if itemKey == .reverseX {
  245. self?.reverseXAction()
  246. } else if itemKey == .reverseY {
  247. self?.reverseYAction()
  248. } else if itemKey == .crop {
  249. self?.cropAction()
  250. } else if itemKey == .replace {
  251. self?.replaceAction()
  252. } else if itemKey == .export {
  253. if let data = obj as? NSView {
  254. self?.showExportMenu(data)
  255. }
  256. }
  257. // 对齐
  258. else if itemKey == .alignmentLeft {
  259. self?.alignmentAction(align: .Left)
  260. } else if itemKey == .alignmentCenterX {
  261. self?.alignmentAction(align: .Horizontally)
  262. } else if itemKey == .alignmentRight {
  263. self?.alignmentAction(align: .Right)
  264. } else if itemKey == .alignmentjustifiedX {
  265. self?.alignmentAction(align: .DisHorizontally)
  266. } else if itemKey == .alignmentTop {
  267. self?.alignmentAction(align: .Top)
  268. } else if itemKey == .alignmentCenterY {
  269. self?.alignmentAction(align: .Vertical)
  270. } else if itemKey == .alignmentBottom {
  271. self?.alignmentAction(align: .Bottom)
  272. } else if itemKey == .alignmentjustifiedY {
  273. self?.alignmentAction(align: .DisVertical)
  274. }
  275. }
  276. // 显示新手引导
  277. if let toolbarView = (win.contentViewController as? KMEditPDFPopToolBarController)?.toolbarView {
  278. self.showGuideView(toolbarView)
  279. }
  280. }
  281. func hiddenPopWindow() {
  282. let win = KMEditPDFPopToolBarWindow.shared
  283. win.orderOut(nil)
  284. win.setIsVisible(false)
  285. self._kRemoveChildWindow(win)
  286. }
  287. func showCropComfirmWindow() {
  288. let winC = KMEditPDFCropComfirmWindowController.shared
  289. if KMEditPDFPopToolBarWindow.shared.isVisible {
  290. let winFrame = KMEditPDFPopToolBarWindow.shared.frame
  291. let x = winFrame.origin.x + (NSWidth(winFrame)-84) * 0.5
  292. let frame = NSMakeRect(x, winFrame.origin.y, 84, 44)
  293. winC.window?.setFrame(frame, display: true)
  294. } else {
  295. let area = (self.listView?.editingAreas().first as? CPDFEditArea)
  296. let areaBounds = (self.listView?.convert(area!.bounds, from: area!.page) as? NSRect) ?? .zero
  297. let positioningView = self.listView
  298. let winFrame = positioningView?.window?.frame ?? .zero
  299. let toView: NSView? = nil
  300. var position = positioningView?.convert(areaBounds.origin, to: toView) ?? .zero
  301. position.x += winFrame.origin.x
  302. position.y += winFrame.origin.y
  303. position.y += areaBounds.size.height
  304. position.y += 26
  305. let x = position.x + (NSWidth(areaBounds)-84) * 0.5
  306. let frame = NSMakeRect(x, position.y, 84, 44)
  307. winC.window?.setFrame(frame, display: true)
  308. }
  309. winC.showWindow(nil)
  310. self._kAddchildwindow(winC.window!)
  311. winC.itemAction = { [weak self] idx, _ in
  312. if idx == 0 { // 确认
  313. self?.cropComfirmAction()
  314. } else if idx == 1 { // 取消
  315. self?.cropCancelAction()
  316. }
  317. }
  318. }
  319. func hiddenCropComfirmWindow() {
  320. let winC = KMEditPDFCropComfirmWindowController.shared
  321. winC.window?.orderOut(nil)
  322. winC.window?.setIsVisible(false)
  323. self._kRemoveChildWindow(winC.window)
  324. }
  325. func showGuideView(_ view: NSView) {
  326. DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  327. if KMGuideInfoWindowController.availableShow(.editPDFPopWindow) {
  328. var winFrame = self.viewC?.view.window?.frame ?? .zero
  329. winFrame.size.height -= 20
  330. let area = (self.listView?.editingAreas().first as? CPDFEditArea)
  331. let areaBounds = (self.listView?.convert(area!.bounds, from: area!.page) as? NSRect) ?? .zero
  332. let guideWC = KMGuideInfoWindowController.currentWC()
  333. guideWC.type = .editPDFPopWindow
  334. var viewFrame = areaBounds
  335. let tmpY = areaBounds.origin.y+(areaBounds.size.height-KMEditPDFPopGuideView.kHeight+80)
  336. if tmpY < 50 {
  337. guideWC.editPDFPopWindowFlag = true
  338. viewFrame.origin.y += (areaBounds.size.height)
  339. viewFrame.origin.x += (areaBounds.size.width*0.5+KMEditPDFPopGuideView.kWidth*0.5)
  340. viewFrame.origin.y += 20
  341. } else {
  342. guideWC.editPDFPopWindowFlag = false
  343. viewFrame.origin.y += (areaBounds.size.height-KMEditPDFPopGuideView.kHeight+80)
  344. viewFrame.origin.x += (areaBounds.size.width*0.5+KMEditPDFPopGuideView.kWidth*0.5)
  345. let offsetY = NSMaxY(winFrame)-NSMaxY(viewFrame)-60
  346. if offsetY <= 0 {
  347. viewFrame.origin.y += offsetY
  348. }
  349. }
  350. guideWC.digitalBoxRect = viewFrame
  351. var beh = view.window?.collectionBehavior ?? []
  352. beh.insert(.canJoinAllSpaces)
  353. guideWC.window?.collectionBehavior = beh
  354. guideWC.window?.setFrame(winFrame, display: false)
  355. guideWC.window?.minSize = winFrame.size
  356. guideWC.window?.maxSize = winFrame.size
  357. self._kAddchildwindow(guideWC.window!)
  358. guideWC.show()
  359. DispatchQueue.main.async {
  360. guideWC.interfaceThemeDidChanged(NSApp.appearance?.name ?? .aqua)
  361. }
  362. guideWC.settingCallback = {
  363. KMPreferenceController.shared.showWindow(nil)
  364. }
  365. }
  366. }
  367. }
  368. func clearData() {
  369. self.hiddenWindows()
  370. self._removeNotification()
  371. }
  372. func hiddenWindows() {
  373. self.hiddenPopWindow()
  374. self.hiddenCropComfirmWindow()
  375. KMColorPanelCloseIfNeed()
  376. }
  377. }
  378. // MARK: - Private Methods
  379. extension KMEditPDfHanddler {
  380. private func _kAddchildwindow(_ childW: NSWindow?) {
  381. guard let win = childW else {
  382. return
  383. }
  384. self.viewC?.view.window?.addChildWindow(win, ordered: .above)
  385. }
  386. private func _kRemoveChildWindow(_ childW: NSWindow?) {
  387. guard let win = childW else {
  388. return
  389. }
  390. let contains = self.viewC?.view.window?.childWindows?.contains(win) ?? false
  391. if contains {
  392. self.viewC?.view.window?.removeChildWindow(win)
  393. }
  394. }
  395. private func _addNotification() {
  396. NotificationCenter.default.addObserver(self, selector: #selector(_scrollViewDidScroll), name: NSScrollView.didLiveScrollNotification, object: self.listView?.documentView())
  397. }
  398. private func _removeNotification() {
  399. NotificationCenter.default.removeObserver(self, name: NSScrollView.didLiveScrollNotification, object: self.listView?.documentView())
  400. }
  401. @objc private func _scrollViewDidScroll(_ noti: Notification) {
  402. if let data = self.listView?.documentView().isEqual(to: noti.object), data {
  403. let win = KMEditPDFPopToolBarWindow.shared
  404. if win.isVisible == false {
  405. // return
  406. }
  407. guard let area = (self.listView?.editingAreas()?.first as? CPDFEditArea) else {
  408. self.hiddenPopWindow()
  409. self.hiddenCropComfirmWindow()
  410. return
  411. }
  412. let isEditImage = self.listView?.isEditImage ?? false
  413. if isEditImage {
  414. let winC = KMEditPDFCropComfirmWindowController.shared
  415. let winW: CGFloat = 84
  416. let areaBounds = (self.listView?.convert(area.bounds, from: area.page) as? NSRect) ?? .zero
  417. let winFrame = self.listView?.window?.frame ?? .zero
  418. let view: NSView? = nil
  419. var position = self.listView?.convert(areaBounds.origin, to: view) ?? .zero
  420. position.x += winFrame.origin.x
  421. position.y += winFrame.origin.y
  422. position.y += areaBounds.size.height
  423. position.y += 26
  424. var x = position.x + (NSWidth(areaBounds)-84) * 0.5
  425. // let frame = NSMakeRect(x, position.y, 84, 44)
  426. // position.x += (areaBounds.size.width*0.5-win.frame.size.width*0.5)
  427. x = max(0, x)
  428. var y = max(0, position.y)
  429. let screenFrame = NSScreen.main?.frame ?? .zero
  430. if y + 44 + 40 >= screenFrame.size.height {
  431. y = screenFrame.size.height - 44 - 40
  432. }
  433. let wframe = NSMakeRect(x, y, winW, 44)
  434. winC.window?.setFrame(wframe, display: true)
  435. if CGRectContainsRect(winFrame, wframe) == false {
  436. self.hiddenCropComfirmWindow()
  437. } else {
  438. self.showCropComfirmWindow()
  439. }
  440. return
  441. }
  442. let areaBounds = (self.listView?.convert(area.bounds, from: area.page) as? NSRect) ?? .zero
  443. let winFrame = self.listView?.window?.frame ?? .zero
  444. let view: NSView? = nil
  445. var position = self.listView?.convert(areaBounds.origin, to: view) ?? .zero
  446. position.x += winFrame.origin.x
  447. position.y += winFrame.origin.y
  448. position.y += areaBounds.size.height
  449. position.y += 26
  450. position.x += (areaBounds.size.width*0.5-win.frame.size.width*0.5)
  451. // var x = max(0, position.x)
  452. var x = max(winFrame.origin.x, position.x)
  453. let width = win.frame.size.width
  454. let offsetX = x + width - NSMaxX(winFrame)
  455. if offsetX > 0 { // 超出右编辑
  456. x -= offsetX
  457. }
  458. var y = max(0, position.y)
  459. let screenFrame = NSScreen.main?.frame ?? .zero
  460. if y + 44 + 40 >= screenFrame.size.height {
  461. y = screenFrame.size.height - 44 - 40
  462. }
  463. let wframe = NSMakeRect(x, y, width, 44)
  464. win.setFrame(wframe, display: true)
  465. if CGRectContainsRect(winFrame, wframe) == false {
  466. self.hiddenPopWindow()
  467. }
  468. }
  469. }
  470. private func _reloadData_right_text() {
  471. self.rightViewC?.eidtPDFTextProperty.reloadData()
  472. }
  473. private func _reloadData_right_image() {
  474. self.rightViewC?.eidtPDFImageProperty.reloadData()
  475. }
  476. }
  477. // MARK: - Tools
  478. extension KMEditPDfHanddler {
  479. func editAreasIsEmpty() -> Bool {
  480. return self.editingAreas.isEmpty
  481. }
  482. func editAreasHavTextArea() -> Bool {
  483. return self.editingTextAreas.isEmpty == false
  484. }
  485. func editAreasHavImageArea() -> Bool {
  486. return self.editingImageAreas.isEmpty == false
  487. }
  488. func editAreasFontColorIsEqual() -> Bool {
  489. if self.editAreasIsEmpty() {
  490. return false
  491. }
  492. let datas = self._editAreasFontColors()
  493. if datas.count == 1 {
  494. return true
  495. }
  496. let color = datas.first
  497. for (i, d) in datas.enumerated() {
  498. if i == 0 {
  499. continue
  500. }
  501. if d != color {
  502. return false
  503. }
  504. }
  505. return true
  506. }
  507. func editAreasFontNameIsEqual() -> Bool {
  508. if self.editAreasIsEmpty() {
  509. return false
  510. }
  511. let datas = self._editAreasFontNames()
  512. if datas.count == 1 {
  513. return true
  514. }
  515. let data = datas.first
  516. for (i, d) in datas.enumerated() {
  517. if i == 0 {
  518. continue
  519. }
  520. if d != data {
  521. return false
  522. }
  523. }
  524. return true
  525. }
  526. func editAreasFontStyleIsEqual() -> Bool {
  527. if self.editAreasIsEmpty() {
  528. return false
  529. }
  530. let datas = self._editAreasFontStyles()
  531. if datas.count == 1 {
  532. return true
  533. }
  534. let data = datas.first
  535. for (i, d) in datas.enumerated() {
  536. if i == 0 {
  537. continue
  538. }
  539. if d != data {
  540. return false
  541. }
  542. }
  543. return true
  544. }
  545. func editAreasFontSizeIsEqual() -> Bool {
  546. if self.editAreasIsEmpty() {
  547. return false
  548. }
  549. let datas = self._editAreasFontSizes()
  550. if datas.count == 1 {
  551. return true
  552. }
  553. let data = datas.first
  554. for (i, d) in datas.enumerated() {
  555. if i == 0 {
  556. continue
  557. }
  558. if d != data {
  559. return false
  560. }
  561. }
  562. return true
  563. }
  564. func editAreasFontBoldIsEqual() -> Bool {
  565. if self.editAreasIsEmpty() {
  566. return false
  567. }
  568. let datas = self._editAreasFontBolds()
  569. if datas.count == 1 {
  570. return true
  571. }
  572. let data = datas.first
  573. for (i, d) in datas.enumerated() {
  574. if i == 0 {
  575. continue
  576. }
  577. if d != data {
  578. return false
  579. }
  580. }
  581. return true
  582. }
  583. func editAreasFontItalicIsEqual() -> Bool {
  584. if self.editAreasIsEmpty() {
  585. return false
  586. }
  587. let datas = self._editAreasFontItalics()
  588. if datas.count == 1 {
  589. return true
  590. }
  591. let data = datas.first
  592. for (i, d) in datas.enumerated() {
  593. if i == 0 {
  594. continue
  595. }
  596. if d != data {
  597. return false
  598. }
  599. }
  600. return true
  601. }
  602. func editAreasTextAlignmentIsEqual() -> Bool {
  603. if self.editAreasIsEmpty() {
  604. return false
  605. }
  606. let datas = self._editAreasTextAlignments()
  607. if datas.count == 1 {
  608. return true
  609. }
  610. let data = datas.first?.rawValue ?? 0
  611. for (i, d) in datas.enumerated() {
  612. if i == 0 {
  613. continue
  614. }
  615. if d.rawValue != data {
  616. return false
  617. }
  618. }
  619. return true
  620. }
  621. func editAreasBoundsIsEqualForWidth() -> Bool {
  622. if self.editAreasIsEmpty() {
  623. return false
  624. }
  625. let rects = self._editAreasBounds()
  626. if rects.count == 1 {
  627. return true
  628. }
  629. let width = rects.first?.width ?? 0
  630. for (i, rect) in rects.enumerated() {
  631. if i == 0 {
  632. continue
  633. }
  634. if width != rect.size.width {
  635. return false
  636. }
  637. }
  638. return true
  639. }
  640. func editAreasBoundsIsEqualForHeight() -> Bool {
  641. if self.editAreasIsEmpty() {
  642. return false
  643. }
  644. let rects = self._editAreasBounds()
  645. if rects.count == 1 {
  646. return true
  647. }
  648. let height = rects.first?.height ?? 0
  649. for (i, rect) in rects.enumerated() {
  650. if i == 0 {
  651. continue
  652. }
  653. if height != rect.size.height {
  654. return false
  655. }
  656. }
  657. return true
  658. }
  659. func editAreasRotateIsEqual() -> Bool {
  660. if self.editAreasIsEmpty() {
  661. return false
  662. }
  663. if self.editAreasHavTextArea() {
  664. return false
  665. }
  666. let datas = self._editAreasRotates()
  667. if datas.count == 1 {
  668. return true
  669. }
  670. let data = datas.first ?? 0
  671. for (i, d) in datas.enumerated() {
  672. if i == 0 {
  673. continue
  674. }
  675. if data != d {
  676. return false
  677. }
  678. }
  679. return true
  680. }
  681. func editAreasOpacityIsEqual() -> Bool {
  682. if self.editAreasIsEmpty() {
  683. return false
  684. }
  685. let datas = self._editAreasOpacitys()
  686. if datas.count == 1 {
  687. return true
  688. }
  689. let data = datas.first ?? 0
  690. for (i, d) in datas.enumerated() {
  691. if i == 0 {
  692. continue
  693. }
  694. if data != d {
  695. return false
  696. }
  697. }
  698. return true
  699. }
  700. private func _editAreasFontColors() -> [NSColor] {
  701. var datas: [NSColor] = []
  702. for area in self.editingTextAreas {
  703. if let data = self.listView?.editingSelectionFontColor(byRangeEdit: area) {
  704. datas.append(data)
  705. }
  706. }
  707. return datas
  708. }
  709. private func _editAreasFontStyles() -> [String] {
  710. var datas: [String] = []
  711. for area in self.editingTextAreas {
  712. if let data = self.listView?.editingSelectionCFont(byRangeEdit: area)?.styleName {
  713. datas.append(data)
  714. }
  715. }
  716. return datas
  717. }
  718. private func _editAreasFontNames() -> [String] {
  719. var datas: [String] = []
  720. for area in self.editingTextAreas {
  721. if let data = self.listView?.editingSelectionCFont(byRangeEdit: area)?.familyName {
  722. datas.append(data)
  723. }
  724. }
  725. return datas
  726. }
  727. private func _editAreasFontSizes() -> [CGFloat] {
  728. var datas: [CGFloat] = []
  729. for area in self.editingTextAreas {
  730. if let data = self.listView?.editingSelectionFontSize(byRangeEdit: area) {
  731. datas.append(data)
  732. }
  733. }
  734. return datas
  735. }
  736. private func _editAreasFontBolds() -> [Bool] {
  737. var datas: [Bool] = []
  738. for area in self.editingTextAreas {
  739. if let data = self.listView?.isBoldCurrentSelection(byRangeEdit: area) {
  740. datas.append(data)
  741. }
  742. }
  743. return datas
  744. }
  745. private func _editAreasFontItalics() -> [Bool] {
  746. var datas: [Bool] = []
  747. for area in self.editingTextAreas {
  748. if let data = self.listView?.isItalicCurrentSelection(byRangeEdit: area) {
  749. datas.append(data)
  750. }
  751. }
  752. return datas
  753. }
  754. private func _editAreasTextAlignments() -> [NSTextAlignment] {
  755. var datas: [NSTextAlignment] = []
  756. for area in self.editingTextAreas {
  757. if let data = self.listView?.currentSelectionAlignment(byRangeEdit: area) {
  758. datas.append(data)
  759. }
  760. }
  761. return datas
  762. }
  763. private func _editAreasBounds() -> [NSRect] {
  764. var rects: [NSRect] = []
  765. for area in self.editingAreas {
  766. rects.append(area.bounds)
  767. }
  768. return rects
  769. }
  770. private func _editAreasRotates() -> [CGFloat] {
  771. var arr: [CGFloat] = []
  772. for area in self.editingImageAreas {
  773. if let data = self.listView?.getRotateWith(area) {
  774. arr.append(data)
  775. }
  776. }
  777. return arr
  778. }
  779. private func _editAreasOpacitys() -> [CGFloat] {
  780. var arr: [CGFloat] = []
  781. for area in self.editingAreas {
  782. if let data = self.listView?.opacityByRange(for: area) {
  783. arr.append(data)
  784. }
  785. }
  786. return arr
  787. }
  788. }
  789. // MARK: - Action
  790. extension KMEditPDfHanddler {
  791. func fontColorAction(color: NSColor?) {
  792. guard let theColor = color else {
  793. return
  794. }
  795. let areas = self.editingTextAreas
  796. for area in areas {
  797. self.listView?.setEditingSelectionFontColor(theColor, with: area)
  798. }
  799. self._reloadData_right_text()
  800. }
  801. func fontStyleAction(fontName: String?) {
  802. guard let font = CPDFFont.mappingFont(withFontString: fontName) else {
  803. return
  804. }
  805. let areas = self.editingTextAreas
  806. for area in areas {
  807. self.listView?.setEditSelectionCFont(font, with: area)
  808. }
  809. self._reloadData_right_text()
  810. }
  811. func fontAddAction() {
  812. let areas = self.editingTextAreas
  813. for area in areas {
  814. if let fontSize = self.listView?.editingSelectionFontSize(byRangeEdit: area) {
  815. self.listView?.setEditingSelectionFontSize(fontSize+1, with: area, isAutoSize: false)
  816. }
  817. }
  818. self._reloadData_right_text()
  819. }
  820. func fontReduceAction() {
  821. let areas = self.editingTextAreas
  822. for area in areas {
  823. if let fontSize = self.listView?.editingSelectionFontSize(byRangeEdit: area) {
  824. self.listView?.setEditingSelectionFontSize(fontSize-1, with: area, isAutoSize: false)
  825. }
  826. }
  827. self._reloadData_right_text()
  828. }
  829. func fontBoldAction() {
  830. let areas = self.editingTextAreas
  831. for area in areas {
  832. if let data = self.listView?.isBoldCurrentSelection(byRangeEdit: area) {
  833. self.listView?.setCurrentSelectionIsBold(!data, with: area)
  834. }
  835. }
  836. self._reloadData_right_text()
  837. }
  838. func fontItalicAction() {
  839. let areas = self.editingTextAreas
  840. for area in areas {
  841. if let data = self.listView?.isItalicCurrentSelection(byRangeEdit: area) {
  842. self.listView?.setCurrentSelectionIsItalic(!data, with: area)
  843. }
  844. }
  845. self._reloadData_right_text()
  846. }
  847. func textAlignmentAction(align: NSTextAlignment) {
  848. let areas = self.editingTextAreas
  849. for area in areas {
  850. self.listView?.setCurrentSelectionAlignment(align, with: area)
  851. }
  852. self._reloadData_right_text()
  853. }
  854. func leftRotateAction() {
  855. let areas = self.editingImageAreas
  856. for area in areas {
  857. self.listView?.rotate(with: area, rotate: -90)
  858. }
  859. }
  860. func rightRotateAction() {
  861. let areas = self.editingImageAreas
  862. for area in areas {
  863. self.listView?.rotate(with: area, rotate: 90)
  864. }
  865. }
  866. func reverseXAction() {
  867. let areas = self.editingImageAreas
  868. for area in areas {
  869. self.listView?.horizontalMirror(with: area)
  870. }
  871. }
  872. func reverseYAction() {
  873. let areas = self.editingImageAreas
  874. for area in areas {
  875. self.listView?.verticalMirror(with: area)
  876. }
  877. }
  878. func cropAction() {
  879. let areas = self.editingImageAreas
  880. if areas.isEmpty {
  881. return
  882. }
  883. self.listView?.isEditImage = true
  884. for area in areas {
  885. self.listView?.enterCrop(with: area)
  886. }
  887. self.hiddenPopWindow()
  888. Task { @MainActor in
  889. self.showCropComfirmWindow()
  890. }
  891. self.rightViewC?.eidtPDFImageProperty.updateButtonState(hidden: false)
  892. self.viewC?.view.window?.makeFirstResponder(self.listView)
  893. }
  894. func cropCancelAction() {
  895. self.hiddenCropComfirmWindow()
  896. let areas = self.editingImageAreas
  897. if areas.isEmpty {
  898. return
  899. }
  900. for area in areas {
  901. self.listView?.exitCrop(with: area)
  902. }
  903. self.listView?.cropAreas = nil
  904. self.listView?.isEditImage = false
  905. self.rightViewC?.eidtPDFImageProperty.updateButtonState(hidden: true)
  906. Task { @MainActor [weak self] in
  907. if let data = self?.listView?.selectImageAreas {
  908. self?.showPopWindow(positionRect:data.bounds)
  909. }
  910. }
  911. }
  912. func cropComfirmAction() {
  913. guard let selectImageAreas = self.listView?.selectImageAreas else {
  914. self.cropCancelAction()
  915. return
  916. }
  917. self.listView?.cropEditImageArea(selectImageAreas, withBounds: self.listView?.cropAreas.cropRect ?? .zero)
  918. self.cropCancelAction()
  919. }
  920. func replaceAction() {
  921. let areas = self.editingImageAreas
  922. if areas.isEmpty {
  923. return
  924. }
  925. let panel = NSOpenPanel()
  926. panel.allowsMultipleSelection = false
  927. panel.allowedFileTypes = ["png","jpg"]
  928. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  929. if response == .OK {
  930. let openPath = panel.url?.path
  931. for area in areas {
  932. // , rect: data.bounds
  933. self.listView?.replace(area, imagePath: openPath!)
  934. }
  935. }
  936. }
  937. }
  938. func showExportMenu(_ sender: NSView) {
  939. // let menuI = NSMenuItem()
  940. let submenu = NSMenu(title: "")
  941. let jpgMI = submenu.addItem(withTitle: "jpg", action: #selector(exportMenuItemAction), keyEquivalent: "")
  942. jpgMI.target = self
  943. jpgMI.tag = 1
  944. let pngMI = submenu.addItem(withTitle: "png", action: #selector(exportMenuItemAction), keyEquivalent: "")
  945. pngMI.target = self
  946. pngMI.tag = 2
  947. let pdfMI = submenu.addItem(withTitle: "pdf", action: #selector(exportMenuItemAction), keyEquivalent: "")
  948. pdfMI.target = self
  949. pdfMI.tag = 3
  950. let p = NSPoint(x: NSMidX(sender.frame), y: NSMidY(sender.frame))
  951. submenu.popUp(positioning: nil, at: p, in: sender.superview)
  952. }
  953. @objc func exportMenuItemAction(_ sender: NSMenuItem) {
  954. var format = ""
  955. if sender.tag == 1 {
  956. format = "jpg"
  957. } else if sender.tag == 2 {
  958. format = "png"
  959. } else if sender.tag == 3 {
  960. format = "pdf"
  961. }
  962. self.exportAction(format: format)
  963. }
  964. func exportAction(format: String) {
  965. let areas = self.editingImageAreas
  966. if areas.isEmpty {
  967. return
  968. }
  969. if areas.count == 1 {
  970. let panel = NSSavePanel()
  971. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).\(format)"
  972. panel.isExtensionHidden = true
  973. let response = panel.runModal()
  974. if response == .OK {
  975. let url = panel.url
  976. if FileManager.default.fileExists(atPath: url!.path) {
  977. try?FileManager.default.removeItem(atPath: url!.path)
  978. }
  979. let result = self.listView?.extractImage(with: areas.first, toImagePath: url!.path) ?? false
  980. if result {
  981. NSWorkspace.shared.activateFileViewerSelecting([url!])
  982. }
  983. }
  984. } else if areas.count > 1 {
  985. let panel = NSOpenPanel()
  986. panel.canChooseFiles = false
  987. panel.canChooseDirectories = true
  988. panel.canCreateDirectories = true
  989. panel.allowsMultipleSelection = false
  990. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  991. if response == .OK {
  992. let outputURL = panel.url
  993. let s = self.listView?.document?.documentURL.lastPathComponent
  994. let folderPath = (self.listView?.document?.documentURL.deletingPathExtension().lastPathComponent ?? "") + "_extract"
  995. var filePath = outputURL?.path.stringByAppendingPathComponent(folderPath)
  996. var i = 1
  997. let testFilePath = filePath
  998. while FileManager.default.fileExists(atPath: filePath!) {
  999. filePath = testFilePath! + "\(i)"
  1000. i = i + 1
  1001. }
  1002. try? FileManager.default.createDirectory(atPath: filePath!, withIntermediateDirectories: false, attributes: nil)
  1003. var saveURLs : [URL] = []
  1004. let pageIndex = self.listView?.currentPageIndex ?? 0
  1005. for j in 0 ..< areas.count {
  1006. let documentFileName = self.listView?.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  1007. var outPath = filePath!
  1008. outPath = outPath.stringByAppendingPathComponent(documentFileName)
  1009. outPath = outPath + "_page\(pageIndex+1)_\(j+1)"
  1010. outPath = outPath.stringByAppendingPathExtension(format)
  1011. let result = self.listView?.extractImage(with: areas[j], toImagePath: outPath) ?? false
  1012. if result {
  1013. saveURLs.append(URL(fileURLWithPath: outPath))
  1014. }
  1015. }
  1016. NSWorkspace.shared.activateFileViewerSelecting(saveURLs)
  1017. }
  1018. }
  1019. }
  1020. }
  1021. func alignmentAction(align: CPDFActiveAreasAlignType) {
  1022. KMPrint("updateFormAearsAlignMangent")
  1023. let stype = align
  1024. let editingAreas = self.editingAreas
  1025. if editingAreas.count >= 2 {
  1026. var zeroRect = NSRect.null
  1027. var highestRect = NSZeroRect
  1028. var widthestRect = NSZeroRect
  1029. let fristArea : CPDFEditArea = editingAreas.first as! CPDFEditArea
  1030. var leftestRect = fristArea.bounds
  1031. var rightestRect = fristArea.bounds
  1032. var topestRect = fristArea.bounds
  1033. var bottomestRect = fristArea.bounds
  1034. var leftestArea : CPDFEditArea = fristArea
  1035. var rightestArea : CPDFEditArea = fristArea
  1036. var topestArea : CPDFEditArea = fristArea
  1037. var bottomestArea : CPDFEditArea = fristArea
  1038. var totalWidth = 0.0
  1039. var totalHeight = 0.0
  1040. for i in 0 ... editingAreas.count-1 {
  1041. let area : CPDFEditArea = editingAreas[i] as! CPDFEditArea
  1042. zeroRect = zeroRect.union(area.bounds)
  1043. totalWidth = totalWidth + area.bounds.width
  1044. totalHeight = totalHeight + area.bounds.height
  1045. if area.bounds.height > highestRect.height {
  1046. highestRect = area.bounds
  1047. }
  1048. if area.bounds.width > widthestRect.width {
  1049. widthestRect = area.bounds
  1050. }
  1051. if leftestRect.minX > area.bounds.minX {
  1052. leftestRect = area.bounds
  1053. leftestArea = area
  1054. }
  1055. if area.bounds.maxX > rightestRect.maxX {
  1056. rightestRect = area.bounds
  1057. rightestArea = area
  1058. }
  1059. if area.bounds.maxY > topestRect.maxY {
  1060. topestRect = area.bounds
  1061. topestArea = area
  1062. }
  1063. if bottomestRect.minY > area.bounds.minY {
  1064. bottomestRect = area.bounds
  1065. bottomestArea = area
  1066. }
  1067. }
  1068. var resultAreasArray: [Any] = []
  1069. var newBoundsArray: [String] = []
  1070. if stype == .Left {
  1071. for i in 0 ... editingAreas.count-1 {
  1072. let areas = editingAreas[i] as! CPDFEditArea
  1073. var bounds = areas.bounds
  1074. bounds.origin.x = zeroRect.origin.x
  1075. newBoundsArray.append(NSStringFromRect(bounds))
  1076. }
  1077. resultAreasArray = editingAreas
  1078. } else if stype == .Right {
  1079. for i in 0 ... editingAreas.count-1 {
  1080. let areas = editingAreas[i] as! CPDFEditArea
  1081. var bounds = areas.bounds
  1082. bounds.origin.x = zeroRect.maxX - bounds.size.width
  1083. newBoundsArray.append(NSStringFromRect(bounds))
  1084. }
  1085. resultAreasArray = editingAreas
  1086. } else if stype == .Top {
  1087. for i in 0 ... editingAreas.count-1 {
  1088. let areas = editingAreas[i] as! CPDFEditArea
  1089. var bounds = areas.bounds
  1090. bounds.origin.y = zeroRect.maxY - bounds.size.height
  1091. newBoundsArray.append(NSStringFromRect(bounds))
  1092. }
  1093. resultAreasArray = editingAreas
  1094. } else if stype == .Bottom {
  1095. for i in 0 ... editingAreas.count-1 {
  1096. let areas = editingAreas[i] as! CPDFEditArea
  1097. var bounds = areas.bounds
  1098. bounds.origin.y = zeroRect.minY
  1099. newBoundsArray.append(NSStringFromRect(bounds))
  1100. }
  1101. resultAreasArray = editingAreas
  1102. } else if stype == .Horizontally {
  1103. for i in 0 ... editingAreas.count-1 {
  1104. let areas = editingAreas[i] as! CPDFEditArea
  1105. var bounds = areas.bounds
  1106. bounds.origin.y = highestRect.midY - bounds.height/2
  1107. newBoundsArray.append(NSStringFromRect(bounds))
  1108. }
  1109. resultAreasArray = editingAreas
  1110. } else if stype == .Vertical {
  1111. for i in 0 ... editingAreas.count-1 {
  1112. let areas = editingAreas[i] as! CPDFEditArea
  1113. var bounds = areas.bounds
  1114. bounds.origin.x = widthestRect.midX - bounds.width/2
  1115. newBoundsArray.append(NSStringFromRect(bounds))
  1116. }
  1117. resultAreasArray = editingAreas
  1118. } else if stype == .DisHorizontally {
  1119. let middleGap = zeroRect.width - leftestRect.width - rightestRect.width
  1120. let otherAreasTotalWidth = totalWidth - leftestRect.width - rightestRect.width
  1121. let gap = (middleGap - otherAreasTotalWidth)/CGFloat(editingAreas.count - 1)
  1122. var areasCopyArray : [CPDFEditArea] = editingAreas as! [CPDFEditArea]
  1123. areasCopyArray.sorted(by: { obj1, obj2 in
  1124. let area1 = obj1
  1125. let area2 = obj2
  1126. if area1.bounds.origin.x < area2.bounds.origin.x {
  1127. return true
  1128. } else {
  1129. return false
  1130. }
  1131. })
  1132. if let index = areasCopyArray.firstIndex(of: leftestArea) {
  1133. areasCopyArray.remove(at: index)
  1134. }
  1135. if let index = areasCopyArray.firstIndex(of: rightestArea) {
  1136. areasCopyArray.remove(at: index)
  1137. }
  1138. var leftStartX = leftestRect.maxX + gap
  1139. for i in 0 ..< areasCopyArray.count {
  1140. let areas = areasCopyArray[i]
  1141. var bounds = areas.bounds
  1142. bounds.origin.x = leftStartX
  1143. newBoundsArray.append(NSStringFromRect(bounds))
  1144. leftStartX = leftStartX + bounds.width + gap
  1145. }
  1146. resultAreasArray = areasCopyArray
  1147. } else if stype == .DisVertical {
  1148. let middleGap = zeroRect.height - topestRect.height - bottomestRect.height
  1149. let otherAreasTotalHeight = totalHeight - topestRect.height - bottomestRect.height
  1150. let gap = (middleGap - otherAreasTotalHeight)/CGFloat(editingAreas.count - 1)
  1151. var areasCopyArray : [CPDFEditArea] = editingAreas as! [CPDFEditArea]
  1152. areasCopyArray.sorted(by: { obj1, obj2 in
  1153. let area1 = obj1
  1154. let area2 = obj2
  1155. if area1.bounds.origin.x < area2.bounds.origin.x {
  1156. return true
  1157. } else {
  1158. return false
  1159. }
  1160. })
  1161. if let index = areasCopyArray.firstIndex(of: topestArea) {
  1162. areasCopyArray.remove(at: index)
  1163. }
  1164. if let index = areasCopyArray.firstIndex(of: bottomestArea) {
  1165. areasCopyArray.remove(at: index)
  1166. }
  1167. var bottomStartY = bottomestRect.maxY + gap
  1168. for i in 0 ... areasCopyArray.count-1 {
  1169. let areas = areasCopyArray[i]
  1170. var bounds = areas.bounds
  1171. bounds.origin.y = bottomStartY
  1172. newBoundsArray.append(NSStringFromRect(bounds))
  1173. bottomStartY = bottomStartY + bounds.height + gap
  1174. }
  1175. resultAreasArray = areasCopyArray
  1176. }
  1177. var oldBounds : [String] = []
  1178. for i in 0 ..< resultAreasArray.count {
  1179. let area : CPDFEditArea = resultAreasArray[i] as! CPDFEditArea
  1180. oldBounds.append(NSStringFromRect(area.bounds))
  1181. self.listView?.setBoundsEditArea(area, withBounds: NSRectFromString(newBoundsArray[i]))
  1182. }
  1183. self.listView?.setNeedsDisplayForVisiblePages()
  1184. }
  1185. }
  1186. }
  1187. // MARK: - CPDFViewDelegate
  1188. extension KMEditPDfHanddler: CPDFViewDelegate {
  1189. // 编辑区块已经改变
  1190. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  1191. let isEdited = self.listView?.isEdited() ?? false
  1192. if isEdited {
  1193. // 记录编辑状态
  1194. self.viewC?.recordIsPDFDocumentEdited(type: .editText)
  1195. }
  1196. if annotationType != .addText {
  1197. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView?.document)
  1198. }
  1199. let areas = self.listView?.editingAreas() as? [CPDFEditArea] ?? []
  1200. if areas.isEmpty {
  1201. self.hiddenPopWindow()
  1202. self.hiddenCropComfirmWindow()
  1203. let toolMode = self.listView?.toolMode ?? .none
  1204. let annotationType = self.annotationType
  1205. if toolMode == .editPDFToolMode {
  1206. if annotationType == .addImage || annotationType == .addText {
  1207. if self.isEditImage {
  1208. self.viewC?.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1209. } else {
  1210. // if self.listView.annotationType == .addImage {
  1211. // self.closeRightPane()
  1212. // }
  1213. if annotationType == .addImage {
  1214. if self.rightViewC?.eidtPDFImageProperty != nil {
  1215. self.rightViewC?.eidtPDFImageProperty.reloadData()
  1216. }
  1217. }
  1218. // self.openRightPane()
  1219. }
  1220. } else {
  1221. // self.viewC?.closeRightPane()
  1222. self.rightViewC?.isHidden = true
  1223. }
  1224. } else {
  1225. self.rightViewC?.isHidden = true
  1226. self.viewC?.closeRightPane()
  1227. if self.subViewType == .EditPDFAddText && annotationType == .addText {
  1228. self.rightViewC?.eidtPDFTextProperty.initData()
  1229. }
  1230. }
  1231. return
  1232. }
  1233. self.hiddenCropComfirmWindow()
  1234. self.viewC?.model.isPDFTextImageEdited = true
  1235. let subViewType = self.rightViewC?.subViewType ?? .None
  1236. if self.annotationType == .addImage {
  1237. var isImageArea = false
  1238. for i in 0 ..< areas.count {
  1239. if areas[i] is CPDFEditImageArea {
  1240. isImageArea = true
  1241. }
  1242. }
  1243. if isImageArea {
  1244. self.rightViewC?.isHidden = false
  1245. if self.subViewType == .EditPDFAddImage {
  1246. self.rightViewC?.subViewType = .EditPDFAddImage
  1247. self.rightViewC?.eidtPDFImageProperty.handdler = self
  1248. self.rightViewC?.eidtPDFImageProperty.reloadData()
  1249. }
  1250. self.openRightPane()
  1251. } else {
  1252. self.rightViewC?.isHidden = true
  1253. // self.viewC?.closeRightPane()
  1254. }
  1255. } else if self.subViewType == .EditPDFAddText && annotationType == .addText {
  1256. self.rightViewC?.isHidden = false
  1257. let count = self.listView?.editingSelectionString()?.count ?? 0
  1258. if count != 0 {
  1259. self.rightViewC?.eidtPDFTextProperty.reloadData()
  1260. } else {
  1261. self.rightViewC?.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1262. }
  1263. self.openRightPane()
  1264. } else {
  1265. var textsAreas : [CPDFEditTextArea] = []
  1266. var imagesAreas : [CPDFEditImageArea] = []
  1267. let count = self.listView?.editingAreas()?.count ?? 0
  1268. if count < 1 {
  1269. return
  1270. }
  1271. for i in 0 ..< areas.count {
  1272. if areas[i] is CPDFEditTextArea {
  1273. textsAreas.append(areas[i] as! CPDFEditTextArea)
  1274. }
  1275. if areas[i] is CPDFEditImageArea {
  1276. imagesAreas.append(areas[i] as! CPDFEditImageArea)
  1277. }
  1278. }
  1279. if textsAreas.count > 0 && textsAreas.count == areas.count {
  1280. self.rightViewC?.isHidden = false
  1281. self.rightViewC?.subViewType = .EditPDFAddText
  1282. self.rightViewC?.eidtPDFTextProperty.handdler = self
  1283. self.rightViewC?.eidtPDFTextProperty?.reloadData()
  1284. self.openRightPane()
  1285. } else if imagesAreas.count > 0 {
  1286. self.rightViewC?.isHidden = false
  1287. self.rightViewC?.subViewType = .EditPDFAddImage
  1288. self.rightViewC?.eidtPDFImageProperty.handdler = self
  1289. self.rightViewC?.eidtPDFImageProperty?.reloadData()
  1290. self.openRightPane()
  1291. }
  1292. }
  1293. var flag: CPDFEditArea?
  1294. for area in areas {
  1295. if flag == nil {
  1296. flag = area
  1297. continue
  1298. }
  1299. if let data = flag, data.bounds.maxY < area.bounds.maxY {
  1300. flag = area
  1301. }
  1302. }
  1303. if let data = flag {
  1304. self.showPopWindow(positionRect: data.bounds)
  1305. }
  1306. }
  1307. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  1308. if editArea != nil && (editArea is CPDFEditImageArea){
  1309. self.listView?.cropAreas = editArea as? CPDFEditImageArea
  1310. }
  1311. }
  1312. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1313. if self.isEditImage {
  1314. self.viewC?.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1315. } else {
  1316. let window = KMEditPDFPopToolBarWindow.shared
  1317. if (window.isVisible) {
  1318. self.listView?.updateEditing([])
  1319. self.hiddenPopWindow()
  1320. self.hiddenCropComfirmWindow()
  1321. return
  1322. }
  1323. let panel = NSOpenPanel()
  1324. panel.allowsMultipleSelection = false
  1325. panel.allowedFileTypes = ["png","jpg"]
  1326. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  1327. if response == .OK {
  1328. var filePath = panel.url?.path
  1329. var image = NSImage.init(contentsOf: panel.url!)
  1330. //图片自适应范围
  1331. if image != nil {
  1332. var imageRect = rect
  1333. let imageSize = image!.size
  1334. var previewSize = rect.size
  1335. var isChangeSize = false
  1336. if previewSize.width == 0 && previewSize.height == 0 {
  1337. previewSize = CGSize(width: 500, height: 500)
  1338. isChangeSize = true
  1339. }
  1340. let scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  1341. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  1342. if isChangeSize {
  1343. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  1344. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  1345. } else {
  1346. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  1347. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  1348. }
  1349. imageRect.size = newSize
  1350. let limitWidth = 1920.0
  1351. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  1352. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  1353. targetSize: CGSize(width: limitWidth, height: limitWidth),
  1354. maxSizeInBytes: 1024 * 1024 * 5,
  1355. targetCompression: 1.0)
  1356. }
  1357. //自适应page
  1358. let pageRect = self.listView?.currentPage().bounds ?? .zero
  1359. if imageRect.width > pageRect.width ||
  1360. imageRect.height > pageRect.height {
  1361. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  1362. imageRect = CGRect(x: imageRect.origin.x,
  1363. y: imageRect.origin.y,
  1364. width: imageRect.width * pageScale,
  1365. height: imageRect.height * pageScale)
  1366. }
  1367. if imageRect.origin.x < 0 {
  1368. imageRect.origin.x = 5
  1369. }
  1370. if imageRect.origin.y < 0 {
  1371. imageRect.origin.y = 5
  1372. }
  1373. if imageRect.origin.x + imageRect.width > pageRect.width ||
  1374. imageRect.origin.y + imageRect.height > pageRect.height {
  1375. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  1376. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  1377. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  1378. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  1379. }
  1380. DispatchQueue.main.async {
  1381. self.listView?.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  1382. self.viewC?.model.isPDFTextImageEdited = true
  1383. self.viewC?.recordIsPDFDocumentEdited(type: .editImage)
  1384. self.showPopWindow(positionRect: imageRect)
  1385. }
  1386. }
  1387. }
  1388. }
  1389. }
  1390. }
  1391. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1392. let window = KMEditPDFPopToolBarWindow.shared
  1393. if (window.isVisible) {
  1394. self.hiddenPopWindow()
  1395. let areas = self.listView?.editingAreas() as? [CPDFEditArea] ?? []
  1396. if let area = areas.last {
  1397. if let data = area as? CPDFEditTextArea {
  1398. if let str = data.editTextAreaString(), str.isEmpty {
  1399. self.listView?.remove(with: [area])
  1400. } else {
  1401. self.listView?.updateEditing([])
  1402. }
  1403. }
  1404. }
  1405. return
  1406. }
  1407. var newRect = rect
  1408. if CGSizeEqualToSize(rect.size, .zero) {
  1409. newRect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  1410. } else {
  1411. newRect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  1412. }
  1413. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  1414. // let fontName = KMEditPDFTextManager.manager.fetchFontName(fontName: model.fontName)
  1415. let fontSize = model.fontSize
  1416. let fontColor = model.color
  1417. let fontAlign = model.alignment
  1418. let fontStyle = KMEditPDFTextManager.manager.fetchFontStyle(fontName: model.fontName)
  1419. NSColorPanel.shared.color = fontColor
  1420. // let font = KMEditPDFTextManager.manager.fetchFont(fontName: fontName, style: fontStyle, size: fontSize)
  1421. let cfont = CPDFFont(familyName: model.fontName, fontStyle: fontStyle)
  1422. let fontNameZ = CPDFFont.convertAppleFont(cfont)
  1423. let font = NSFont(name: fontNameZ ?? "Helvetica", size: fontSize)
  1424. let attri = CEditAttributes()
  1425. attri.font = font!
  1426. attri.fontColor = fontColor
  1427. attri.alignment = fontAlign
  1428. self.listView?.createStringBounds(newRect, with: attri, page: page)
  1429. // self.rightViewC != nil &&
  1430. if self.subViewType == .EditPDFAddText && self.annotationType == .addText {
  1431. self.rightViewC?.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1432. }
  1433. self.showPopWindow(positionRect: newRect)
  1434. }
  1435. // 文本区块 选中文本已经变化
  1436. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  1437. // self.viewC?.rightSideViewController != nil &&
  1438. if self.subViewType == .EditPDFAddText {
  1439. self.rightViewC?.eidtPDFTextProperty.reloadData()
  1440. self.rightViewC?.eidtPDFTextProperty.updateTextTextPresuppositionState()
  1441. self.showPopWindow(positionRect: .zero)
  1442. }
  1443. }
  1444. func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
  1445. let areas = self.editingAreas
  1446. if areas.count == 1 {
  1447. if let data = areas.first as? CPDFEditImageArea {
  1448. let updating = self.listView?.editAreaBoundUpdating ?? false
  1449. if updating {
  1450. self.listView?.editAreaBoundUpdating = false
  1451. } else {
  1452. self.rightViewC?.eidtPDFImageProperty.reloadData()
  1453. }
  1454. }
  1455. }
  1456. }
  1457. func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
  1458. }
  1459. func pdfViewMobileEditingBegan(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  1460. self.hiddenPopWindow()
  1461. }
  1462. func pdfViewMobileEditingMove(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  1463. }
  1464. func pdfViewMobileEditingEnd(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  1465. self.showPopWindow(positionRect: .zero)
  1466. }
  1467. func pdfViewEditingSelectCharDidChanged(_ pdfView: CPDFView!) {
  1468. let areas = self.editingTextAreas
  1469. if areas.isEmpty {
  1470. return
  1471. }
  1472. if self.subViewType == .EditPDFAddText {
  1473. // self.rightViewC?.eidtPDFTextProperty.reloadData()
  1474. // self.rightViewC?.eidtPDFTextProperty.updateTextTextPresuppositionState()
  1475. self.showPopWindow(positionRect: .zero)
  1476. }
  1477. }
  1478. }