KMRedactPDFView.swift 35 KB

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