KMRedactPDFView.swift 36 KB

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