KMRedactPDFView.swift 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. //
  2. // KMRedactPDFView.swift
  3. // PDF Master
  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 ?? NSFullUserName())
  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. /*
  405. #pragma mark -
  406. - (void)drawPage:(CPDFPage *)page toContext:(CGContextRef)context
  407. {
  408. [self.activeAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
  409. if (annotation.page && [annotation.page isEqual:page]) {
  410. [annotation drawSelectionHighlightForView:self inContext:context];
  411. }
  412. }];
  413. }
  414. - (CPDFPage *)pageAndPoint:(NSPoint *)point forEvent:(NSEvent *)event nearest:(BOOL)nearest {
  415. NSPoint p = [event locationInView:self];
  416. CPDFPage *page = [self pageForPoint:p nearest:nearest];
  417. if (page && point)
  418. *point = [self convertPoint:p toPage:page];
  419. return page;
  420. }
  421. */
  422. }
  423. // MARK: - NSMenuItemValidation
  424. extension KMRedactPDFView: NSMenuItemValidation {
  425. override func validate(_ menuItem: NSMenuItem!) -> Bool {
  426. guard let _doc = self.document, _doc.isLocked == false else {
  427. return false
  428. }
  429. let action = menuItem.action
  430. if (action == #selector(deleteAnnotation)) {
  431. return true
  432. } else if (action == #selector(setPropertiesDefault)) {
  433. return true
  434. } else if (action == #selector(properties)) {
  435. return true
  436. } else if (action == #selector(repeatMark)) {
  437. if(_doc.pageCount == 1) {
  438. return false
  439. }
  440. return true
  441. } else if (action == #selector(applyRedact)) {
  442. return true
  443. } else {
  444. return super.validate(menuItem)
  445. }
  446. }
  447. }
  448. // MARK: - KMExtensions
  449. extension KMRedactPDFView {
  450. @objc dynamic func acrossAddAnnotations(_ pages: NSMutableArray) {
  451. if(pages.count == 0) {
  452. return
  453. }
  454. var anntations = NSMutableArray()
  455. for i in 0 ..< pages.count {
  456. // NSUInteger index = [[pages objectAtIndex:i] integerValue];
  457. guard let index = (pages.object(at: i) as? NSNumber)?.intValue else {
  458. continue
  459. }
  460. if(index - 1 < self.document.pageCount) {
  461. // CPDFPage *page = [[self.document pageAtIndex:index-1] retain];
  462. let page = self.document.page(at: UInt(index-1))
  463. let annotation = CPDFRedactAnnotation(document: self.document)
  464. if let anno = self.currentAnnotation {
  465. annotation?.setUserName(anno.userName())
  466. annotation?.setModificationDate(anno.modificationDate())
  467. annotation?.setQuadrilateralPoints(anno.quadrilateralPoints())
  468. annotation?.borderWidth = anno.borderWidth
  469. annotation?.setBorderColor(anno.borderColor())
  470. annotation?.setInteriorColor(anno.interiorColor())
  471. annotation?.setFont(anno.font())
  472. annotation?.setOverlayText(anno.overlayText())
  473. annotation?.setFontColor(anno.fontColor())
  474. let pageRect = page?.bounds ?? .zero
  475. let annotationRect = annotation?.bounds ?? .zero
  476. if (CGRectGetMaxX(annotationRect) > CGRectGetMaxX(pageRect) ||
  477. CGRectGetMinX(annotationRect) < CGRectGetMinX(pageRect) ||
  478. CGRectGetMinY(annotationRect) < CGRectGetMinY(pageRect) ||
  479. CGRectGetMaxY(annotationRect) > CGRectGetMaxY(pageRect) ||
  480. anno.page == page){
  481. continue
  482. }
  483. }
  484. page?.addAnnotation(annotation)
  485. anntations.add(annotation)
  486. self.setNeedsDisplayAnnotationViewFor(page)
  487. }
  488. }
  489. (self.undoManager?.prepare(withInvocationTarget: self) as AnyObject).removeAccosAnnotations(anntations)
  490. }
  491. @objc dynamic func removeAccosAnnotations(_ annotations: NSMutableArray) {
  492. if(annotations.count == 0){
  493. return
  494. }
  495. var pageIndexs = NSMutableArray()
  496. for i in 0 ..< annotations.count {
  497. guard let annotation = annotations.object(at: i) as? CPDFRedactAnnotation else {
  498. continue
  499. }
  500. let page = annotation.page
  501. let index = self.document.index(for: page)
  502. page?.removeAnnotation(annotation)
  503. pageIndexs.add(NSNumber(integerLiteral: Int(index)+1))
  504. self.setNeedsDisplayAnnotationViewFor(page)
  505. }
  506. (self.undoManager?.prepare(withInvocationTarget: self) as AnyObject).acrossAddAnnotations(pageIndexs)
  507. }
  508. /*
  509. - (CGFloat)unitWidthOnPage:(CPDFPage *)page
  510. {
  511. return NSWidth([self convertRect:NSMakeRect(0.0, 0.0, 1.0, 1.0) toPage:page]);
  512. }
  513. - (NSRect)integralRect:(NSRect)rect onPage:(CPDFPage *)page
  514. {
  515. return [self convertRect:[self convertRect:rect fromPage:page] toPage:page];
  516. }
  517. - (CPDFAnnotation *)addRedactPDFSelection:(CPDFSelection *)currentSelection
  518. {
  519. NSMutableArray *quadrilateralPoints = [NSMutableArray array];
  520. CPDFRedactAnnotation *annotation = [[CPDFRedactAnnotation alloc] initWithDocument:self.document];
  521. for (CPDFSelection *selection in currentSelection.selectionsByLine) {
  522. CGRect bounds = selection.bounds;
  523. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMinX(bounds), CGRectGetMaxY(bounds))]];
  524. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))]];
  525. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMinX(bounds), CGRectGetMinY(bounds))]];
  526. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMinY(bounds))]];
  527. }
  528. NSString *userName = [[NSUserDefaults standardUserDefaults] stringForKey:@"SKUserName"];
  529. [annotation setUserName:userName ? : NSFullUserName()];
  530. [annotation setModificationDate:[NSDate date]];
  531. [annotation setQuadrilateralPoints:quadrilateralPoints];
  532. [annotation setBorderWidth:10];
  533. [(CPDFRedactAnnotation *)annotation setBorderColor:[KMPDFAnnotationRedactConfig sharedInstance].redactOutlineColor];
  534. [(CPDFRedactAnnotation *)annotation setInteriorColor:[KMPDFAnnotationRedactConfig sharedInstance].redactFillColor];
  535. [(CPDFRedactAnnotation *)annotation setFontColor:[KMPDFAnnotationRedactConfig sharedInstance].redactFontColor];
  536. if([KMPDFAnnotationRedactConfig sharedInstance].overlayText) {
  537. [(CPDFRedactAnnotation *)annotation setAlignment:[KMPDFAnnotationRedactConfig sharedInstance].textAlignment];
  538. NSFont* font = [NSFont fontWithName:@"Helvetica" size:[KMPDFAnnotationRedactConfig sharedInstance].fontSize];
  539. [(CPDFRedactAnnotation *)annotation setFont:font];
  540. [(CPDFRedactAnnotation *)annotation setOverlayText:[KMPDFAnnotationRedactConfig sharedInstance].overlayTextString];
  541. }
  542. return annotation;
  543. }
  544. - (void)deleteAnnotation:(NSMenuItem *)item {
  545. CPDFRedactAnnotation *annotation = item.representedObject;
  546. if(annotation && [annotation isKindOfClass:[CPDFRedactAnnotation class]]) {
  547. [annotation retain];
  548. CPDFPage *page = [[annotation page] retain];
  549. [self setNeedsDisplayAnnotationViewForPage:page];
  550. [self removeAnnotation:annotation];
  551. [annotation release];
  552. [page release];
  553. }
  554. }
  555. - (void)addAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page
  556. {
  557. [[[self undoManager] prepareWithInvocationTarget:self] removeAnnotation:annotation];
  558. [page addAnnotation:annotation];
  559. if([self.newAddAnnotation containsObject:annotation]) {
  560. [self.newAddAnnotation removeObject:annotation];
  561. } else {
  562. [self.newAddAnnotation addObject:annotation];
  563. }
  564. [self setNeedsDisplayAnnotationViewForPage:page];
  565. }
  566. - (void)removeAnnotation:(CPDFAnnotation *)annotation
  567. {
  568. CPDFAnnotation *wasAnnotation = [annotation retain];
  569. CPDFPage *page = [[wasAnnotation page] retain];
  570. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  571. if([self.newAddAnnotation containsObject:annotation]) {
  572. [self.newAddAnnotation removeObject:annotation];
  573. } else {
  574. [self.newAddAnnotation addObject:annotation];
  575. }
  576. if([self.activeAnnotations containsObject:annotation]) {
  577. [self.activeAnnotations removeObject:annotation];
  578. }
  579. [self setNeedsDisplayAnnotationViewForPage:page];
  580. [page removeAnnotation:wasAnnotation];
  581. [wasAnnotation release];
  582. [page release];
  583. }
  584. */
  585. }
  586. // MARK: - Event
  587. extension KMRedactPDFView {
  588. func fontColorMenuItem() -> NSMenuItem {
  589. let fontColorItem = NSMenuItem(title: KMLocalizedString("Text Color", nil), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  590. fontColorItem.target = self
  591. return fontColorItem
  592. }
  593. @objc func menuItemEditingClick_FontColor(_ sender: NSMenuItem?) {
  594. let color = self.editingSelectionFontColor()
  595. let cp = NSColorPanel.shared
  596. cp.orderFront(nil)
  597. cp.setTarget(self)
  598. cp.color = color!
  599. cp.showsAlpha = false
  600. cp.setAction(#selector(fontColorChangeAction))
  601. }
  602. @objc func fontColorChangeAction(_ sender: AnyObject?) {
  603. self.setEditingSelectionFontColor(NSColorPanel.shared.color)
  604. guard let callback = self.eventColorChanged else {
  605. return
  606. }
  607. callback(NSColorPanel.shared.color)
  608. }
  609. func fontSizeMenuItem() -> NSMenuItem {
  610. let size = self.editingSelectionFontSize()
  611. let fontSizes = self.fontSizes()
  612. let submenu = NSMenu()
  613. for (i,fontSize) in fontSizes.enumerated() {
  614. let fs: CGFloat = fontSize.stringToCGFloat()
  615. let item = NSMenuItem(title: String(format: "%d pt", fs), action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  616. item.target = self
  617. item.tag = i
  618. submenu.addItem(item)
  619. if (fabsf(Float(fs-size)) < 0.1) {
  620. item.state = .on
  621. }
  622. }
  623. let fontSizeItem = NSMenuItem(title: KMLocalizedString("Font Size", nil), action: nil, keyEquivalent: "")
  624. fontSizeItem.submenu = submenu
  625. return fontSizeItem
  626. }
  627. func fontSizes() -> [String] {
  628. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  629. }
  630. @objc func menuItemEditingClick_FontSize(_ item: NSMenuItem) {
  631. let fontSize = self.fontSizes()[item.tag].stringToCGFloat()
  632. self.setEditingSelectionFontSize(fontSize)
  633. guard let callback = self.eventFontChanged else {
  634. return
  635. }
  636. callback()
  637. }
  638. func imageExportMenuItem() -> NSMenuItem {
  639. let submenu = NSMenu()
  640. for (i, title) in self.titles().enumerated() {
  641. let item = NSMenuItem(title: title, action: #selector(menuItemEditingClick_export), keyEquivalent: "")
  642. item.tag = i
  643. submenu.addItem(item)
  644. }
  645. let exportmentItem = NSMenuItem(title: KMLocalizedString("Export", nil), action: nil, keyEquivalent: "")
  646. exportmentItem.submenu = submenu
  647. return exportmentItem
  648. }
  649. func titles() -> [String] {
  650. return ["PNG", "JPG", "PDF"]
  651. }
  652. @objc func menuItemEditingClick_export(_ item: NSMenuItem) {
  653. let idx = item.tag
  654. guard let callback = self.exportBtnTaped else {
  655. return
  656. }
  657. callback(idx)
  658. }
  659. func imageRotateMenuItem() -> NSMenuItem {
  660. let item = NSMenuItem(title: KMLocalizedString("Rotate", nil), action: #selector(menuItemEditingClick_RotateImage), keyEquivalent: "")
  661. item.target = self
  662. return item
  663. }
  664. @objc func menuItemEditingClick_RotateImage(_ iten: NSMenuItem) {
  665. self.rotate(with: self.editingArea() as? CPDFEditImageArea, rotate: 90)
  666. }
  667. /*
  668. - (NSMenuItem *)alightMenuItem {
  669. NSMenu *submenu = [[[NSMenu alloc] init] autorelease];
  670. NSArray *titles = @[NSLocalizedString(@"Left Alignment", nil),
  671. NSLocalizedString(@"Right Alignment", nil),
  672. NSLocalizedString(@"Center", nil),
  673. NSLocalizedString(@"Justified Alignment", nil),];
  674. NSTextAlignment alignment = [self editingSelectionAlignment];
  675. for (NSUInteger i=0; i<titles.count; i++) {
  676. NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:[titles objectAtIndex:i]
  677. action:@selector(menuItemEditingClick_alignment:)
  678. keyEquivalent:@""] autorelease];
  679. if (alignment == i) {
  680. item.state = NSControlStateValueOn;
  681. }
  682. item.tag = i;
  683. [submenu addItem:item];
  684. }
  685. NSMenuItem *alignmentItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Text Alignment", nil) action:nil keyEquivalent:@""];
  686. alignmentItem.submenu = submenu;
  687. return alignmentItem;
  688. }
  689. - (void)menuItemEditingClick_alignment:(NSMenuItem *)item {
  690. [self setCurrentSelectionAlignment:(NSTextAlignment)item.tag];
  691. }
  692. - (NSMenuItem *)imageCutMenuItem {
  693. NSMenuItem *fontColorItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Cut", nil)
  694. action:@selector(menuItemEditingClick_CutImage:)
  695. keyEquivalent:@""] autorelease];
  696. fontColorItem.target = self;
  697. return fontColorItem;
  698. }
  699. - (NSMenuItem *)imagePasteMenuItem {
  700. NSMenuItem *fontColorItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Paste", nil)
  701. action:@selector(menuItemEditingClick_PasteImage:)
  702. keyEquivalent:@""] autorelease];
  703. fontColorItem.target = self;
  704. return fontColorItem;
  705. }
  706. - (void)menuItemEditingClick_CutImage:(NSMenuItem *)item {
  707. }
  708. - (void)menuItemEditingClick_PasteImage:(NSMenuItem *)item {
  709. }
  710. */
  711. }