KMEditPDfHanddler.swift 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666
  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. let width = win.frame.size.width
  453. let offsetX = x + width - NSMaxX(winFrame)
  454. if offsetX > 0 { // 超出右编辑
  455. x -= offsetX
  456. }
  457. var y = max(0, position.y)
  458. let screenFrame = NSScreen.main?.frame ?? .zero
  459. if y + 44 + 40 >= screenFrame.size.height {
  460. y = screenFrame.size.height - 44 - 40
  461. }
  462. let wframe = NSMakeRect(x, y, width, 44)
  463. win.setFrame(wframe, display: true)
  464. if CGRectContainsRect(winFrame, wframe) == false {
  465. self.hiddenPopWindow()
  466. }
  467. }
  468. }
  469. private func _reloadData_right_text() {
  470. self.rightViewC?.eidtPDFTextProperty.reloadData()
  471. }
  472. private func _reloadData_right_image() {
  473. self.rightViewC?.eidtPDFImageProperty.reloadData()
  474. }
  475. }
  476. // MARK: - Tools
  477. extension KMEditPDfHanddler {
  478. func editAreasIsEmpty() -> Bool {
  479. return self.editingAreas.isEmpty
  480. }
  481. func editAreasHavTextArea() -> Bool {
  482. return self.editingTextAreas.isEmpty == false
  483. }
  484. func editAreasHavImageArea() -> Bool {
  485. return self.editingImageAreas.isEmpty == false
  486. }
  487. func editAreasFontColorIsEqual() -> Bool {
  488. if self.editAreasIsEmpty() {
  489. return false
  490. }
  491. let datas = self._editAreasFontColors()
  492. if datas.count == 1 {
  493. return true
  494. }
  495. let color = datas.first
  496. for (i, d) in datas.enumerated() {
  497. if i == 0 {
  498. continue
  499. }
  500. if d != color {
  501. return false
  502. }
  503. }
  504. return true
  505. }
  506. func editAreasFontNameIsEqual() -> Bool {
  507. if self.editAreasIsEmpty() {
  508. return false
  509. }
  510. let datas = self._editAreasFontNames()
  511. if datas.count == 1 {
  512. return true
  513. }
  514. let data = datas.first
  515. for (i, d) in datas.enumerated() {
  516. if i == 0 {
  517. continue
  518. }
  519. if d != data {
  520. return false
  521. }
  522. }
  523. return true
  524. }
  525. func editAreasFontStyleIsEqual() -> Bool {
  526. if self.editAreasIsEmpty() {
  527. return false
  528. }
  529. let datas = self._editAreasFontStyles()
  530. if datas.count == 1 {
  531. return true
  532. }
  533. let data = datas.first
  534. for (i, d) in datas.enumerated() {
  535. if i == 0 {
  536. continue
  537. }
  538. if d != data {
  539. return false
  540. }
  541. }
  542. return true
  543. }
  544. func editAreasFontSizeIsEqual() -> Bool {
  545. if self.editAreasIsEmpty() {
  546. return false
  547. }
  548. let datas = self._editAreasFontSizes()
  549. if datas.count == 1 {
  550. return true
  551. }
  552. let data = datas.first
  553. for (i, d) in datas.enumerated() {
  554. if i == 0 {
  555. continue
  556. }
  557. if d != data {
  558. return false
  559. }
  560. }
  561. return true
  562. }
  563. func editAreasFontBoldIsEqual() -> Bool {
  564. if self.editAreasIsEmpty() {
  565. return false
  566. }
  567. let datas = self._editAreasFontBolds()
  568. if datas.count == 1 {
  569. return true
  570. }
  571. let data = datas.first
  572. for (i, d) in datas.enumerated() {
  573. if i == 0 {
  574. continue
  575. }
  576. if d != data {
  577. return false
  578. }
  579. }
  580. return true
  581. }
  582. func editAreasFontItalicIsEqual() -> Bool {
  583. if self.editAreasIsEmpty() {
  584. return false
  585. }
  586. let datas = self._editAreasFontItalics()
  587. if datas.count == 1 {
  588. return true
  589. }
  590. let data = datas.first
  591. for (i, d) in datas.enumerated() {
  592. if i == 0 {
  593. continue
  594. }
  595. if d != data {
  596. return false
  597. }
  598. }
  599. return true
  600. }
  601. func editAreasTextAlignmentIsEqual() -> Bool {
  602. if self.editAreasIsEmpty() {
  603. return false
  604. }
  605. let datas = self._editAreasTextAlignments()
  606. if datas.count == 1 {
  607. return true
  608. }
  609. let data = datas.first?.rawValue ?? 0
  610. for (i, d) in datas.enumerated() {
  611. if i == 0 {
  612. continue
  613. }
  614. if d.rawValue != data {
  615. return false
  616. }
  617. }
  618. return true
  619. }
  620. func editAreasBoundsIsEqualForWidth() -> Bool {
  621. if self.editAreasIsEmpty() {
  622. return false
  623. }
  624. let rects = self._editAreasBounds()
  625. if rects.count == 1 {
  626. return true
  627. }
  628. let width = rects.first?.width ?? 0
  629. for (i, rect) in rects.enumerated() {
  630. if i == 0 {
  631. continue
  632. }
  633. if width != rect.size.width {
  634. return false
  635. }
  636. }
  637. return true
  638. }
  639. func editAreasBoundsIsEqualForHeight() -> Bool {
  640. if self.editAreasIsEmpty() {
  641. return false
  642. }
  643. let rects = self._editAreasBounds()
  644. if rects.count == 1 {
  645. return true
  646. }
  647. let height = rects.first?.height ?? 0
  648. for (i, rect) in rects.enumerated() {
  649. if i == 0 {
  650. continue
  651. }
  652. if height != rect.size.height {
  653. return false
  654. }
  655. }
  656. return true
  657. }
  658. func editAreasRotateIsEqual() -> Bool {
  659. if self.editAreasIsEmpty() {
  660. return false
  661. }
  662. if self.editAreasHavTextArea() {
  663. return false
  664. }
  665. let datas = self._editAreasRotates()
  666. if datas.count == 1 {
  667. return true
  668. }
  669. let data = datas.first ?? 0
  670. for (i, d) in datas.enumerated() {
  671. if i == 0 {
  672. continue
  673. }
  674. if data != d {
  675. return false
  676. }
  677. }
  678. return true
  679. }
  680. func editAreasOpacityIsEqual() -> Bool {
  681. if self.editAreasIsEmpty() {
  682. return false
  683. }
  684. let datas = self._editAreasOpacitys()
  685. if datas.count == 1 {
  686. return true
  687. }
  688. let data = datas.first ?? 0
  689. for (i, d) in datas.enumerated() {
  690. if i == 0 {
  691. continue
  692. }
  693. if data != d {
  694. return false
  695. }
  696. }
  697. return true
  698. }
  699. private func _editAreasFontColors() -> [NSColor] {
  700. var datas: [NSColor] = []
  701. for area in self.editingTextAreas {
  702. if let data = self.listView?.editingSelectionFontColor(byRangeEdit: area) {
  703. datas.append(data)
  704. }
  705. }
  706. return datas
  707. }
  708. private func _editAreasFontStyles() -> [String] {
  709. var datas: [String] = []
  710. for area in self.editingTextAreas {
  711. if let data = self.listView?.editingSelectionCFont(byRangeEdit: area)?.styleName {
  712. datas.append(data)
  713. }
  714. }
  715. return datas
  716. }
  717. private func _editAreasFontNames() -> [String] {
  718. var datas: [String] = []
  719. for area in self.editingTextAreas {
  720. if let data = self.listView?.editingSelectionCFont(byRangeEdit: area)?.familyName {
  721. datas.append(data)
  722. }
  723. }
  724. return datas
  725. }
  726. private func _editAreasFontSizes() -> [CGFloat] {
  727. var datas: [CGFloat] = []
  728. for area in self.editingTextAreas {
  729. if let data = self.listView?.editingSelectionFontSize(byRangeEdit: area) {
  730. datas.append(data)
  731. }
  732. }
  733. return datas
  734. }
  735. private func _editAreasFontBolds() -> [Bool] {
  736. var datas: [Bool] = []
  737. for area in self.editingTextAreas {
  738. if let data = self.listView?.isBoldCurrentSelection(byRangeEdit: area) {
  739. datas.append(data)
  740. }
  741. }
  742. return datas
  743. }
  744. private func _editAreasFontItalics() -> [Bool] {
  745. var datas: [Bool] = []
  746. for area in self.editingTextAreas {
  747. if let data = self.listView?.isItalicCurrentSelection(byRangeEdit: area) {
  748. datas.append(data)
  749. }
  750. }
  751. return datas
  752. }
  753. private func _editAreasTextAlignments() -> [NSTextAlignment] {
  754. var datas: [NSTextAlignment] = []
  755. for area in self.editingTextAreas {
  756. if let data = self.listView?.currentSelectionAlignment(byRangeEdit: area) {
  757. datas.append(data)
  758. }
  759. }
  760. return datas
  761. }
  762. private func _editAreasBounds() -> [NSRect] {
  763. var rects: [NSRect] = []
  764. for area in self.editingAreas {
  765. rects.append(area.bounds)
  766. }
  767. return rects
  768. }
  769. private func _editAreasRotates() -> [CGFloat] {
  770. var arr: [CGFloat] = []
  771. for area in self.editingImageAreas {
  772. if let data = self.listView?.getRotateWith(area) {
  773. arr.append(data)
  774. }
  775. }
  776. return arr
  777. }
  778. private func _editAreasOpacitys() -> [CGFloat] {
  779. var arr: [CGFloat] = []
  780. for area in self.editingAreas {
  781. if let data = self.listView?.opacityByRange(for: area) {
  782. arr.append(data)
  783. }
  784. }
  785. return arr
  786. }
  787. }
  788. // MARK: - Action
  789. extension KMEditPDfHanddler {
  790. func fontColorAction(color: NSColor?) {
  791. guard let theColor = color else {
  792. return
  793. }
  794. let areas = self.editingTextAreas
  795. for area in areas {
  796. self.listView?.setEditingSelectionFontColor(theColor, with: area)
  797. }
  798. self._reloadData_right_text()
  799. }
  800. func fontStyleAction(fontName: String?) {
  801. guard let font = CPDFFont.mappingFont(withFontString: fontName) else {
  802. return
  803. }
  804. let areas = self.editingTextAreas
  805. for area in areas {
  806. self.listView?.setEditSelectionCFont(font, with: area)
  807. }
  808. self._reloadData_right_text()
  809. }
  810. func fontAddAction() {
  811. let areas = self.editingTextAreas
  812. for area in areas {
  813. if let fontSize = self.listView?.editingSelectionFontSize(byRangeEdit: area) {
  814. self.listView?.setEditingSelectionFontSize(fontSize+1, with: area, isAutoSize: false)
  815. }
  816. }
  817. self._reloadData_right_text()
  818. }
  819. func fontReduceAction() {
  820. let areas = self.editingTextAreas
  821. for area in areas {
  822. if let fontSize = self.listView?.editingSelectionFontSize(byRangeEdit: area) {
  823. self.listView?.setEditingSelectionFontSize(fontSize-1, with: area, isAutoSize: false)
  824. }
  825. }
  826. self._reloadData_right_text()
  827. }
  828. func fontBoldAction() {
  829. let areas = self.editingTextAreas
  830. for area in areas {
  831. if let data = self.listView?.isBoldCurrentSelection(byRangeEdit: area) {
  832. self.listView?.setCurrentSelectionIsBold(!data, with: area)
  833. }
  834. }
  835. self._reloadData_right_text()
  836. }
  837. func fontItalicAction() {
  838. let areas = self.editingTextAreas
  839. for area in areas {
  840. if let data = self.listView?.isItalicCurrentSelection(byRangeEdit: area) {
  841. self.listView?.setCurrentSelectionIsItalic(!data, with: area)
  842. }
  843. }
  844. self._reloadData_right_text()
  845. }
  846. func textAlignmentAction(align: NSTextAlignment) {
  847. let areas = self.editingTextAreas
  848. for area in areas {
  849. self.listView?.setCurrentSelectionAlignment(align, with: area)
  850. }
  851. self._reloadData_right_text()
  852. }
  853. func leftRotateAction() {
  854. let areas = self.editingImageAreas
  855. for area in areas {
  856. self.listView?.rotate(with: area, rotate: -90)
  857. }
  858. }
  859. func rightRotateAction() {
  860. let areas = self.editingImageAreas
  861. for area in areas {
  862. self.listView?.rotate(with: area, rotate: 90)
  863. }
  864. }
  865. func reverseXAction() {
  866. let areas = self.editingImageAreas
  867. for area in areas {
  868. self.listView?.horizontalMirror(with: area)
  869. }
  870. }
  871. func reverseYAction() {
  872. let areas = self.editingImageAreas
  873. for area in areas {
  874. self.listView?.verticalMirror(with: area)
  875. }
  876. }
  877. func cropAction() {
  878. let areas = self.editingImageAreas
  879. if areas.isEmpty {
  880. return
  881. }
  882. self.listView?.isEditImage = true
  883. for area in areas {
  884. self.listView?.enterCrop(with: area)
  885. }
  886. self.hiddenPopWindow()
  887. Task { @MainActor in
  888. self.showCropComfirmWindow()
  889. }
  890. self.rightViewC?.eidtPDFImageProperty.updateButtonState(hidden: false)
  891. self.viewC?.view.window?.makeFirstResponder(self.listView)
  892. }
  893. func cropCancelAction() {
  894. self.hiddenCropComfirmWindow()
  895. let areas = self.editingImageAreas
  896. if areas.isEmpty {
  897. return
  898. }
  899. for area in areas {
  900. self.listView?.exitCrop(with: area)
  901. }
  902. self.listView?.cropAreas = nil
  903. self.listView?.isEditImage = false
  904. self.rightViewC?.eidtPDFImageProperty.updateButtonState(hidden: true)
  905. Task { @MainActor [weak self] in
  906. if let data = self?.listView?.selectImageAreas {
  907. self?.showPopWindow(positionRect:data.bounds)
  908. }
  909. }
  910. }
  911. func cropComfirmAction() {
  912. guard let selectImageAreas = self.listView?.selectImageAreas else {
  913. self.cropCancelAction()
  914. return
  915. }
  916. self.listView?.cropEditImageArea(selectImageAreas, withBounds: self.listView?.cropAreas.cropRect ?? .zero)
  917. self.cropCancelAction()
  918. }
  919. func replaceAction() {
  920. let areas = self.editingImageAreas
  921. if areas.isEmpty {
  922. return
  923. }
  924. let panel = NSOpenPanel()
  925. panel.allowsMultipleSelection = false
  926. panel.allowedFileTypes = ["png","jpg"]
  927. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  928. if response == .OK {
  929. let openPath = panel.url?.path
  930. for area in areas {
  931. // , rect: data.bounds
  932. self.listView?.replace(area, imagePath: openPath!)
  933. }
  934. }
  935. }
  936. }
  937. func showExportMenu(_ sender: NSView) {
  938. // let menuI = NSMenuItem()
  939. let submenu = NSMenu(title: "")
  940. let jpgMI = submenu.addItem(withTitle: "jpg", action: #selector(exportMenuItemAction), keyEquivalent: "")
  941. jpgMI.target = self
  942. jpgMI.tag = 1
  943. let pngMI = submenu.addItem(withTitle: "png", action: #selector(exportMenuItemAction), keyEquivalent: "")
  944. pngMI.target = self
  945. pngMI.tag = 2
  946. let pdfMI = submenu.addItem(withTitle: "pdf", action: #selector(exportMenuItemAction), keyEquivalent: "")
  947. pdfMI.target = self
  948. pdfMI.tag = 3
  949. let p = NSPoint(x: NSMidX(sender.frame), y: NSMidY(sender.frame))
  950. submenu.popUp(positioning: nil, at: p, in: sender.superview)
  951. }
  952. @objc func exportMenuItemAction(_ sender: NSMenuItem) {
  953. var format = ""
  954. if sender.tag == 1 {
  955. format = "jpg"
  956. } else if sender.tag == 2 {
  957. format = "png"
  958. } else if sender.tag == 3 {
  959. format = "pdf"
  960. }
  961. self.exportAction(format: format)
  962. }
  963. func exportAction(format: String) {
  964. let areas = self.editingImageAreas
  965. if areas.isEmpty {
  966. return
  967. }
  968. if areas.count == 1 {
  969. let panel = NSSavePanel()
  970. panel.nameFieldStringValue = "\(NSLocalizedString("Untitled", comment: "")).\(format)"
  971. panel.isExtensionHidden = true
  972. let response = panel.runModal()
  973. if response == .OK {
  974. let url = panel.url
  975. if FileManager.default.fileExists(atPath: url!.path) {
  976. try?FileManager.default.removeItem(atPath: url!.path)
  977. }
  978. let result = self.listView?.extractImage(with: areas.first, toImagePath: url!.path) ?? false
  979. if result {
  980. NSWorkspace.shared.activateFileViewerSelecting([url!])
  981. }
  982. }
  983. } else if areas.count > 1 {
  984. let panel = NSOpenPanel()
  985. panel.canChooseFiles = false
  986. panel.canChooseDirectories = true
  987. panel.canCreateDirectories = true
  988. panel.allowsMultipleSelection = false
  989. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  990. if response == .OK {
  991. let outputURL = panel.url
  992. let s = self.listView?.document?.documentURL.lastPathComponent
  993. let folderPath = (self.listView?.document?.documentURL.deletingPathExtension().lastPathComponent ?? "") + "_extract"
  994. var filePath = outputURL?.path.stringByAppendingPathComponent(folderPath)
  995. var i = 1
  996. let testFilePath = filePath
  997. while FileManager.default.fileExists(atPath: filePath!) {
  998. filePath = testFilePath! + "\(i)"
  999. i = i + 1
  1000. }
  1001. try? FileManager.default.createDirectory(atPath: filePath!, withIntermediateDirectories: false, attributes: nil)
  1002. var saveURLs : [URL] = []
  1003. for j in 0 ..< areas.count {
  1004. let documentFileName = self.listView?.document?.documentURL.deletingPathExtension().lastPathComponent ?? ""
  1005. var outPath = filePath!
  1006. outPath = outPath.stringByAppendingPathComponent(documentFileName)
  1007. outPath = outPath + "page \(j+1)"
  1008. outPath = outPath.stringByAppendingPathExtension(format)
  1009. let result = self.listView?.extractImage(with: areas[j], toImagePath: outPath) ?? false
  1010. if result {
  1011. saveURLs.append(URL(fileURLWithPath: outPath))
  1012. }
  1013. }
  1014. NSWorkspace.shared.activateFileViewerSelecting(saveURLs)
  1015. }
  1016. }
  1017. }
  1018. }
  1019. func alignmentAction(align: CPDFActiveAreasAlignType) {
  1020. KMPrint("updateFormAearsAlignMangent")
  1021. let stype = align
  1022. let editingAreas = self.editingAreas
  1023. if editingAreas.count >= 2 {
  1024. var zeroRect = NSRect.null
  1025. var highestRect = NSZeroRect
  1026. var widthestRect = NSZeroRect
  1027. let fristArea : CPDFEditArea = editingAreas.first as! CPDFEditArea
  1028. var leftestRect = fristArea.bounds
  1029. var rightestRect = fristArea.bounds
  1030. var topestRect = fristArea.bounds
  1031. var bottomestRect = fristArea.bounds
  1032. var leftestArea : CPDFEditArea = fristArea
  1033. var rightestArea : CPDFEditArea = fristArea
  1034. var topestArea : CPDFEditArea = fristArea
  1035. var bottomestArea : CPDFEditArea = fristArea
  1036. var totalWidth = 0.0
  1037. var totalHeight = 0.0
  1038. for i in 0 ... editingAreas.count-1 {
  1039. let area : CPDFEditArea = editingAreas[i] as! CPDFEditArea
  1040. zeroRect = zeroRect.union(area.bounds)
  1041. totalWidth = totalWidth + area.bounds.width
  1042. totalHeight = totalHeight + area.bounds.height
  1043. if area.bounds.height > highestRect.height {
  1044. highestRect = area.bounds
  1045. }
  1046. if area.bounds.width > widthestRect.width {
  1047. widthestRect = area.bounds
  1048. }
  1049. if leftestRect.minX > area.bounds.minX {
  1050. leftestRect = area.bounds
  1051. leftestArea = area
  1052. }
  1053. if area.bounds.maxX > rightestRect.maxX {
  1054. rightestRect = area.bounds
  1055. rightestArea = area
  1056. }
  1057. if area.bounds.maxY > topestRect.maxY {
  1058. topestRect = area.bounds
  1059. topestArea = area
  1060. }
  1061. if bottomestRect.minY > area.bounds.minY {
  1062. bottomestRect = area.bounds
  1063. bottomestArea = area
  1064. }
  1065. }
  1066. var resultAreasArray: [Any] = []
  1067. var newBoundsArray: [String] = []
  1068. if stype == .Left {
  1069. for i in 0 ... editingAreas.count-1 {
  1070. let areas = editingAreas[i] as! CPDFEditArea
  1071. var bounds = areas.bounds
  1072. bounds.origin.x = zeroRect.origin.x
  1073. newBoundsArray.append(NSStringFromRect(bounds))
  1074. }
  1075. resultAreasArray = editingAreas
  1076. } else if stype == .Right {
  1077. for i in 0 ... editingAreas.count-1 {
  1078. let areas = editingAreas[i] as! CPDFEditArea
  1079. var bounds = areas.bounds
  1080. bounds.origin.x = zeroRect.maxX - bounds.size.width
  1081. newBoundsArray.append(NSStringFromRect(bounds))
  1082. }
  1083. resultAreasArray = editingAreas
  1084. } else if stype == .Top {
  1085. for i in 0 ... editingAreas.count-1 {
  1086. let areas = editingAreas[i] as! CPDFEditArea
  1087. var bounds = areas.bounds
  1088. bounds.origin.y = zeroRect.maxY - bounds.size.height
  1089. newBoundsArray.append(NSStringFromRect(bounds))
  1090. }
  1091. resultAreasArray = editingAreas
  1092. } else if stype == .Bottom {
  1093. for i in 0 ... editingAreas.count-1 {
  1094. let areas = editingAreas[i] as! CPDFEditArea
  1095. var bounds = areas.bounds
  1096. bounds.origin.y = zeroRect.minY
  1097. newBoundsArray.append(NSStringFromRect(bounds))
  1098. }
  1099. resultAreasArray = editingAreas
  1100. } else if stype == .Horizontally {
  1101. for i in 0 ... editingAreas.count-1 {
  1102. let areas = editingAreas[i] as! CPDFEditArea
  1103. var bounds = areas.bounds
  1104. bounds.origin.y = highestRect.midY - bounds.height/2
  1105. newBoundsArray.append(NSStringFromRect(bounds))
  1106. }
  1107. resultAreasArray = editingAreas
  1108. } else if stype == .Vertical {
  1109. for i in 0 ... editingAreas.count-1 {
  1110. let areas = editingAreas[i] as! CPDFEditArea
  1111. var bounds = areas.bounds
  1112. bounds.origin.x = widthestRect.midX - bounds.width/2
  1113. newBoundsArray.append(NSStringFromRect(bounds))
  1114. }
  1115. resultAreasArray = editingAreas
  1116. } else if stype == .DisHorizontally {
  1117. let middleGap = zeroRect.width - leftestRect.width - rightestRect.width
  1118. let otherAreasTotalWidth = totalWidth - leftestRect.width - rightestRect.width
  1119. let gap = (middleGap - otherAreasTotalWidth)/CGFloat(editingAreas.count - 1)
  1120. var areasCopyArray : [CPDFEditArea] = editingAreas as! [CPDFEditArea]
  1121. areasCopyArray.sorted(by: { obj1, obj2 in
  1122. let area1 = obj1
  1123. let area2 = obj2
  1124. if area1.bounds.origin.x < area2.bounds.origin.x {
  1125. return true
  1126. } else {
  1127. return false
  1128. }
  1129. })
  1130. if let index = areasCopyArray.firstIndex(of: leftestArea) {
  1131. areasCopyArray.remove(at: index)
  1132. }
  1133. if let index = areasCopyArray.firstIndex(of: rightestArea) {
  1134. areasCopyArray.remove(at: index)
  1135. }
  1136. var leftStartX = leftestRect.maxX + gap
  1137. for i in 0 ..< areasCopyArray.count {
  1138. let areas = areasCopyArray[i]
  1139. var bounds = areas.bounds
  1140. bounds.origin.x = leftStartX
  1141. newBoundsArray.append(NSStringFromRect(bounds))
  1142. leftStartX = leftStartX + bounds.width + gap
  1143. }
  1144. resultAreasArray = areasCopyArray
  1145. } else if stype == .DisVertical {
  1146. let middleGap = zeroRect.height - topestRect.height - bottomestRect.height
  1147. let otherAreasTotalHeight = totalHeight - topestRect.height - bottomestRect.height
  1148. let gap = (middleGap - otherAreasTotalHeight)/CGFloat(editingAreas.count - 1)
  1149. var areasCopyArray : [CPDFEditArea] = editingAreas as! [CPDFEditArea]
  1150. areasCopyArray.sorted(by: { obj1, obj2 in
  1151. let area1 = obj1
  1152. let area2 = obj2
  1153. if area1.bounds.origin.x < area2.bounds.origin.x {
  1154. return true
  1155. } else {
  1156. return false
  1157. }
  1158. })
  1159. if let index = areasCopyArray.firstIndex(of: topestArea) {
  1160. areasCopyArray.remove(at: index)
  1161. }
  1162. if let index = areasCopyArray.firstIndex(of: bottomestArea) {
  1163. areasCopyArray.remove(at: index)
  1164. }
  1165. var bottomStartY = bottomestRect.maxY + gap
  1166. for i in 0 ... areasCopyArray.count-1 {
  1167. let areas = areasCopyArray[i]
  1168. var bounds = areas.bounds
  1169. bounds.origin.y = bottomStartY
  1170. newBoundsArray.append(NSStringFromRect(bounds))
  1171. bottomStartY = bottomStartY + bounds.height + gap
  1172. }
  1173. resultAreasArray = areasCopyArray
  1174. }
  1175. var oldBounds : [String] = []
  1176. for i in 0 ..< resultAreasArray.count {
  1177. let area : CPDFEditArea = resultAreasArray[i] as! CPDFEditArea
  1178. oldBounds.append(NSStringFromRect(area.bounds))
  1179. self.listView?.setBoundsEditArea(area, withBounds: NSRectFromString(newBoundsArray[i]))
  1180. }
  1181. self.listView?.setNeedsDisplayForVisiblePages()
  1182. }
  1183. }
  1184. }
  1185. // MARK: - CPDFViewDelegate
  1186. extension KMEditPDfHanddler: CPDFViewDelegate {
  1187. // 编辑区块已经改变
  1188. func pdfViewEditingAreaDidChanged(_ pdfView: CPDFView!) {
  1189. let isEdited = self.listView?.isEdited() ?? false
  1190. if isEdited {
  1191. // 记录编辑状态
  1192. self.viewC?.recordIsPDFDocumentEdited(type: .editText)
  1193. }
  1194. if annotationType != .addText {
  1195. NotificationCenter.default.post(name: NSNotification.Name(rawValue: "kPDFViewEditingAreaDidChanged"), object: self.listView?.document)
  1196. }
  1197. let areas = self.listView?.editingAreas() as? [CPDFEditArea] ?? []
  1198. if areas.isEmpty {
  1199. self.hiddenPopWindow()
  1200. self.hiddenCropComfirmWindow()
  1201. let toolMode = self.listView?.toolMode ?? .none
  1202. let annotationType = self.annotationType
  1203. if toolMode == .editPDFToolMode {
  1204. if annotationType == .addImage || annotationType == .addText {
  1205. if self.isEditImage {
  1206. self.viewC?.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1207. } else {
  1208. // if self.listView.annotationType == .addImage {
  1209. // self.closeRightPane()
  1210. // }
  1211. if annotationType == .addImage {
  1212. if self.rightViewC?.eidtPDFImageProperty != nil {
  1213. self.rightViewC?.eidtPDFImageProperty.reloadData()
  1214. }
  1215. }
  1216. // self.openRightPane()
  1217. }
  1218. } else {
  1219. // self.viewC?.closeRightPane()
  1220. self.rightViewC?.isHidden = true
  1221. }
  1222. } else {
  1223. self.rightViewC?.isHidden = true
  1224. self.viewC?.closeRightPane()
  1225. if self.subViewType == .EditPDFAddText && annotationType == .addText {
  1226. self.rightViewC?.eidtPDFTextProperty.initData()
  1227. }
  1228. }
  1229. return
  1230. }
  1231. self.hiddenCropComfirmWindow()
  1232. self.viewC?.model.isPDFTextImageEdited = true
  1233. let subViewType = self.rightViewC?.subViewType ?? .None
  1234. if self.annotationType == .addImage {
  1235. var isImageArea = false
  1236. for i in 0 ..< areas.count {
  1237. if areas[i] is CPDFEditImageArea {
  1238. isImageArea = true
  1239. }
  1240. }
  1241. if isImageArea {
  1242. self.rightViewC?.isHidden = false
  1243. if self.subViewType == .EditPDFAddImage {
  1244. self.rightViewC?.subViewType = .EditPDFAddImage
  1245. self.rightViewC?.eidtPDFImageProperty.handdler = self
  1246. self.rightViewC?.eidtPDFImageProperty.reloadData()
  1247. }
  1248. self.openRightPane()
  1249. } else {
  1250. self.rightViewC?.isHidden = true
  1251. // self.viewC?.closeRightPane()
  1252. }
  1253. } else if self.subViewType == .EditPDFAddText && annotationType == .addText {
  1254. self.rightViewC?.isHidden = false
  1255. let count = self.listView?.editingSelectionString()?.count ?? 0
  1256. if count != 0 {
  1257. self.rightViewC?.eidtPDFTextProperty.reloadData()
  1258. } else {
  1259. self.rightViewC?.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1260. }
  1261. self.openRightPane()
  1262. } else {
  1263. var textsAreas : [CPDFEditTextArea] = []
  1264. var imagesAreas : [CPDFEditImageArea] = []
  1265. let count = self.listView?.editingAreas()?.count ?? 0
  1266. if count < 1 {
  1267. return
  1268. }
  1269. for i in 0 ..< areas.count {
  1270. if areas[i] is CPDFEditTextArea {
  1271. textsAreas.append(areas[i] as! CPDFEditTextArea)
  1272. }
  1273. if areas[i] is CPDFEditImageArea {
  1274. imagesAreas.append(areas[i] as! CPDFEditImageArea)
  1275. }
  1276. }
  1277. if textsAreas.count > 0 && textsAreas.count == areas.count {
  1278. self.rightViewC?.isHidden = false
  1279. self.rightViewC?.subViewType = .EditPDFAddText
  1280. self.rightViewC?.eidtPDFTextProperty.handdler = self
  1281. self.rightViewC?.eidtPDFTextProperty?.reloadData()
  1282. self.openRightPane()
  1283. } else if imagesAreas.count > 0 {
  1284. self.rightViewC?.isHidden = false
  1285. self.rightViewC?.subViewType = .EditPDFAddImage
  1286. self.rightViewC?.eidtPDFImageProperty.handdler = self
  1287. self.rightViewC?.eidtPDFImageProperty?.reloadData()
  1288. self.openRightPane()
  1289. }
  1290. }
  1291. var flag: CPDFEditArea?
  1292. for area in areas {
  1293. if flag == nil {
  1294. flag = area
  1295. continue
  1296. }
  1297. if let data = flag, data.bounds.maxY < area.bounds.maxY {
  1298. flag = area
  1299. }
  1300. }
  1301. if let data = flag {
  1302. self.showPopWindow(positionRect: data.bounds)
  1303. }
  1304. }
  1305. func pdfViewEditingCropBoundsDidChanged(_ pdfView: CPDFView!, editing editArea: CPDFEditArea!) {
  1306. if editArea != nil && (editArea is CPDFEditImageArea){
  1307. self.listView?.cropAreas = editArea as? CPDFEditImageArea
  1308. }
  1309. }
  1310. func pdfViewEditingAddImageArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1311. if self.isEditImage {
  1312. self.viewC?.menuItemEditingClick_CropImage(sender: NSMenuItem())
  1313. } else {
  1314. let window = KMEditPDFPopToolBarWindow.shared
  1315. if (window.isVisible) {
  1316. self.listView?.updateEditing([])
  1317. self.hiddenPopWindow()
  1318. self.hiddenCropComfirmWindow()
  1319. return
  1320. }
  1321. let panel = NSOpenPanel()
  1322. panel.allowsMultipleSelection = false
  1323. panel.allowedFileTypes = ["png","jpg"]
  1324. panel.beginSheetModal(for: NSApp.mainWindow!) { response in
  1325. if response == .OK {
  1326. var filePath = panel.url?.path
  1327. var image = NSImage.init(contentsOf: panel.url!)
  1328. //图片自适应范围
  1329. if image != nil {
  1330. var imageRect = rect
  1331. let imageSize = image!.size
  1332. var previewSize = rect.size
  1333. var isChangeSize = false
  1334. if previewSize.width == 0 && previewSize.height == 0 {
  1335. previewSize = CGSize(width: 500, height: 500)
  1336. isChangeSize = true
  1337. }
  1338. let scale = min(previewSize.width / imageSize.width, previewSize.height / imageSize.height)
  1339. let newSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale)
  1340. if isChangeSize {
  1341. imageRect.origin.x = imageRect.origin.x - newSize.width / 2
  1342. imageRect.origin.y = imageRect.origin.y - newSize.height / 2
  1343. } else {
  1344. imageRect.origin.x = imageRect.origin.x + imageRect.width / 2 - newSize.width / 2
  1345. imageRect.origin.y = imageRect.origin.y + imageRect.height / 2 - newSize.height / 2
  1346. }
  1347. imageRect.size = newSize
  1348. let limitWidth = 1920.0
  1349. if imageSize.width > limitWidth || imageSize.height > limitWidth {
  1350. filePath = KMImageOptimization.needCompressImageLosslessly(image: image!,
  1351. targetSize: CGSize(width: limitWidth, height: limitWidth),
  1352. maxSizeInBytes: 1024 * 1024 * 5,
  1353. targetCompression: 1.0)
  1354. }
  1355. //自适应page
  1356. let pageRect = self.listView?.currentPage().bounds ?? .zero
  1357. if imageRect.width > pageRect.width ||
  1358. imageRect.height > pageRect.height {
  1359. let pageScale = min(pageRect.width / imageSize.width, pageRect.height / imageSize.height)
  1360. imageRect = CGRect(x: imageRect.origin.x,
  1361. y: imageRect.origin.y,
  1362. width: imageRect.width * pageScale,
  1363. height: imageRect.height * pageScale)
  1364. }
  1365. if imageRect.origin.x < 0 {
  1366. imageRect.origin.x = 5
  1367. }
  1368. if imageRect.origin.y < 0 {
  1369. imageRect.origin.y = 5
  1370. }
  1371. if imageRect.origin.x + imageRect.width > pageRect.width ||
  1372. imageRect.origin.y + imageRect.height > pageRect.height {
  1373. let offsetX = imageRect.origin.x + imageRect.width - pageRect.width
  1374. let offsetY = imageRect.origin.y + imageRect.height - pageRect.height
  1375. imageRect.origin.x = imageRect.origin.x - offsetX - 5
  1376. imageRect.origin.y = imageRect.origin.y - offsetY - 5
  1377. }
  1378. DispatchQueue.main.async {
  1379. self.listView?.createImagePath(filePath, rect: imageRect, page: pdfView.currentPage())
  1380. self.viewC?.model.isPDFTextImageEdited = true
  1381. self.viewC?.recordIsPDFDocumentEdited(type: .editImage)
  1382. self.showPopWindow(positionRect: imageRect)
  1383. }
  1384. }
  1385. }
  1386. }
  1387. }
  1388. }
  1389. func pdfViewEditingAddTextArea(_ pdfView: CPDFView!, add page: CPDFPage!, add rect: CGRect) {
  1390. let window = KMEditPDFPopToolBarWindow.shared
  1391. if (window.isVisible) {
  1392. self.hiddenPopWindow()
  1393. let areas = self.listView?.editingAreas() as? [CPDFEditArea] ?? []
  1394. if let area = areas.last {
  1395. if let data = area as? CPDFEditTextArea {
  1396. if let str = data.editTextAreaString(), str.isEmpty {
  1397. self.listView?.remove(with: [area])
  1398. }
  1399. }
  1400. }
  1401. return
  1402. }
  1403. var newRect = rect
  1404. if CGSizeEqualToSize(rect.size, .zero) {
  1405. newRect = CGRect(x: rect.origin.x, y: rect.origin.y - 12, width: 20, height: 12)
  1406. } else {
  1407. newRect = CGRect(x: rect.origin.x, y: rect.origin.y + rect.size.height - 12, width: rect.size.width, height: 12)
  1408. }
  1409. let model = KMEditPDFTextManager.manager.fetchUserDefaultData(type: .commonly)
  1410. let fontName = KMEditPDFTextManager.manager.fetchFontName(fontName: model.fontName)
  1411. let fontSize = model.fontSize
  1412. let fontColor = model.color
  1413. let fontAlign = model.alignment
  1414. let fontStyle = KMEditPDFTextManager.manager.fetchFontStyle(fontName: model.fontName)
  1415. NSColorPanel.shared.color = fontColor
  1416. let font = KMEditPDFTextManager.manager.fetchFont(fontName: fontName, style: fontStyle, size: fontSize)
  1417. let attri = CEditAttributes()
  1418. attri.font = font
  1419. attri.fontColor = fontColor
  1420. attri.alignment = fontAlign
  1421. self.listView?.createStringBounds(newRect, with: attri, page: page)
  1422. // self.rightViewC != nil &&
  1423. if self.subViewType == .EditPDFAddText && self.annotationType == .addText {
  1424. self.rightViewC?.eidtPDFTextProperty.refreshSelectAreaProperty(needDefaultData: true)
  1425. }
  1426. self.showPopWindow(positionRect: newRect)
  1427. }
  1428. // 文本区块 选中文本已经变化
  1429. func pdfViewEditingSelectionDidChanged(_ pdfView: CPDFView!) {
  1430. // self.viewC?.rightSideViewController != nil &&
  1431. if self.subViewType == .EditPDFAddText {
  1432. self.rightViewC?.eidtPDFTextProperty.reloadData()
  1433. self.rightViewC?.eidtPDFTextProperty.updateTextTextPresuppositionState()
  1434. self.showPopWindow(positionRect: .zero)
  1435. }
  1436. }
  1437. func pdfViewEditingOperationDidChanged(_ pdfView: CPDFView!) {
  1438. let areas = self.editingAreas
  1439. if areas.count == 1 {
  1440. if let data = areas.first as? CPDFEditImageArea {
  1441. let updating = self.listView?.editAreaBoundUpdating ?? false
  1442. if updating {
  1443. self.listView?.editAreaBoundUpdating = false
  1444. } else {
  1445. self.rightViewC?.eidtPDFImageProperty.reloadData()
  1446. }
  1447. }
  1448. }
  1449. }
  1450. func pdfViewEditingDoubleClick(_ pdfView: CPDFView!, imageArea editArea: CPDFEditArea!) {
  1451. }
  1452. func pdfViewMobileEditingBegan(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  1453. self.hiddenPopWindow()
  1454. }
  1455. func pdfViewMobileEditingMove(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  1456. }
  1457. func pdfViewMobileEditingEnd(_ point: CGPoint, for pdfView: CPDFView!, forEditing editingAreas: [CPDFEditArea]!) {
  1458. self.showPopWindow(positionRect: .zero)
  1459. }
  1460. func pdfViewEditingSelectCharDidChanged(_ pdfView: CPDFView!) {
  1461. let areas = self.editingTextAreas
  1462. if areas.isEmpty {
  1463. return
  1464. }
  1465. if self.subViewType == .EditPDFAddText {
  1466. // self.rightViewC?.eidtPDFTextProperty.reloadData()
  1467. // self.rightViewC?.eidtPDFTextProperty.updateTextTextPresuppositionState()
  1468. self.showPopWindow(positionRect: .zero)
  1469. }
  1470. }
  1471. }