KMRedactPDFView.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  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. var 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.fontSize())
  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. let pageRect = page?.bounds ?? .zero
  480. let annotationRect = annotation?.bounds ?? .zero
  481. if (CGRectGetMaxX(annotationRect) > CGRectGetMaxX(pageRect) ||
  482. CGRectGetMinX(annotationRect) < CGRectGetMinX(pageRect) ||
  483. CGRectGetMinY(annotationRect) < CGRectGetMinY(pageRect) ||
  484. CGRectGetMaxY(annotationRect) > CGRectGetMaxY(pageRect) ||
  485. anno.page == page){
  486. continue
  487. }
  488. }
  489. page?.addAnnotation(annotation)
  490. anntations.add(annotation as Any)
  491. self.setNeedsDisplayAnnotationViewFor(page)
  492. }
  493. }
  494. (self.undoManager?.prepare(withInvocationTarget: self) as AnyObject).removeAccosAnnotations(anntations)
  495. }
  496. @objc dynamic func removeAccosAnnotations(_ annotations: NSMutableArray) {
  497. if(annotations.count == 0){
  498. return
  499. }
  500. var pageIndexs = NSMutableArray()
  501. for i in 0 ..< annotations.count {
  502. guard let annotation = annotations.object(at: i) as? CPDFRedactAnnotation else {
  503. continue
  504. }
  505. let page = annotation.page
  506. let index = self.document.index(for: page)
  507. page?.removeAnnotation(annotation)
  508. pageIndexs.add(NSNumber(integerLiteral: Int(index)+1))
  509. self.setNeedsDisplayAnnotationViewFor(page)
  510. }
  511. (self.undoManager?.prepare(withInvocationTarget: self) as AnyObject).acrossAddAnnotations(pageIndexs)
  512. }
  513. /*
  514. - (CGFloat)unitWidthOnPage:(CPDFPage *)page
  515. {
  516. return NSWidth([self convertRect:NSMakeRect(0.0, 0.0, 1.0, 1.0) toPage:page]);
  517. }
  518. - (NSRect)integralRect:(NSRect)rect onPage:(CPDFPage *)page
  519. {
  520. return [self convertRect:[self convertRect:rect fromPage:page] toPage:page];
  521. }
  522. - (CPDFAnnotation *)addRedactPDFSelection:(CPDFSelection *)currentSelection
  523. {
  524. NSMutableArray *quadrilateralPoints = [NSMutableArray array];
  525. CPDFRedactAnnotation *annotation = [[CPDFRedactAnnotation alloc] initWithDocument:self.document];
  526. for (CPDFSelection *selection in currentSelection.selectionsByLine) {
  527. CGRect bounds = selection.bounds;
  528. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMinX(bounds), CGRectGetMaxY(bounds))]];
  529. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))]];
  530. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMinX(bounds), CGRectGetMinY(bounds))]];
  531. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMinY(bounds))]];
  532. }
  533. NSString *userName = [[NSUserDefaults standardUserDefaults] stringForKey:@"SKUserName"];
  534. [annotation setUserName:userName ? : NSFullUserName()];
  535. [annotation setModificationDate:[NSDate date]];
  536. [annotation setQuadrilateralPoints:quadrilateralPoints];
  537. [annotation setBorderWidth:10];
  538. [(CPDFRedactAnnotation *)annotation setBorderColor:[KMPDFAnnotationRedactConfig sharedInstance].redactOutlineColor];
  539. [(CPDFRedactAnnotation *)annotation setInteriorColor:[KMPDFAnnotationRedactConfig sharedInstance].redactFillColor];
  540. [(CPDFRedactAnnotation *)annotation setFontColor:[KMPDFAnnotationRedactConfig sharedInstance].redactFontColor];
  541. if([KMPDFAnnotationRedactConfig sharedInstance].overlayText) {
  542. [(CPDFRedactAnnotation *)annotation setAlignment:[KMPDFAnnotationRedactConfig sharedInstance].textAlignment];
  543. NSFont* font = [NSFont fontWithName:@"Helvetica" size:[KMPDFAnnotationRedactConfig sharedInstance].fontSize];
  544. [(CPDFRedactAnnotation *)annotation setFont:font];
  545. [(CPDFRedactAnnotation *)annotation setOverlayText:[KMPDFAnnotationRedactConfig sharedInstance].overlayTextString];
  546. }
  547. return annotation;
  548. }
  549. - (void)deleteAnnotation:(NSMenuItem *)item {
  550. CPDFRedactAnnotation *annotation = item.representedObject;
  551. if(annotation && [annotation isKindOfClass:[CPDFRedactAnnotation class]]) {
  552. [annotation retain];
  553. CPDFPage *page = [[annotation page] retain];
  554. [self setNeedsDisplayAnnotationViewForPage:page];
  555. [self removeAnnotation:annotation];
  556. [annotation release];
  557. [page release];
  558. }
  559. }
  560. - (void)addAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page
  561. {
  562. [[[self undoManager] prepareWithInvocationTarget:self] removeAnnotation:annotation];
  563. [page addAnnotation:annotation];
  564. if([self.newAddAnnotation containsObject:annotation]) {
  565. [self.newAddAnnotation removeObject:annotation];
  566. } else {
  567. [self.newAddAnnotation addObject:annotation];
  568. }
  569. [self setNeedsDisplayAnnotationViewForPage:page];
  570. }
  571. - (void)removeAnnotation:(CPDFAnnotation *)annotation
  572. {
  573. CPDFAnnotation *wasAnnotation = [annotation retain];
  574. CPDFPage *page = [[wasAnnotation page] retain];
  575. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  576. if([self.newAddAnnotation containsObject:annotation]) {
  577. [self.newAddAnnotation removeObject:annotation];
  578. } else {
  579. [self.newAddAnnotation addObject:annotation];
  580. }
  581. if([self.activeAnnotations containsObject:annotation]) {
  582. [self.activeAnnotations removeObject:annotation];
  583. }
  584. [self setNeedsDisplayAnnotationViewForPage:page];
  585. [page removeAnnotation:wasAnnotation];
  586. [wasAnnotation release];
  587. [page release];
  588. }
  589. */
  590. }
  591. // MARK: - Event
  592. extension KMRedactPDFView {
  593. func fontColorMenuItem() -> NSMenuItem {
  594. let fontColorItem = NSMenuItem(title: KMLocalizedString("Text Color", nil), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  595. fontColorItem.target = self
  596. return fontColorItem
  597. }
  598. @objc func menuItemEditingClick_FontColor(_ sender: NSMenuItem?) {
  599. let color = self.editingSelectionFontColor()
  600. let cp = NSColorPanel.shared
  601. cp.orderFront(nil)
  602. cp.setTarget(self)
  603. cp.color = color!
  604. cp.showsAlpha = false
  605. cp.setAction(#selector(fontColorChangeAction))
  606. }
  607. @objc func fontColorChangeAction(_ sender: AnyObject?) {
  608. self.setEditingSelectionFontColor(NSColorPanel.shared.color)
  609. guard let callback = self.eventColorChanged else {
  610. return
  611. }
  612. callback(NSColorPanel.shared.color)
  613. }
  614. func fontSizeMenuItem() -> NSMenuItem {
  615. let size = self.editingSelectionFontSize()
  616. let fontSizes = self.fontSizes()
  617. let submenu = NSMenu()
  618. for (i,fontSize) in fontSizes.enumerated() {
  619. let fs: CGFloat = fontSize.stringToCGFloat()
  620. let item = NSMenuItem(title: String(format: "%d pt", fs), action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  621. item.target = self
  622. item.tag = i
  623. submenu.addItem(item)
  624. if (fabsf(Float(fs-size)) < 0.1) {
  625. item.state = .on
  626. }
  627. }
  628. let fontSizeItem = NSMenuItem(title: KMLocalizedString("Font Size", nil), action: nil, keyEquivalent: "")
  629. fontSizeItem.submenu = submenu
  630. return fontSizeItem
  631. }
  632. func fontSizes() -> [String] {
  633. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  634. }
  635. @objc func menuItemEditingClick_FontSize(_ item: NSMenuItem) {
  636. let fontSize = self.fontSizes()[item.tag].stringToCGFloat()
  637. self.setEditingSelectionFontSize(fontSize)
  638. guard let callback = self.eventFontChanged else {
  639. return
  640. }
  641. callback()
  642. }
  643. func imageExportMenuItem() -> NSMenuItem {
  644. let submenu = NSMenu()
  645. for (i, title) in self.titles().enumerated() {
  646. let item = NSMenuItem(title: title, action: #selector(menuItemEditingClick_export), keyEquivalent: "")
  647. item.tag = i
  648. submenu.addItem(item)
  649. }
  650. let exportmentItem = NSMenuItem(title: KMLocalizedString("Export", nil), action: nil, keyEquivalent: "")
  651. exportmentItem.submenu = submenu
  652. return exportmentItem
  653. }
  654. func titles() -> [String] {
  655. return ["PNG", "JPG", "PDF"]
  656. }
  657. @objc func menuItemEditingClick_export(_ item: NSMenuItem) {
  658. let idx = item.tag
  659. guard let callback = self.exportBtnTaped else {
  660. return
  661. }
  662. callback(idx)
  663. }
  664. func imageRotateMenuItem() -> NSMenuItem {
  665. let item = NSMenuItem(title: KMLocalizedString("Rotate", nil), action: #selector(menuItemEditingClick_RotateImage), keyEquivalent: "")
  666. item.target = self
  667. return item
  668. }
  669. @objc func menuItemEditingClick_RotateImage(_ iten: NSMenuItem) {
  670. self.rotate(with: self.editingArea() as? CPDFEditImageArea, rotate: 90)
  671. }
  672. /*
  673. - (NSMenuItem *)alightMenuItem {
  674. NSMenu *submenu = [[[NSMenu alloc] init] autorelease];
  675. NSArray *titles = @[NSLocalizedString(@"Left Alignment", nil),
  676. NSLocalizedString(@"Right Alignment", nil),
  677. NSLocalizedString(@"Center", nil),
  678. NSLocalizedString(@"Justified Alignment", nil),];
  679. NSTextAlignment alignment = [self editingSelectionAlignment];
  680. for (NSUInteger i=0; i<titles.count; i++) {
  681. NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:[titles objectAtIndex:i]
  682. action:@selector(menuItemEditingClick_alignment:)
  683. keyEquivalent:@""] autorelease];
  684. if (alignment == i) {
  685. item.state = NSControlStateValueOn;
  686. }
  687. item.tag = i;
  688. [submenu addItem:item];
  689. }
  690. NSMenuItem *alignmentItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Text Alignment", nil) action:nil keyEquivalent:@""];
  691. alignmentItem.submenu = submenu;
  692. return alignmentItem;
  693. }
  694. - (void)menuItemEditingClick_alignment:(NSMenuItem *)item {
  695. [self setCurrentSelectionAlignment:(NSTextAlignment)item.tag];
  696. }
  697. - (NSMenuItem *)imageCutMenuItem {
  698. NSMenuItem *fontColorItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Cut", nil)
  699. action:@selector(menuItemEditingClick_CutImage:)
  700. keyEquivalent:@""] autorelease];
  701. fontColorItem.target = self;
  702. return fontColorItem;
  703. }
  704. - (NSMenuItem *)imagePasteMenuItem {
  705. NSMenuItem *fontColorItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Paste", nil)
  706. action:@selector(menuItemEditingClick_PasteImage:)
  707. keyEquivalent:@""] autorelease];
  708. fontColorItem.target = self;
  709. return fontColorItem;
  710. }
  711. - (void)menuItemEditingClick_CutImage:(NSMenuItem *)item {
  712. }
  713. - (void)menuItemEditingClick_PasteImage:(NSMenuItem *)item {
  714. }
  715. */
  716. }