KMRedactPDFView.swift 35 KB

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