KMRedactPDFView.swift 39 KB

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