KMEditPDfHanddler.swift 65 KB

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