KMEditPDfHanddler.swift 60 KB

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