KMRedactPDFView.swift 36 KB

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