KMEditPDfHanddler.swift 66 KB

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