KMEditPDfHanddler.swift 60 KB

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