KMEditPDfHanddler.swift 60 KB

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