KMEditPDfHanddler.swift 62 KB

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