KMEditPDfHanddler.swift 66 KB

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