KMRedactPDFView.swift 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. //
  2. // KMRedactPDFView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/12/18.
  6. //
  7. import Cocoa
  8. enum KMPDFRedactViewOperationType: Int {
  9. case none = 0 //没有进入任何模式
  10. case redact //标记密文模式
  11. case editText //文本编辑
  12. case redactWhite //密文标记涂白模式
  13. }
  14. private let KMPDFViewShowCurrentRedactAnnotation = "KMPDFViewShowCurrentRedactAnnotation"
  15. private let KMPDFViewRedactAnnotationApply = "KMPDFViewRedactAnnotationApply"
  16. private let KMPDFViewRedactAnnotationAcross = "KMPDFViewRedactAnnotationAcross"
  17. @objcMembers class KMRedactPDFView: CPDFListView {
  18. private let MIN_NOTE_SIZE: CGFloat = 8.0
  19. static let showCurrentRedactAnnotationNotificationName = Notification.Name(KMPDFViewShowCurrentRedactAnnotation)
  20. static let redactAnnotationApplyNotificationName = Notification.Name(KMPDFViewRedactAnnotationApply)
  21. static let redactAnnotationAcrossNotificationName = Notification.Name(KMPDFViewRedactAnnotationAcross)
  22. var mouseMoveAnnotation: CPDFAnnotation?
  23. var currentAnnotation: CPDFRedactAnnotation?
  24. var newAddAnnotation: [CPDFAnnotation] = []
  25. // var activeAnnotations: [CPDFAnnotation] = []
  26. var operationType: KMPDFRedactViewOperationType = .none
  27. var isEidtImageModel = false
  28. var isEidtTextModel = false
  29. var eventColorChanged: ((NSColor)->Void)?
  30. var eventFontChanged: (()->Void)?
  31. var exportBtnTaped: ((Int)->Void)?
  32. private var _localMonitor: AnyObject?
  33. override init(frame frameRect: NSRect) {
  34. super.init(frame: frameRect)
  35. self.operationType = .none
  36. self.addTrackingArea()
  37. self.initMonitor()
  38. }
  39. required init?(coder: NSCoder) {
  40. super.init(coder: coder)
  41. self.operationType = .none
  42. self.addTrackingArea()
  43. self.initMonitor()
  44. }
  45. override func draw(_ dirtyRect: NSRect) {
  46. super.draw(dirtyRect)
  47. // Drawing code here.
  48. }
  49. func resignMonitor() {
  50. if let monitor = self._localMonitor {
  51. NSEvent.removeMonitor(monitor)
  52. self._localMonitor = nil
  53. }
  54. }
  55. func addTrackingArea() {
  56. self.newAddAnnotation = []
  57. self.activeAnnotations = []
  58. let trackingArea = NSTrackingArea(rect: self.bounds, options: [.mouseEnteredAndExited, .inVisibleRect, .activeInKeyWindow], owner: self)
  59. self.addTrackingArea(trackingArea)
  60. }
  61. func initMonitor() {
  62. let mask: NSEvent.EventTypeMask = .keyDown
  63. guard _localMonitor == nil else { return }
  64. _localMonitor = NSEvent.addLocalMonitorForEvents(matching: mask) { event in
  65. // 获取事件的第一个字符
  66. let eventChar = event.PDFListViewFirstCharacter()
  67. // 获取标准的修饰符标志
  68. let modifiers = Self.standardPDFListViewModifierFlags()
  69. // 获取当前响应者
  70. if let currentResponder = NSApp.keyWindow?.firstResponder, !(currentResponder is NSTextView) {
  71. // 如果按下的是删除键,并且没有修饰符,则执行删除操作
  72. if (eventChar == NSDeleteCharacter || eventChar == NSDeleteFunctionKey), modifiers == 0 {
  73. self.delete()
  74. }
  75. // 如果按下的是回车键,并且没有修饰符,则执行图像裁剪完成操作
  76. if event.keyCode == 36, modifiers == 0 {
  77. self.corpImageDoneWithEnter()
  78. }
  79. }
  80. // 返回事件以继续处理
  81. return event
  82. } as AnyObject?
  83. }
  84. override func menu(for event: NSEvent) -> NSMenu? {
  85. var menu = super.menu(for: event)
  86. // if (menu == nil) {
  87. menu = NSMenu()
  88. // }
  89. var pagePoint = NSZeroPoint
  90. // CPDFPage *page = [self pageAndPoint:&pagePoint forEvent:event nearest:YES];
  91. let page = self.pageAndPoint(&pagePoint, for: event, nearest: true)
  92. // CPDFAnnotation *annotation = [page annotationAtPoint:pagePoint];
  93. let annotation = page?.annotation(at: pagePoint)
  94. if let data = annotation, data is CPDFRedactAnnotation && (self.operationType == .redact || self.operationType == .redactWhite) {
  95. var item = menu?.insertItem(withTitle: KMLocalizedString("Delete", nil), action: #selector(deleteAnnotation), target: self, at: 0)
  96. item?.representedObject = annotation
  97. menu?.insertItem(.separator(), at: 1)
  98. item = menu?.insertItem(withTitle: KMLocalizedString("Make Current Properties Default", nil), action: #selector(setPropertiesDefault), target: self, at: 2)
  99. item?.representedObject = annotation
  100. _ = menu?.insertItem(withTitle: KMLocalizedString("Properties", nil), action: #selector(properties), target: self, at: 3)
  101. menu?.insertItem(.separator(), at: 4)
  102. _ = menu?.insertItem(withTitle: KMLocalizedString("Repeat Mark Across Pages", nil), action: #selector(repeatMark), target: self, at: 5)
  103. _ = menu?.insertItem(withTitle: KMLocalizedString("Apply Redactions", nil), action: #selector(applyRedact), target: self, at: 6)
  104. self.currentAnnotation = annotation as? CPDFRedactAnnotation
  105. }
  106. return menu
  107. }
  108. @objc func deleteAnnotation(_ sender: NSMenuItem?) {
  109. if let annotation = sender?.representedObject as? CPDFRedactAnnotation {
  110. self.remove(annotation)
  111. // removeAnnotation(annotation: annotation)
  112. }
  113. }
  114. func removeAnnotation(annotation: CPDFAnnotation) {
  115. let annos = NSMutableArray()
  116. annos.add(annotation)
  117. removeAccosAnnotations(annos)
  118. }
  119. @objc func setPropertiesDefault(_ sender: NSMenuItem?) {
  120. if let annotation = sender?.representedObject as? CPDFRedactAnnotation {
  121. KMPDFAnnotationRedactConfig.shared.redactOutlineColor = annotation.borderColor()
  122. KMPDFAnnotationRedactConfig.shared.redactFillColor = annotation.interiorColor()
  123. KMPDFAnnotationRedactConfig.shared.redactFontColor = annotation.fontColor()
  124. KMPDFAnnotationRedactConfig.shared.overlayText = annotation.overlayText().isEmpty == false
  125. KMPDFAnnotationRedactConfig.shared.fontSize = Int(annotation.font().pointSize)
  126. if annotation.alignment() == .left {
  127. KMPDFAnnotationRedactConfig.shared.textAlignment = 0
  128. } else if annotation.alignment() == .center {
  129. KMPDFAnnotationRedactConfig.shared.textAlignment = 1
  130. } else if annotation.alignment() == .right {
  131. KMPDFAnnotationRedactConfig.shared.textAlignment = 2
  132. }
  133. KMPDFAnnotationRedactConfig.shared.overlayTextString = annotation.overlayText()
  134. }
  135. }
  136. @objc func properties() {
  137. NotificationCenter.default.post(name: Self.showCurrentRedactAnnotationNotificationName, object: self)
  138. }
  139. @objc func repeatMark() {
  140. NotificationCenter.default.post(name: Self.redactAnnotationAcrossNotificationName, object: self)
  141. }
  142. @objc func applyRedact() {
  143. NotificationCenter.default.post(name: Self.redactAnnotationApplyNotificationName, object: self)
  144. }
  145. /*
  146. - (CGSize)getWidthFromText:(NSString *)text WithSize:(NSFont *)font AboutWidth:(CGFloat)width AndHeight:(CGFloat)height
  147. {
  148. if (!text) {
  149. return CGSizeMake(0, 0);
  150. }
  151. CGRect rect = [text boundingRectWithSize:CGSizeMake(width, height) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:font} context:nil];
  152. return rect.size;
  153. }
  154. */
  155. override func menuItemsEditing(at point: CGPoint, for page: CPDFPage!) -> [NSMenuItem]! {
  156. var menuItems = super.menuItemsEditing(at: point, for: page)
  157. if (menuItems == nil) {
  158. menuItems = []
  159. }
  160. if self.isSelectEditCharRange() || self.isSelecteditArea(with: point) {
  161. menuItems?.insert(.separator(), at: 0)
  162. menuItems?.insert(self.fontColorMenuItem(), at: 0)
  163. menuItems?.insert(self.fontSizeMenuItem(), at: 0)
  164. }
  165. if self.editingArea() != nil {
  166. if self.editingArea().isImageArea() {
  167. menuItems?.insert(.separator(), at: 0)
  168. // // [menuItems insertObject:[self imageCutMenuItem] atIndex:0];
  169. // // [menuItems insertObject:[self imagePasteMenuItem] atIndex:0];
  170. // [menuItems insertObject:[self imageRotateMenuItem] atIndex:0];
  171. menuItems?.insert(self.imageExportMenuItem(), at: 0)
  172. }
  173. }
  174. return menuItems
  175. }
  176. // MARK: - keyDown
  177. override func mouseMoved(with event: NSEvent) {
  178. self.window?.mouseMoved(with: event)
  179. super.mouseMoved(with: event)
  180. var continueAction = false
  181. if(self.operationType == .redact ||
  182. self.operationType == .redactWhite) {
  183. continueAction = true
  184. }
  185. if continueAction == false {
  186. return
  187. }
  188. var pagePoint = NSZeroPoint
  189. var page = self.pageAndPoint(&pagePoint, for: event, nearest: true)
  190. var fromView: NSView?
  191. let newpoint = self.convert(event.locationInWindow, from: fromView)
  192. let area = self.areaOfInterest(for: newpoint)
  193. if area.contains(.textArea) {
  194. NSCursor.iBeam.set()
  195. }else{
  196. NSCursor.arrow.set()
  197. }
  198. let newActiveAnnotation = page?.annotation(at: pagePoint)
  199. if newActiveAnnotation != nil && newActiveAnnotation is CPDFRedactAnnotation && self.mouseMoveAnnotation == newActiveAnnotation {
  200. (newActiveAnnotation as? CPDFRedactAnnotation)?.drawRedactionsAsRedacted = true
  201. self.setNeedsDisplayAnnotationViewFor(page)
  202. } else if self.mouseMoveAnnotation != nil && self.mouseMoveAnnotation is CPDFRedactAnnotation {
  203. (self.mouseMoveAnnotation as? CPDFRedactAnnotation)?.drawRedactionsAsRedacted = false
  204. self.setNeedsDisplayAnnotationViewFor(page)
  205. }
  206. self.mouseMoveAnnotation = newActiveAnnotation
  207. }
  208. override func mouseDown(with event: NSEvent) {
  209. var pagePoint = NSZeroPoint
  210. var continueAction = false
  211. if(self.operationType == .redact ||
  212. self.operationType == .redactWhite) {
  213. continueAction = true
  214. }
  215. if continueAction == false {
  216. return
  217. }
  218. var page = self.pageAndPoint(&pagePoint, for: event, nearest: true)
  219. let newActiveAnnotation = page?.annotation(at: pagePoint)
  220. var fromView: NSView?
  221. let newpoint = self.convert(event.locationInWindow, from: fromView)
  222. let area = self.areaOfInterest(for: newpoint)
  223. self.activeAnnotations.removeAllObjects() //预留
  224. if(newActiveAnnotation != nil) {
  225. if self.activeAnnotations.contains(newActiveAnnotation!) == false {
  226. self.activeAnnotations.add(newActiveAnnotation!)
  227. }
  228. self.setNeedsDisplayAnnotationViewFor(page)
  229. _ = self.doDragMouse(event: event)
  230. } else if area.contains(.textArea) {
  231. super.mouseDown(with: event)
  232. self.doMarkUp(event: event)
  233. self.currentSelection = nil
  234. } else {
  235. self.doRedact(event: event)
  236. }
  237. }
  238. func delete() {
  239. for anno in self.activeAnnotations {
  240. if anno is CPDFRedactAnnotation {
  241. self.remove(anno as? CPDFAnnotation)
  242. }
  243. }
  244. }
  245. func corpImageDoneWithEnter() {
  246. // if([self.editingArea isKindOfClass:[CPDFEditImageArea class]]) {
  247. // CPDFEditImageArea *editImageArea = (CPDFEditImageArea *)self.editingArea;
  248. // if(editImageArea.isCropMode) {
  249. // [self cropEditImageArea:editImageArea withBounds:editImageArea.cropRect];
  250. // [self exitCropWithEditImageArea:editImageArea];
  251. // }
  252. // }
  253. }
  254. // MARK: - Rendering
  255. func doDragMouse(event: NSEvent) -> Bool {
  256. var didDrag = false
  257. while (true) {
  258. if self.window?.nextEvent(matching: [.leftMouseUp, .leftMouseDragged])?.type == .leftMouseUp {
  259. break
  260. }
  261. didDrag = true
  262. }
  263. return didDrag
  264. }
  265. func doMarkUp(event: NSEvent) {
  266. let eventMask: NSEvent.EventTypeMask = [.leftMouseUp, .leftMouseDragged]
  267. var theEvent: NSEvent = event
  268. while (true) {
  269. theEvent = self.window!.nextEvent(matching: eventMask)!
  270. if theEvent.type == .leftMouseUp {
  271. if (self.currentSelection != nil) {
  272. let page = self.currentSelection.page
  273. let annotation = self.addRedactPDFSelection(self.currentSelection)
  274. annotation?.setModificationDate(Date())
  275. let userName = KMPreference.shared.author
  276. annotation?.setUserName(userName)
  277. annotation?.borderWidth = 10
  278. if self.operationType == .redact {
  279. annotation?.setBorderColor(KMPDFAnnotationRedactConfig.shared.redactOutlineColor)
  280. annotation?.setInteriorColor(KMPDFAnnotationRedactConfig.shared.redactFillColor)
  281. annotation?.setFontColor(KMPDFAnnotationRedactConfig.shared.redactFontColor)
  282. if KMPDFAnnotationRedactConfig.shared.overlayText {
  283. if KMPDFAnnotationRedactConfig.shared.textAlignment == 0 {
  284. annotation?.setAlignment(.left)
  285. } else if KMPDFAnnotationRedactConfig.shared.textAlignment == 1 {
  286. annotation?.setAlignment(.center)
  287. } else if KMPDFAnnotationRedactConfig.shared.textAlignment == 2 {
  288. annotation?.setAlignment(.right)
  289. }
  290. let font = NSFont(name: "Helvetica", size: KMPDFAnnotationRedactConfig.shared.fontSize.cgFloat)
  291. annotation?.setFont(font)
  292. annotation?.setOverlayText(KMPDFAnnotationRedactConfig.shared.overlayTextString)
  293. }
  294. } else if self.operationType == .redactWhite {
  295. annotation?.setBorderColor(NSColor.white)
  296. annotation?.setInteriorColor(NSColor.white)
  297. annotation?.setFontColor(NSColor.white)
  298. }
  299. self.addAnnotation(with: annotation, to: page)
  300. self.newAddAnnotation.append(annotation!)
  301. self.setNeedsDisplayFor(page)
  302. }
  303. break
  304. } else if theEvent.type == .leftMouseDragged {
  305. super.mouseDragged(with: theEvent)
  306. }
  307. }
  308. }
  309. func doRedact(event: NSEvent) {
  310. var point = NSZeroPoint
  311. let page = self.pageAndPoint(&point, for: event, nearest: true)
  312. let wasMouseCoalescingEnabled = NSEvent.isMouseCoalescingEnabled
  313. let window = self.window
  314. var bezierPath: NSBezierPath?
  315. var layer: CAShapeLayer?
  316. let boxBounds = page?.bounds ?? .zero
  317. let t = CGAffineTransformRotate(CGAffineTransformMakeScale(self.scaleFactor, self.scaleFactor), -Double.pi * 0.5 * (page!.rotation.cgFloat / 90.0))
  318. layer = CAShapeLayer()
  319. layer?.bounds = NSRectToCGRect(boxBounds)
  320. layer?.anchorPoint = .zero
  321. let posi = self.convert(boxBounds.origin, from: page)
  322. layer?.position = NSPointToCGPoint(posi)
  323. layer?.setAffineTransform(t)
  324. layer?.zPosition = 1.0
  325. layer?.masksToBounds = true
  326. if self.operationType == .redact {
  327. layer?.fillColor = KMPDFAnnotationRedactConfig.shared.redactFillColor?.cgColor
  328. // layer?.strokeColor = .black
  329. } else if self.operationType == .redactWhite {
  330. layer?.fillColor = .white
  331. layer?.strokeColor = .white
  332. }
  333. // layer?.strokeColor = CGColorGetConstantColor(kCGColorBlack)
  334. layer?.lineJoin = .round
  335. layer?.lineCap = .round
  336. var lastMouseEvent = event
  337. // SKRectEdges
  338. var resizeHandle: CRectEdges = [.minYEdgeMask, .maxXEdgeMask]
  339. var originalBounds = CGRectMake(point.x, point.y, 0, 0)
  340. self.layer?.addSublayer(layer!)
  341. var eventMask: NSEvent.EventTypeMask = [.leftMouseUp, .leftMouseDragged]
  342. var rect = CGRectZero
  343. var theEvent = event
  344. while (true) {
  345. theEvent = window!.nextEvent(matching: eventMask)!
  346. if theEvent.type == .leftMouseUp {
  347. if (rect.size.width < MIN_NOTE_SIZE || rect.size.height < MIN_NOTE_SIZE) {
  348. break
  349. }
  350. var quadrilateralPoints = NSMutableArray()
  351. let annotation = CPDFRedactAnnotation(document: self.document)
  352. var bounds = rect
  353. quadrilateralPoints.add(NSValue(point: CGPointMake(CGRectGetMinX(bounds), CGRectGetMaxY(bounds))))
  354. quadrilateralPoints.add(NSValue(point: CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))))
  355. quadrilateralPoints.add(NSValue(point: CGPointMake(CGRectGetMinX(bounds), CGRectGetMinY(bounds))))
  356. quadrilateralPoints.add(NSValue(point: CGPointMake(CGRectGetMaxX(bounds), CGRectGetMinY(bounds))))
  357. annotation?.setQuadrilateralPoints(quadrilateralPoints as? [Any] ?? [])
  358. annotation?.setModificationDate(Date())
  359. let userName = KMPreference.shared.author
  360. annotation?.setUserName(userName)
  361. // if ([annotation isKindOfClass:[CPDFRedactAnnotation class]]) {
  362. annotation?.borderWidth = 10
  363. if self.operationType == .redact {
  364. annotation?.setBorderColor(KMPDFAnnotationRedactConfig.shared.redactOutlineColor)
  365. annotation?.setInteriorColor(KMPDFAnnotationRedactConfig.shared.redactFillColor)
  366. annotation?.setFontColor(KMPDFAnnotationRedactConfig.shared.redactFontColor)
  367. if KMPDFAnnotationRedactConfig.shared.overlayText {
  368. if KMPDFAnnotationRedactConfig.shared.textAlignment == 0 {
  369. annotation?.setAlignment(.left)
  370. } else if KMPDFAnnotationRedactConfig.shared.textAlignment == 1 {
  371. annotation?.setAlignment(.center)
  372. } else if KMPDFAnnotationRedactConfig.shared.textAlignment == 2 {
  373. annotation?.setAlignment(.right)
  374. }
  375. let font = NSFont(name: "Helvetica", size: KMPDFAnnotationRedactConfig.shared.fontSize.cgFloat)
  376. annotation?.setFont(font)
  377. annotation?.setOverlayText(KMPDFAnnotationRedactConfig.shared.overlayTextString)
  378. }
  379. } else if self.operationType == .redactWhite {
  380. annotation?.setBorderColor(NSColor.white)
  381. annotation?.setInteriorColor(NSColor.white)
  382. annotation?.setFontColor(NSColor.white)
  383. }
  384. self.addAnnotation(with: annotation, to: page)
  385. self.newAddAnnotation.append(annotation!)
  386. break
  387. } else if theEvent.type == .leftMouseDragged {
  388. // rect = self.doResizeLink(event: lastMouseEvent, fromPoint: point, originalBounds: originalBounds, page: page!, resizeHandle: &resizeHandle)
  389. rect = self.doResizeLink(with: lastMouseEvent, from: point, originalBounds: originalBounds, page: page, resizeHandle: &resizeHandle)
  390. bezierPath = NSBezierPath(rect: rect)
  391. layer?.path = bezierPath?.kmCGPath()
  392. lastMouseEvent = theEvent
  393. }
  394. }
  395. layer?.removeFromSuperlayer()
  396. NSEvent.isMouseCoalescingEnabled = wasMouseCoalescingEnabled
  397. }
  398. func doResizeLink(event: NSEvent, fromPoint originalPagePoint: NSPoint, originalBounds: NSRect, page: CPDFPage, resizeHandle resizeHandlePtr: inout CRectEdges) -> NSRect {
  399. let currentPagePoint = self.convert(event.locationInView(self), to: page)
  400. var newBounds = originalBounds
  401. var pageBounds = page.bounds
  402. var relPoint = CPDFListViewSubstractPoints(currentPagePoint, originalPagePoint)
  403. var resizeHandle = resizeHandlePtr
  404. if (NSEqualSizes(originalBounds.size, NSZeroSize)) {
  405. var currentResizeHandle: CRectEdges = .minYEdgeMask
  406. if relPoint.x < 0.0 {
  407. currentResizeHandle = [.minXEdgeMask]
  408. } else {
  409. currentResizeHandle = [.maxXEdgeMask]
  410. }
  411. if relPoint.y <= 0.0 {
  412. currentResizeHandle.insert(.minYEdgeMask)
  413. } else {
  414. currentResizeHandle.insert(.maxYEdgeMask)
  415. }
  416. if (currentResizeHandle != resizeHandle) {
  417. resizeHandlePtr = currentResizeHandle
  418. resizeHandle = currentResizeHandle
  419. }
  420. }
  421. let minWidth = MIN_NOTE_SIZE
  422. let minHeight = MIN_NOTE_SIZE
  423. if resizeHandle.contains(.maxXEdgeMask) {
  424. newBounds.size.width += relPoint.x
  425. if (NSMaxX(newBounds) > NSMaxX(pageBounds)) {
  426. newBounds.size.width = NSMaxX(pageBounds) - NSMinX(newBounds)
  427. }
  428. if (NSWidth(newBounds) < minWidth) {
  429. newBounds.size.width = minWidth
  430. }
  431. } else if resizeHandle.contains(.minXEdgeMask) {
  432. newBounds.origin.x += relPoint.x
  433. newBounds.size.width -= relPoint.x
  434. if (NSMinX(newBounds) < NSMinX(pageBounds)) {
  435. newBounds.size.width = NSMaxX(newBounds) - NSMinX(pageBounds)
  436. newBounds.origin.x = NSMinX(pageBounds)
  437. }
  438. if (NSWidth(newBounds) < minWidth) {
  439. newBounds.origin.x = NSMaxX(newBounds) - minWidth
  440. newBounds.size.width = minWidth
  441. }
  442. }
  443. if resizeHandle.contains(.maxXEdgeMask) {
  444. newBounds.size.height += relPoint.y
  445. if (NSMaxY(newBounds) > NSMaxY(pageBounds)) {
  446. newBounds.size.height = NSMaxY(pageBounds) - NSMinY(newBounds)
  447. }
  448. if (NSHeight(newBounds) < minHeight) {
  449. newBounds.size.height = minHeight
  450. }
  451. } else if resizeHandle.contains(.minYEdgeMask) {
  452. newBounds.origin.y += relPoint.y
  453. newBounds.size.height -= relPoint.y
  454. if (NSMinY(newBounds) < NSMinY(pageBounds)) {
  455. newBounds.size.height = NSMaxY(newBounds) - NSMinY(pageBounds)
  456. newBounds.origin.y = NSMinY(pageBounds)
  457. }
  458. if (NSHeight(newBounds) < minHeight) {
  459. newBounds.origin.y = NSMaxY(newBounds) - minHeight
  460. newBounds.size.height = minHeight
  461. }
  462. }
  463. return newBounds
  464. }
  465. override func validate(_ menuItem: NSMenuItem!) -> Bool {
  466. guard let _doc = self.document, _doc.isLocked == false else {
  467. return false
  468. }
  469. let action = menuItem.action
  470. if (action == #selector(deleteAnnotation)) {
  471. return true
  472. } else if (action == #selector(setPropertiesDefault)) {
  473. return true
  474. } else if (action == #selector(properties)) {
  475. return true
  476. } else if (action == #selector(repeatMark)) {
  477. if(_doc.pageCount == 1) {
  478. return false
  479. }
  480. return true
  481. } else if (action == #selector(applyRedact)) {
  482. return true
  483. } else {
  484. return super.validate(menuItem)
  485. }
  486. }
  487. /*
  488. #pragma mark -
  489. - (void)drawPage:(CPDFPage *)page toContext:(CGContextRef)context
  490. {
  491. [self.activeAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
  492. if (annotation.page && [annotation.page isEqual:page]) {
  493. [annotation drawSelectionHighlightForView:self inContext:context];
  494. }
  495. }];
  496. }
  497. - (CPDFPage *)pageAndPoint:(NSPoint *)point forEvent:(NSEvent *)event nearest:(BOOL)nearest {
  498. NSPoint p = [event locationInView:self];
  499. CPDFPage *page = [self pageForPoint:p nearest:nearest];
  500. if (page && point)
  501. *point = [self convertPoint:p toPage:page];
  502. return page;
  503. }
  504. */
  505. }
  506. // MARK: - KMExtensions
  507. extension KMRedactPDFView {
  508. @objc dynamic func acrossAddAnnotations(_ pages: NSMutableArray) {
  509. if(pages.count == 0) {
  510. return
  511. }
  512. var anntations = NSMutableArray()
  513. for i in 0 ..< pages.count {
  514. // NSUInteger index = [[pages objectAtIndex:i] integerValue];
  515. guard let index = (pages.object(at: i) as? NSNumber)?.intValue else {
  516. continue
  517. }
  518. if(index - 1 < self.document.pageCount) {
  519. // CPDFPage *page = [[self.document pageAtIndex:index-1] retain];
  520. let page = self.document.page(at: UInt(index-1))
  521. let annotation = CPDFRedactAnnotation(document: self.document)
  522. if let anno = self.currentAnnotation {
  523. annotation?.setUserName(anno.userName())
  524. annotation?.setModificationDate(anno.modificationDate())
  525. annotation?.setQuadrilateralPoints(anno.quadrilateralPoints())
  526. annotation?.borderWidth = anno.borderWidth
  527. annotation?.setBorderColor(anno.borderColor())
  528. annotation?.setInteriorColor(anno.interiorColor())
  529. annotation?.setFont(anno.font())
  530. annotation?.setOverlayText(anno.overlayText())
  531. annotation?.setFontColor(anno.fontColor())
  532. annotation?.setAlignment(anno.alignment())
  533. let pageRect = page?.bounds ?? .zero
  534. let annotationRect = annotation?.bounds ?? .zero
  535. if (CGRectGetMaxX(annotationRect) > CGRectGetMaxX(pageRect) ||
  536. CGRectGetMinX(annotationRect) < CGRectGetMinX(pageRect) ||
  537. CGRectGetMinY(annotationRect) < CGRectGetMinY(pageRect) ||
  538. CGRectGetMaxY(annotationRect) > CGRectGetMaxY(pageRect) ||
  539. anno.page == page){
  540. continue
  541. }
  542. }
  543. page?.addAnnotation(annotation)
  544. anntations.add(annotation as Any)
  545. self.setNeedsDisplayAnnotationViewFor(page)
  546. }
  547. }
  548. (self.undoManager?.prepare(withInvocationTarget: self) as AnyObject).removeAccosAnnotations(anntations)
  549. }
  550. @objc dynamic func removeAccosAnnotations(_ annotations: NSMutableArray) {
  551. if(annotations.count == 0){
  552. return
  553. }
  554. var pageIndexs = NSMutableArray()
  555. for i in 0 ..< annotations.count {
  556. guard let annotation = annotations.object(at: i) as? CPDFRedactAnnotation else {
  557. continue
  558. }
  559. let page = annotation.page
  560. let index = self.document.index(for: page)
  561. page?.removeAnnotation(annotation)
  562. pageIndexs.add(NSNumber(integerLiteral: Int(index)+1))
  563. self.setNeedsDisplayAnnotationViewFor(page)
  564. }
  565. (self.undoManager?.prepare(withInvocationTarget: self) as AnyObject).acrossAddAnnotations(pageIndexs)
  566. }
  567. /*
  568. - (CGFloat)unitWidthOnPage:(CPDFPage *)page
  569. {
  570. return NSWidth([self convertRect:NSMakeRect(0.0, 0.0, 1.0, 1.0) toPage:page]);
  571. }
  572. - (NSRect)integralRect:(NSRect)rect onPage:(CPDFPage *)page
  573. {
  574. return [self convertRect:[self convertRect:rect fromPage:page] toPage:page];
  575. }
  576. - (CPDFAnnotation *)addRedactPDFSelection:(CPDFSelection *)currentSelection
  577. {
  578. NSMutableArray *quadrilateralPoints = [NSMutableArray array];
  579. CPDFRedactAnnotation *annotation = [[CPDFRedactAnnotation alloc] initWithDocument:self.document];
  580. for (CPDFSelection *selection in currentSelection.selectionsByLine) {
  581. CGRect bounds = selection.bounds;
  582. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMinX(bounds), CGRectGetMaxY(bounds))]];
  583. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))]];
  584. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMinX(bounds), CGRectGetMinY(bounds))]];
  585. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMinY(bounds))]];
  586. }
  587. NSString *userName = [[NSUserDefaults standardUserDefaults] stringForKey:@"SKUserName"];
  588. [annotation setUserName:userName ? : NSFullUserName()];
  589. [annotation setModificationDate:[NSDate date]];
  590. [annotation setQuadrilateralPoints:quadrilateralPoints];
  591. [annotation setBorderWidth:10];
  592. [(CPDFRedactAnnotation *)annotation setBorderColor:[KMPDFAnnotationRedactConfig sharedInstance].redactOutlineColor];
  593. [(CPDFRedactAnnotation *)annotation setInteriorColor:[KMPDFAnnotationRedactConfig sharedInstance].redactFillColor];
  594. [(CPDFRedactAnnotation *)annotation setFontColor:[KMPDFAnnotationRedactConfig sharedInstance].redactFontColor];
  595. if([KMPDFAnnotationRedactConfig sharedInstance].overlayText) {
  596. [(CPDFRedactAnnotation *)annotation setAlignment:[KMPDFAnnotationRedactConfig sharedInstance].textAlignment];
  597. NSFont* font = [NSFont fontWithName:@"Helvetica" size:[KMPDFAnnotationRedactConfig sharedInstance].fontSize];
  598. [(CPDFRedactAnnotation *)annotation setFont:font];
  599. [(CPDFRedactAnnotation *)annotation setOverlayText:[KMPDFAnnotationRedactConfig sharedInstance].overlayTextString];
  600. }
  601. return annotation;
  602. }
  603. - (void)deleteAnnotation:(NSMenuItem *)item {
  604. CPDFRedactAnnotation *annotation = item.representedObject;
  605. if(annotation && [annotation isKindOfClass:[CPDFRedactAnnotation class]]) {
  606. [annotation retain];
  607. CPDFPage *page = [[annotation page] retain];
  608. [self setNeedsDisplayAnnotationViewForPage:page];
  609. [self removeAnnotation:annotation];
  610. [annotation release];
  611. [page release];
  612. }
  613. }
  614. - (void)addAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page
  615. {
  616. [[[self undoManager] prepareWithInvocationTarget:self] removeAnnotation:annotation];
  617. [page addAnnotation:annotation];
  618. if([self.newAddAnnotation containsObject:annotation]) {
  619. [self.newAddAnnotation removeObject:annotation];
  620. } else {
  621. [self.newAddAnnotation addObject:annotation];
  622. }
  623. [self setNeedsDisplayAnnotationViewForPage:page];
  624. }
  625. - (void)removeAnnotation:(CPDFAnnotation *)annotation
  626. {
  627. CPDFAnnotation *wasAnnotation = [annotation retain];
  628. CPDFPage *page = [[wasAnnotation page] retain];
  629. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  630. if([self.newAddAnnotation containsObject:annotation]) {
  631. [self.newAddAnnotation removeObject:annotation];
  632. } else {
  633. [self.newAddAnnotation addObject:annotation];
  634. }
  635. if([self.activeAnnotations containsObject:annotation]) {
  636. [self.activeAnnotations removeObject:annotation];
  637. }
  638. [self setNeedsDisplayAnnotationViewForPage:page];
  639. [page removeAnnotation:wasAnnotation];
  640. [wasAnnotation release];
  641. [page release];
  642. }
  643. */
  644. }
  645. // MARK: - Event
  646. extension KMRedactPDFView {
  647. func fontColorMenuItem() -> NSMenuItem {
  648. let fontColorItem = NSMenuItem(title: KMLocalizedString("Text Color", nil), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  649. fontColorItem.target = self
  650. return fontColorItem
  651. }
  652. @objc func menuItemEditingClick_FontColor(_ sender: NSMenuItem?) {
  653. let color = self.editingSelectionFontColor()
  654. let cp = NSColorPanel.shared
  655. cp.orderFront(nil)
  656. cp.setTarget(self)
  657. cp.color = color!
  658. cp.showsAlpha = false
  659. cp.setAction(#selector(fontColorChangeAction))
  660. }
  661. @objc func fontColorChangeAction(_ sender: AnyObject?) {
  662. self.setEditingSelectionFontColor(NSColorPanel.shared.color)
  663. guard let callback = self.eventColorChanged else {
  664. return
  665. }
  666. callback(NSColorPanel.shared.color)
  667. }
  668. func fontSizeMenuItem() -> NSMenuItem {
  669. let size = self.editingSelectionFontSize()
  670. let fontSizes = self.fontSizes()
  671. let submenu = NSMenu()
  672. for (i,fontSize) in fontSizes.enumerated() {
  673. let fs: CGFloat = fontSize.stringToCGFloat()
  674. let item = NSMenuItem(title: String(format: "%d pt", fs), action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  675. item.target = self
  676. item.tag = i
  677. submenu.addItem(item)
  678. if (fabsf(Float(fs-size)) < 0.1) {
  679. item.state = .on
  680. }
  681. }
  682. let fontSizeItem = NSMenuItem(title: KMLocalizedString("Font Size", nil), action: nil, keyEquivalent: "")
  683. fontSizeItem.submenu = submenu
  684. return fontSizeItem
  685. }
  686. func fontSizes() -> [String] {
  687. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  688. }
  689. @objc func menuItemEditingClick_FontSize(_ item: NSMenuItem) {
  690. let fontSize = self.fontSizes()[item.tag].stringToCGFloat()
  691. self.setEditingSelectionFontSize(fontSize)
  692. guard let callback = self.eventFontChanged else {
  693. return
  694. }
  695. callback()
  696. }
  697. func imageExportMenuItem() -> NSMenuItem {
  698. let submenu = NSMenu()
  699. for (i, title) in self.titles().enumerated() {
  700. let item = NSMenuItem(title: title, action: #selector(menuItemEditingClick_export), keyEquivalent: "")
  701. item.tag = i
  702. submenu.addItem(item)
  703. }
  704. let exportmentItem = NSMenuItem(title: KMLocalizedString("Export", nil), action: nil, keyEquivalent: "")
  705. exportmentItem.submenu = submenu
  706. return exportmentItem
  707. }
  708. func titles() -> [String] {
  709. return ["PNG", "JPG", "PDF"]
  710. }
  711. @objc func menuItemEditingClick_export(_ item: NSMenuItem) {
  712. let idx = item.tag
  713. guard let callback = self.exportBtnTaped else {
  714. return
  715. }
  716. callback(idx)
  717. }
  718. func imageRotateMenuItem() -> NSMenuItem {
  719. let item = NSMenuItem(title: KMLocalizedString("Rotate", nil), action: #selector(menuItemEditingClick_RotateImage), keyEquivalent: "")
  720. item.target = self
  721. return item
  722. }
  723. @objc func menuItemEditingClick_RotateImage(_ iten: NSMenuItem) {
  724. self.rotate(with: self.editingArea() as? CPDFEditImageArea, rotate: 90)
  725. }
  726. /*
  727. - (NSMenuItem *)alightMenuItem {
  728. NSMenu *submenu = [[[NSMenu alloc] init] autorelease];
  729. NSArray *titles = @[NSLocalizedString(@"Left Alignment", nil),
  730. NSLocalizedString(@"Right Alignment", nil),
  731. NSLocalizedString(@"Center", nil),
  732. NSLocalizedString(@"Justified Alignment", nil),];
  733. NSTextAlignment alignment = [self editingSelectionAlignment];
  734. for (NSUInteger i=0; i<titles.count; i++) {
  735. NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:[titles objectAtIndex:i]
  736. action:@selector(menuItemEditingClick_alignment:)
  737. keyEquivalent:@""] autorelease];
  738. if (alignment == i) {
  739. item.state = NSControlStateValueOn;
  740. }
  741. item.tag = i;
  742. [submenu addItem:item];
  743. }
  744. NSMenuItem *alignmentItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Text Alignment", nil) action:nil keyEquivalent:@""];
  745. alignmentItem.submenu = submenu;
  746. return alignmentItem;
  747. }
  748. - (void)menuItemEditingClick_alignment:(NSMenuItem *)item {
  749. [self setCurrentSelectionAlignment:(NSTextAlignment)item.tag];
  750. }
  751. - (NSMenuItem *)imageCutMenuItem {
  752. NSMenuItem *fontColorItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Cut", nil)
  753. action:@selector(menuItemEditingClick_CutImage:)
  754. keyEquivalent:@""] autorelease];
  755. fontColorItem.target = self;
  756. return fontColorItem;
  757. }
  758. - (NSMenuItem *)imagePasteMenuItem {
  759. NSMenuItem *fontColorItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Paste", nil)
  760. action:@selector(menuItemEditingClick_PasteImage:)
  761. keyEquivalent:@""] autorelease];
  762. fontColorItem.target = self;
  763. return fontColorItem;
  764. }
  765. - (void)menuItemEditingClick_CutImage:(NSMenuItem *)item {
  766. }
  767. - (void)menuItemEditingClick_PasteImage:(NSMenuItem *)item {
  768. }
  769. */
  770. }