KMRedactPDFView.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  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. annotation?.borderWidth = 2
  263. if self.isWhiteOut {
  264. annotation?.setBorderColor(.white)
  265. annotation?.setInteriorColor(.white)
  266. } else {
  267. annotation?.setBorderColor(KMPDFAnnotationRedactConfig.shared.redactOutlineColor)
  268. annotation?.setInteriorColor(KMPDFAnnotationRedactConfig.shared.redactFillColor)
  269. }
  270. annotation?.setFontColor(KMPDFAnnotationRedactConfig.shared.redactFontColor)
  271. if KMPDFAnnotationRedactConfig.shared.overlayText {
  272. annotation?.setAlignment(NSTextAlignment(rawValue: KMPDFAnnotationRedactConfig.shared.textAlignment) ?? .left)
  273. let font = NSFont(name: "Helvetica", size: KMPDFAnnotationRedactConfig.shared.fontSize.cgFloat)
  274. annotation?.setFont(font)
  275. annotation?.setOverlayText(KMPDFAnnotationRedactConfig.shared.overlayTextString)
  276. }
  277. self.addAnnotation(with: annotation, to: page)
  278. self.newAddAnnotation.append(annotation!)
  279. self.setNeedsDisplayFor(page)
  280. }
  281. break
  282. } else if theEvent.type == .leftMouseDragged {
  283. super.mouseDragged(with: theEvent)
  284. }
  285. }
  286. }
  287. func doRedact(event: NSEvent) {
  288. var point = NSZeroPoint
  289. let page = self.pageAndPoint(&point, for: event, nearest: true)
  290. let wasMouseCoalescingEnabled = NSEvent.isMouseCoalescingEnabled
  291. let window = self.window
  292. var bezierPath: NSBezierPath?
  293. var layer: CAShapeLayer?
  294. let boxBounds = page?.bounds ?? .zero
  295. let t = CGAffineTransform(scaleX: self.scaleFactor, y: self.scaleFactor).rotated(by: -Double.pi * 0.5 * (page!.rotation.cgFloat / 90.0))
  296. layer = CAShapeLayer()
  297. layer?.bounds = NSRectToCGRect(boxBounds)
  298. layer?.anchorPoint = .zero
  299. let posi = self.convert(boxBounds.origin, from: page)
  300. layer?.position = NSPointToCGPoint(posi)
  301. layer?.setAffineTransform(t)
  302. layer?.zPosition = 1.0
  303. layer?.masksToBounds = true
  304. layer?.fillColor = KMPDFAnnotationRedactConfig.shared.redactFillColor?.cgColor
  305. // layer?.strokeColor = CGColorGetConstantColor(kCGColorBlack)
  306. layer?.strokeColor = .black
  307. layer?.lineJoin = .round
  308. layer?.lineCap = .round
  309. var lastMouseEvent = event
  310. // SKRectEdges
  311. var resizeHandle: CRectEdges = [.minYEdgeMask, .maxXEdgeMask]
  312. var originalBounds = NSMakeRect(point.x, point.y, 0, 0)
  313. self.layer?.addSublayer(layer!)
  314. var eventMask: NSEvent.EventTypeMask = [.leftMouseUp, .leftMouseDragged]
  315. var rect = NSRect.zero
  316. var theEvent = event
  317. while (true) {
  318. theEvent = window!.nextEvent(matching: eventMask)!
  319. if theEvent.type == .leftMouseUp {
  320. if (rect.size.width < MIN_NOTE_SIZE || rect.size.height < MIN_NOTE_SIZE) {
  321. break
  322. }
  323. var quadrilateralPoints = NSMutableArray()
  324. let annotation = CPDFRedactAnnotation(document: self.document)
  325. var bounds = rect
  326. quadrilateralPoints.add(NSValue(point: NSMakePoint(NSMinX(bounds), NSMaxY(bounds))))
  327. quadrilateralPoints.add(NSValue(point: NSMakePoint(NSMaxX(bounds), NSMaxY(bounds))))
  328. quadrilateralPoints.add(NSValue(point: NSMakePoint(NSMinX(bounds), NSMinY(bounds))))
  329. quadrilateralPoints.add(NSValue(point: NSMakePoint(NSMaxX(bounds), NSMinY(bounds))))
  330. annotation?.setQuadrilateralPoints(quadrilateralPoints as? [Any] ?? [])
  331. annotation?.setModificationDate(Date())
  332. let userName = KMPreference.shared.author
  333. annotation?.setUserName(userName)
  334. // if ([annotation isKindOfClass:[CPDFRedactAnnotation class]]) {
  335. // annotation?.borderWidth = 10
  336. annotation?.borderWidth = 2
  337. if self.isWhiteOut {
  338. annotation?.setBorderColor(.white)
  339. annotation?.setInteriorColor(.white)
  340. } else {
  341. annotation?.setBorderColor(KMPDFAnnotationRedactConfig.shared.redactOutlineColor)
  342. annotation?.setInteriorColor(KMPDFAnnotationRedactConfig.shared.redactFillColor)
  343. }
  344. annotation?.setFontColor(KMPDFAnnotationRedactConfig.shared.redactFontColor)
  345. if KMPDFAnnotationRedactConfig.shared.overlayText {
  346. annotation?.setAlignment(NSTextAlignment(rawValue: KMPDFAnnotationRedactConfig.shared.textAlignment) ?? .left)
  347. let font = NSFont(name: "Helvetica", size: KMPDFAnnotationRedactConfig.shared.fontSize.cgFloat)
  348. annotation?.setFont(font)
  349. annotation?.setOverlayText(KMPDFAnnotationRedactConfig.shared.overlayTextString)
  350. }
  351. self.addAnnotation(with: annotation, to: page)
  352. self.newAddAnnotation.append(annotation!)
  353. break
  354. } else if theEvent.type == .leftMouseDragged {
  355. // rect = self.doResizeLink(event: lastMouseEvent, fromPoint: point, originalBounds: originalBounds, page: page!, resizeHandle: &resizeHandle)
  356. rect = self.doResizeLink(with: lastMouseEvent, from: point, originalBounds: originalBounds, page: page, resizeHandle: &resizeHandle)
  357. bezierPath = NSBezierPath(rect: rect)
  358. layer?.path = bezierPath?.kmCGPath()
  359. lastMouseEvent = theEvent
  360. }
  361. }
  362. layer?.removeFromSuperlayer()
  363. NSEvent.isMouseCoalescingEnabled = wasMouseCoalescingEnabled
  364. }
  365. func doResizeLink(event: NSEvent, fromPoint originalPagePoint: NSPoint, originalBounds: NSRect, page: CPDFPage, resizeHandle resizeHandlePtr: inout CRectEdges) -> NSRect {
  366. let currentPagePoint = self.convert(event.locationInView(self), to: page)
  367. var newBounds = originalBounds
  368. var pageBounds = page.bounds
  369. var relPoint = CPDFListViewSubstractPoints(currentPagePoint, originalPagePoint)
  370. var resizeHandle = resizeHandlePtr
  371. if (NSEqualSizes(originalBounds.size, NSZeroSize)) {
  372. var currentResizeHandle: CRectEdges = .minYEdgeMask
  373. if relPoint.x < 0.0 {
  374. currentResizeHandle = [.minXEdgeMask]
  375. } else {
  376. currentResizeHandle = [.maxXEdgeMask]
  377. }
  378. if relPoint.y <= 0.0 {
  379. currentResizeHandle.insert(.minYEdgeMask)
  380. } else {
  381. currentResizeHandle.insert(.maxYEdgeMask)
  382. }
  383. if (currentResizeHandle != resizeHandle) {
  384. resizeHandlePtr = currentResizeHandle
  385. resizeHandle = currentResizeHandle
  386. }
  387. }
  388. let minWidth = MIN_NOTE_SIZE
  389. let minHeight = MIN_NOTE_SIZE
  390. if resizeHandle.contains(.maxXEdgeMask) {
  391. newBounds.size.width += relPoint.x
  392. if (NSMaxX(newBounds) > NSMaxX(pageBounds)) {
  393. newBounds.size.width = NSMaxX(pageBounds) - NSMinX(newBounds)
  394. }
  395. if (NSWidth(newBounds) < minWidth) {
  396. newBounds.size.width = minWidth
  397. }
  398. } else if resizeHandle.contains(.minXEdgeMask) {
  399. newBounds.origin.x += relPoint.x
  400. newBounds.size.width -= relPoint.x
  401. if (NSMinX(newBounds) < NSMinX(pageBounds)) {
  402. newBounds.size.width = NSMaxX(newBounds) - NSMinX(pageBounds)
  403. newBounds.origin.x = NSMinX(pageBounds)
  404. }
  405. if (NSWidth(newBounds) < minWidth) {
  406. newBounds.origin.x = NSMaxX(newBounds) - minWidth
  407. newBounds.size.width = minWidth
  408. }
  409. }
  410. if resizeHandle.contains(.maxXEdgeMask) {
  411. newBounds.size.height += relPoint.y
  412. if (NSMaxY(newBounds) > NSMaxY(pageBounds)) {
  413. newBounds.size.height = NSMaxY(pageBounds) - NSMinY(newBounds)
  414. }
  415. if (NSHeight(newBounds) < minHeight) {
  416. newBounds.size.height = minHeight
  417. }
  418. } else if resizeHandle.contains(.minYEdgeMask) {
  419. newBounds.origin.y += relPoint.y
  420. newBounds.size.height -= relPoint.y
  421. if (NSMinY(newBounds) < NSMinY(pageBounds)) {
  422. newBounds.size.height = NSMaxY(newBounds) - NSMinY(pageBounds)
  423. newBounds.origin.y = NSMinY(pageBounds)
  424. }
  425. if (NSHeight(newBounds) < minHeight) {
  426. newBounds.origin.y = NSMaxY(newBounds) - minHeight
  427. newBounds.size.height = minHeight
  428. }
  429. }
  430. return newBounds
  431. }
  432. override func validate(_ menuItem: NSMenuItem!) -> Bool {
  433. guard let _doc = self.document, _doc.isLocked == false else {
  434. return false
  435. }
  436. let action = menuItem.action
  437. if (action == #selector(deleteAnnotation)) {
  438. return true
  439. } else if (action == #selector(setPropertiesDefault)) {
  440. return true
  441. } else if (action == #selector(properties)) {
  442. return true
  443. } else if (action == #selector(repeatMark)) {
  444. if(_doc.pageCount == 1) {
  445. return false
  446. }
  447. return true
  448. } else if (action == #selector(applyRedact)) {
  449. return true
  450. } else {
  451. return super.validate(menuItem)
  452. }
  453. }
  454. /*
  455. #pragma mark -
  456. - (void)drawPage:(CPDFPage *)page toContext:(CGContextRef)context
  457. {
  458. [self.activeAnnotations enumerateObjectsUsingBlock:^(CPDFAnnotation *annotation, NSUInteger idx, BOOL * _Nonnull stop) {
  459. if (annotation.page && [annotation.page isEqual:page]) {
  460. [annotation drawSelectionHighlightForView:self inContext:context];
  461. }
  462. }];
  463. }
  464. - (CPDFPage *)pageAndPoint:(NSPoint *)point forEvent:(NSEvent *)event nearest:(BOOL)nearest {
  465. NSPoint p = [event locationInView:self];
  466. CPDFPage *page = [self pageForPoint:p nearest:nearest];
  467. if (page && point)
  468. *point = [self convertPoint:p toPage:page];
  469. return page;
  470. }
  471. */
  472. }
  473. // MARK: - KMExtensions
  474. extension KMRedactPDFView {
  475. @objc dynamic func acrossAddAnnotations(_ pages: NSMutableArray) {
  476. if(pages.count == 0) {
  477. return
  478. }
  479. var anntations = NSMutableArray()
  480. for i in 0 ..< pages.count {
  481. // NSUInteger index = [[pages objectAtIndex:i] integerValue];
  482. guard let index = (pages.object(at: i) as? NSNumber)?.intValue else {
  483. continue
  484. }
  485. if(index - 1 < self.document.pageCount) {
  486. // CPDFPage *page = [[self.document pageAtIndex:index-1] retain];
  487. let page = self.document.page(at: UInt(index-1))
  488. let annotation = CPDFRedactAnnotation(document: self.document)
  489. if let anno = self.currentAnnotation {
  490. annotation?.setUserName(anno.userName())
  491. annotation?.setModificationDate(anno.modificationDate())
  492. annotation?.setQuadrilateralPoints(anno.quadrilateralPoints())
  493. annotation?.borderWidth = anno.borderWidth
  494. if self.isWhiteOut {
  495. annotation?.setBorderColor(.white)
  496. annotation?.setInteriorColor(.white)
  497. } else {
  498. annotation?.setBorderColor(anno.borderColor())
  499. annotation?.setInteriorColor(anno.interiorColor())
  500. }
  501. annotation?.setFont(anno.font())
  502. annotation?.setOverlayText(anno.overlayText())
  503. annotation?.setFontColor(anno.fontColor())
  504. annotation?.setAlignment(anno.alignment())
  505. let pageRect = page?.bounds ?? .zero
  506. let annotationRect = annotation?.bounds ?? .zero
  507. if (NSMaxX(annotationRect) > NSMaxX(pageRect) ||
  508. NSMinX(annotationRect) < NSMinX(pageRect) ||
  509. NSMinY(annotationRect) < NSMinY(pageRect) ||
  510. NSMaxY(annotationRect) > NSMaxY(pageRect) ||
  511. anno.page == page){
  512. continue
  513. }
  514. }
  515. page?.addAnnotation(annotation)
  516. anntations.add(annotation as Any)
  517. self.setNeedsDisplayAnnotationViewFor(page)
  518. }
  519. }
  520. (self.undoManager?.prepare(withInvocationTarget: self) as AnyObject).removeAccosAnnotations(anntations)
  521. }
  522. @objc dynamic func removeAccosAnnotations(_ annotations: NSMutableArray) {
  523. if(annotations.count == 0){
  524. return
  525. }
  526. var pageIndexs = NSMutableArray()
  527. for i in 0 ..< annotations.count {
  528. guard let annotation = annotations.object(at: i) as? CPDFRedactAnnotation else {
  529. continue
  530. }
  531. let page = annotation.page
  532. let index = self.document.index(for: page)
  533. page?.removeAnnotation(annotation)
  534. pageIndexs.add(NSNumber(integerLiteral: Int(index)+1))
  535. self.setNeedsDisplayAnnotationViewFor(page)
  536. }
  537. (self.undoManager?.prepare(withInvocationTarget: self) as AnyObject).acrossAddAnnotations(pageIndexs)
  538. }
  539. /*
  540. - (CGFloat)unitWidthOnPage:(CPDFPage *)page
  541. {
  542. return NSWidth([self convertRect:NSMakeRect(0.0, 0.0, 1.0, 1.0) toPage:page]);
  543. }
  544. - (NSRect)integralRect:(NSRect)rect onPage:(CPDFPage *)page
  545. {
  546. return [self convertRect:[self convertRect:rect fromPage:page] toPage:page];
  547. }
  548. - (CPDFAnnotation *)addRedactPDFSelection:(CPDFSelection *)currentSelection
  549. {
  550. NSMutableArray *quadrilateralPoints = [NSMutableArray array];
  551. CPDFRedactAnnotation *annotation = [[CPDFRedactAnnotation alloc] initWithDocument:self.document];
  552. for (CPDFSelection *selection in currentSelection.selectionsByLine) {
  553. CGRect bounds = selection.bounds;
  554. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMinX(bounds), CGRectGetMaxY(bounds))]];
  555. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMaxY(bounds))]];
  556. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMinX(bounds), CGRectGetMinY(bounds))]];
  557. [quadrilateralPoints addObject:[NSValue valueWithPoint:CGPointMake(CGRectGetMaxX(bounds), CGRectGetMinY(bounds))]];
  558. }
  559. NSString *userName = [[NSUserDefaults standardUserDefaults] stringForKey:@"SKUserName"];
  560. [annotation setUserName:userName ? : NSFullUserName()];
  561. [annotation setModificationDate:[NSDate date]];
  562. [annotation setQuadrilateralPoints:quadrilateralPoints];
  563. [annotation setBorderWidth:10];
  564. [(CPDFRedactAnnotation *)annotation setBorderColor:[KMPDFAnnotationRedactConfig sharedInstance].redactOutlineColor];
  565. [(CPDFRedactAnnotation *)annotation setInteriorColor:[KMPDFAnnotationRedactConfig sharedInstance].redactFillColor];
  566. [(CPDFRedactAnnotation *)annotation setFontColor:[KMPDFAnnotationRedactConfig sharedInstance].redactFontColor];
  567. if([KMPDFAnnotationRedactConfig sharedInstance].overlayText) {
  568. [(CPDFRedactAnnotation *)annotation setAlignment:[KMPDFAnnotationRedactConfig sharedInstance].textAlignment];
  569. NSFont* font = [NSFont fontWithName:@"Helvetica" size:[KMPDFAnnotationRedactConfig sharedInstance].fontSize];
  570. [(CPDFRedactAnnotation *)annotation setFont:font];
  571. [(CPDFRedactAnnotation *)annotation setOverlayText:[KMPDFAnnotationRedactConfig sharedInstance].overlayTextString];
  572. }
  573. return annotation;
  574. }
  575. - (void)deleteAnnotation:(NSMenuItem *)item {
  576. CPDFRedactAnnotation *annotation = item.representedObject;
  577. if(annotation && [annotation isKindOfClass:[CPDFRedactAnnotation class]]) {
  578. [annotation retain];
  579. CPDFPage *page = [[annotation page] retain];
  580. [self setNeedsDisplayAnnotationViewForPage:page];
  581. [self removeAnnotation:annotation];
  582. [annotation release];
  583. [page release];
  584. }
  585. }
  586. - (void)addAnnotation:(CPDFAnnotation *)annotation toPage:(CPDFPage *)page
  587. {
  588. [[[self undoManager] prepareWithInvocationTarget:self] removeAnnotation:annotation];
  589. [page addAnnotation:annotation];
  590. if([self.newAddAnnotation containsObject:annotation]) {
  591. [self.newAddAnnotation removeObject:annotation];
  592. } else {
  593. [self.newAddAnnotation addObject:annotation];
  594. }
  595. [self setNeedsDisplayAnnotationViewForPage:page];
  596. }
  597. - (void)removeAnnotation:(CPDFAnnotation *)annotation
  598. {
  599. CPDFAnnotation *wasAnnotation = [annotation retain];
  600. CPDFPage *page = [[wasAnnotation page] retain];
  601. [[[self undoManager] prepareWithInvocationTarget:self] addAnnotation:wasAnnotation toPage:page];
  602. if([self.newAddAnnotation containsObject:annotation]) {
  603. [self.newAddAnnotation removeObject:annotation];
  604. } else {
  605. [self.newAddAnnotation addObject:annotation];
  606. }
  607. if([self.activeAnnotations containsObject:annotation]) {
  608. [self.activeAnnotations removeObject:annotation];
  609. }
  610. [self setNeedsDisplayAnnotationViewForPage:page];
  611. [page removeAnnotation:wasAnnotation];
  612. [wasAnnotation release];
  613. [page release];
  614. }
  615. */
  616. }
  617. // MARK: - Event
  618. extension KMRedactPDFView {
  619. func fontColorMenuItem() -> NSMenuItem {
  620. let fontColorItem = NSMenuItem(title: KMLocalizedString("Text Color", nil), action: #selector(menuItemEditingClick_FontColor), keyEquivalent: "")
  621. fontColorItem.target = self
  622. return fontColorItem
  623. }
  624. @objc func menuItemEditingClick_FontColor(_ sender: NSMenuItem?) {
  625. let color = self.editingSelectionFontColor()
  626. let cp = NSColorPanel.shared
  627. cp.orderFront(nil)
  628. cp.setTarget(self)
  629. cp.color = color!
  630. cp.showsAlpha = false
  631. cp.setAction(#selector(fontColorChangeAction))
  632. }
  633. @objc func fontColorChangeAction(_ sender: AnyObject?) {
  634. self.setEditingSelectionFontColor(NSColorPanel.shared.color)
  635. guard let callback = self.eventColorChanged else {
  636. return
  637. }
  638. callback(NSColorPanel.shared.color)
  639. }
  640. func fontSizeMenuItem() -> NSMenuItem {
  641. let size = self.editingSelectionFontSize()
  642. let fontSizes = self.fontSizes()
  643. let submenu = NSMenu()
  644. for (i,fontSize) in fontSizes.enumerated() {
  645. let fs: CGFloat = fontSize.stringToCGFloat()
  646. let item = NSMenuItem(title: String(format: "%d pt", fs), action: #selector(menuItemEditingClick_FontSize), keyEquivalent: "")
  647. item.target = self
  648. item.tag = i
  649. submenu.addItem(item)
  650. if (fabsf(Float(fs-size)) < 0.1) {
  651. item.state = .on
  652. }
  653. }
  654. let fontSizeItem = NSMenuItem(title: KMLocalizedString("Font Size", nil), action: nil, keyEquivalent: "")
  655. fontSizeItem.submenu = submenu
  656. return fontSizeItem
  657. }
  658. func fontSizes() -> [String] {
  659. return ["6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "24", "36", "48", "72", "96", "144", "288"]
  660. }
  661. @objc func menuItemEditingClick_FontSize(_ item: NSMenuItem) {
  662. let fontSize = self.fontSizes()[item.tag].stringToCGFloat()
  663. self.setEditingSelectionFontSize(fontSize)
  664. guard let callback = self.eventFontChanged else {
  665. return
  666. }
  667. callback()
  668. }
  669. func imageExportMenuItem() -> NSMenuItem {
  670. let submenu = NSMenu()
  671. for (i, title) in self.titles().enumerated() {
  672. let item = NSMenuItem(title: title, action: #selector(menuItemEditingClick_export), keyEquivalent: "")
  673. item.tag = i
  674. submenu.addItem(item)
  675. }
  676. let exportmentItem = NSMenuItem(title: KMLocalizedString("Export", nil), action: nil, keyEquivalent: "")
  677. exportmentItem.submenu = submenu
  678. return exportmentItem
  679. }
  680. func titles() -> [String] {
  681. return ["PNG", "JPG", "PDF"]
  682. }
  683. @objc func menuItemEditingClick_export(_ item: NSMenuItem) {
  684. let idx = item.tag
  685. guard let callback = self.exportBtnTaped else {
  686. return
  687. }
  688. callback(idx)
  689. }
  690. func imageRotateMenuItem() -> NSMenuItem {
  691. let item = NSMenuItem(title: KMLocalizedString("Rotate", nil), action: #selector(menuItemEditingClick_RotateImage), keyEquivalent: "")
  692. item.target = self
  693. return item
  694. }
  695. @objc func menuItemEditingClick_RotateImage(_ iten: NSMenuItem) {
  696. self.rotate(with: self.editingArea() as? CPDFEditImageArea, rotate: 90)
  697. }
  698. /*
  699. - (NSMenuItem *)alightMenuItem {
  700. NSMenu *submenu = [[[NSMenu alloc] init] autorelease];
  701. NSArray *titles = @[NSLocalizedString(@"Left Alignment", nil),
  702. NSLocalizedString(@"Right Alignment", nil),
  703. NSLocalizedString(@"Center", nil),
  704. NSLocalizedString(@"Justified Alignment", nil),];
  705. NSTextAlignment alignment = [self editingSelectionAlignment];
  706. for (NSUInteger i=0; i<titles.count; i++) {
  707. NSMenuItem *item = [[[NSMenuItem alloc] initWithTitle:[titles objectAtIndex:i]
  708. action:@selector(menuItemEditingClick_alignment:)
  709. keyEquivalent:@""] autorelease];
  710. if (alignment == i) {
  711. item.state = NSControlStateValueOn;
  712. }
  713. item.tag = i;
  714. [submenu addItem:item];
  715. }
  716. NSMenuItem *alignmentItem = [[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Text Alignment", nil) action:nil keyEquivalent:@""];
  717. alignmentItem.submenu = submenu;
  718. return alignmentItem;
  719. }
  720. - (void)menuItemEditingClick_alignment:(NSMenuItem *)item {
  721. [self setCurrentSelectionAlignment:(NSTextAlignment)item.tag];
  722. }
  723. - (NSMenuItem *)imageCutMenuItem {
  724. NSMenuItem *fontColorItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Cut", nil)
  725. action:@selector(menuItemEditingClick_CutImage:)
  726. keyEquivalent:@""] autorelease];
  727. fontColorItem.target = self;
  728. return fontColorItem;
  729. }
  730. - (NSMenuItem *)imagePasteMenuItem {
  731. NSMenuItem *fontColorItem = [[[NSMenuItem alloc] initWithTitle:NSLocalizedString(@"Paste", nil)
  732. action:@selector(menuItemEditingClick_PasteImage:)
  733. keyEquivalent:@""] autorelease];
  734. fontColorItem.target = self;
  735. return fontColorItem;
  736. }
  737. - (void)menuItemEditingClick_CutImage:(NSMenuItem *)item {
  738. }
  739. - (void)menuItemEditingClick_PasteImage:(NSMenuItem *)item {
  740. }
  741. */
  742. }