KMEditPDfHanddler.swift 60 KB

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