KMEditPDfHanddler.swift 61 KB

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