KMRedactPDFView.swift 37 KB

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