KMEditPDfHanddler.swift 66 KB

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