KMRedactPDFView.swift 34 KB

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