KMEditPDfHanddler.swift 63 KB

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