KMCustomViewButton.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512
  1. //
  2. // KMCustomViewButton.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2023/11/2.
  6. //
  7. import Cocoa
  8. @objc enum KMCustomViewButtonType: Int {
  9. case batchToolbar = 0
  10. case menuItem
  11. case normal
  12. }
  13. @objc enum KMCustomViewButtonState: Int {
  14. case normal = 0
  15. case mouseIn
  16. case hightLighted
  17. }
  18. @objc protocol KMCustomButtonViewPopDataSource: NSObjectProtocol {
  19. /// pop框有多少行
  20. func numberOfLine(in button: KMCustomViewButton) -> Int
  21. /// pop框某行显示的文字
  22. func string(for button: KMCustomViewButton, index: Int) -> String?
  23. /// 某行是否需要下划线
  24. func needInsertSeperateLine(_ button: KMCustomViewButton, index: Int) -> Bool
  25. /// 某行是否需要选取
  26. func needHightLightLine(_ button: KMCustomViewButton, index: Int) -> Bool
  27. }
  28. @objc protocol KMCustomButtonViewPopDelegate: NSObjectProtocol {
  29. func customViewButton(_ button: KMCustomViewButton, didSelectIndex index: Int)
  30. }
  31. @objcMembers class KMCustomViewButton: NSView {
  32. /// constraint
  33. var frontImageLeftConstraint: MASConstraint? //左边图片距离左边约束
  34. var frontImageTopConstraint: MASConstraint? //左边图片顶部约束
  35. var titleLeftConstraint: MASConstraint? //标题距离左边约束
  36. var titleTopConstraint: MASConstraint? //标题顶部约束
  37. var backImageLeftConstraint: MASConstraint? //右边图片距离左边约束
  38. /// view
  39. lazy var imageView: NSImageView = {
  40. let view = NSImageView()
  41. return view
  42. }()
  43. lazy var titleTextField: NSTextField = {
  44. let view = NSTextField()
  45. view.isBordered = false
  46. view.drawsBackground = true
  47. view.backgroundColor = .clear
  48. view.isEditable = false
  49. return view
  50. }()
  51. lazy var indicateImageView: NSImageView = {
  52. let view = NSImageView()
  53. return view
  54. }()
  55. weak var layoutReferenceView: NSView?
  56. /// layer
  57. var backLayer: CALayer?
  58. /// state
  59. var isSelected = false {
  60. didSet {
  61. if (self.isSelected) {
  62. self._toolbarButtonSelected(true)
  63. if let color = self.selectColor {
  64. self.backLayer?.backgroundColor = color.cgColor
  65. }
  66. } else {
  67. self._toolbarButtonSelected(true)
  68. self.backLayer?.backgroundColor = .clear
  69. }
  70. }
  71. }
  72. var mouseInColor: NSColor?
  73. var highLightColor: NSColor?
  74. var selectColor: NSColor?
  75. /// popover
  76. var popOver: NSPopover?
  77. var enable = false
  78. /// title Attribute
  79. var titleAttributeDict: [String : Any]?
  80. weak var dataSource: KMCustomButtonViewPopDataSource? {
  81. didSet {
  82. NotificationCenter.default.removeObserver(self)
  83. NotificationCenter.default.addObserver(self, selector: #selector(_closePop), name: NSNotification.Name("KMCloseCustomViewButtonPopNotification"), object: nil)
  84. }
  85. }
  86. weak var delegate: KMCustomButtonViewPopDelegate?
  87. private var _showMenuFlag = false
  88. private var _type: KMCustomViewButtonType = .batchToolbar
  89. private var _state: KMCustomViewButtonState = .normal {
  90. didSet {
  91. if (self._state == .normal) {
  92. if (self.isSelected) {
  93. self.backLayer?.backgroundColor = self.selectColor != nil ? self.selectColor!.cgColor : .clear
  94. } else {
  95. self._toolbarButtonSelected(true)
  96. self.backLayer?.backgroundColor = .clear
  97. }
  98. } else if (self._state == .mouseIn) {
  99. self._toolbarButtonSelected(true)
  100. if (self.isSelected) {
  101. self.backLayer?.backgroundColor = self.selectColor != nil ? self.selectColor!.cgColor : (self.mouseInColor ?? NSColor.clear).cgColor
  102. } else {
  103. self.backLayer?.backgroundColor = (self.mouseInColor ?? NSColor.clear).cgColor
  104. }
  105. } else if (self._state == .hightLighted) {
  106. if (self.isSelected) {
  107. self.backLayer?.backgroundColor = self.selectColor != nil ? self.selectColor!.cgColor : (self.highLightColor ?? NSColor.clear).cgColor
  108. } else {
  109. self.backLayer?.backgroundColor = (self.highLightColor ?? NSColor.clear).cgColor
  110. }
  111. }
  112. if (self.titleAttributeDict != nil) {
  113. self.titleTextField.textColor = self.titleAttributeDict?["\(self._state.rawValue)"] as? NSColor
  114. }
  115. }
  116. }
  117. private weak var _target: AnyObject?
  118. private var _action: Selector?
  119. deinit {
  120. KMPrint("KMCustomViewButton deinit.")
  121. NotificationCenter.default.removeObserver(self)
  122. }
  123. /**
  124. * 初始化方法
  125. * @param frontImage 头部图片
  126. * @param backImage 尾部图片
  127. * @param title 标题
  128. * @param title 样式
  129. *
  130. */
  131. convenience init(frontImage: NSImage?, backImage: NSImage?, title: String?, type: KMCustomViewButtonType) {
  132. if frontImage == nil && backImage == nil && title == nil {
  133. // return
  134. }
  135. self.init()
  136. self.wantsLayer = true
  137. self.enable = false
  138. self._addTrackingArea()
  139. self.layoutReferenceView = self
  140. var leftMargin = 0.0
  141. if (frontImage != nil) {
  142. self.addSubview(self.imageView)
  143. self.imageView.image = frontImage
  144. leftMargin = 8
  145. self.imageView.mas_makeConstraints { make in
  146. self.frontImageLeftConstraint = make?.left.equalTo()(self.layoutReferenceView)?.offset()(leftMargin)
  147. make?.centerY.top().equalTo()(self.layoutReferenceView)
  148. self.frontImageTopConstraint = make?.top.equalTo()(self.layoutReferenceView)?.offset()(3)
  149. }
  150. self.layoutReferenceView = self.imageView
  151. }
  152. if (title != nil) {
  153. self.addSubview(self.titleTextField)
  154. self.titleTextField.stringValue = title!
  155. self.titleTextField.font = .systemFont(ofSize: 12)
  156. self.titleTextField.textColor = KMAppearance.Layout.h0Color()
  157. self.titleTextField.mas_makeConstraints { make in
  158. if self.isEqual(to: self.layoutReferenceView) {
  159. leftMargin = 30
  160. self.titleLeftConstraint = make?.left.equalTo()(self)?.offset()(leftMargin)
  161. self.titleTopConstraint = make?.top.equalTo()(self)?.offset()(3)
  162. make?.centerY.equalTo()(self)
  163. } else {
  164. leftMargin = 8
  165. self.titleLeftConstraint = make?.left.equalTo()(self.imageView.mas_right)?.offset()(leftMargin)
  166. make?.centerY.equalTo()(self)
  167. }
  168. }
  169. self.layoutReferenceView = self.titleTextField
  170. }
  171. if (backImage != nil) {
  172. self.addSubview(self.indicateImageView)
  173. self.indicateImageView.image = backImage
  174. self.indicateImageView.mas_makeConstraints { make in
  175. self.backImageLeftConstraint = make?.left.equalTo()(self.layoutReferenceView?.mas_right)?.offset()(2)
  176. make?.centerY.equalTo()(self)
  177. }
  178. self.layoutReferenceView = self.indicateImageView
  179. }
  180. self.layoutReferenceView?.mas_makeConstraints({ make in
  181. make?.right.equalTo()(self)?.offset()(-leftMargin)
  182. })
  183. self.configuAppearance(type: type)
  184. self._type = type
  185. self._state = .normal
  186. self.isSelected = false
  187. }
  188. override func mouseEntered(with event: NSEvent) {
  189. if (self.enable) {
  190. super.mouseEntered(with: event)
  191. self._showPop()
  192. if (self.dataSource == nil) {
  193. NotificationCenter.default.post(name: NSNotification.Name("KMCloseCustomViewButtonPopNotification"), object: nil)
  194. }
  195. self._state = .mouseIn
  196. }
  197. }
  198. // MARK: - Public Methods
  199. /// 设置设置target-action
  200. func addTarget(_ target: AnyObject?, action: Selector?) {
  201. self._target = target
  202. self._action = action
  203. }
  204. /// 关闭pop
  205. func closePop() {
  206. self._closePop()
  207. }
  208. override func mouseExited(with event: NSEvent) {
  209. if (self.enable) {
  210. super.mouseExited(with: event)
  211. if (self._showMenuFlag) {
  212. } else {
  213. self._state = .normal
  214. }
  215. }
  216. }
  217. override func mouseDown(with event: NSEvent) {
  218. if (self.enable) {
  219. super.mouseDown(with: event)
  220. self._state = .hightLighted
  221. }
  222. }
  223. override func mouseUp(with event: NSEvent) {
  224. if (self.enable) {
  225. super.mouseUp(with: event)
  226. if (self._showMenuFlag) {
  227. } else {
  228. self._state = .normal
  229. }
  230. /// 响应事件
  231. if let data = (self._target as? NSObject)?.responds(to: self._action), data {
  232. (self._target as? NSObject)?.perform(self._action, with: self)
  233. }
  234. }
  235. }
  236. }
  237. // MARK: - Private Methods
  238. extension KMCustomViewButton {
  239. private func _toolbarButtonSelected(_ isSelected: Bool) {
  240. // if (isSelected) {
  241. // if ([self.titleTextField.stringValue isEqualToString:NSLocalizedString(@"Convert", nil)]) {
  242. // self.imageView.image = [NSImage imageNamed:@"KMImageNameUXIconBatchConvert"];
  243. // } else if ([self.titleTextField.stringValue isEqualToString:NSLocalizedString(@"Merge", nil)]) {
  244. // self.imageView.image = [NSImage imageNamed:@"KMImageNameUXIconBatchMerge"];
  245. // } else if ([self.titleTextField.stringValue isEqualToString:NSLocalizedString(@"Compress", nil)]) {
  246. // self.imageView.image = [NSImage imageNamed:@"KMImageNameUXIconBatchOptimize"];
  247. // } else if ([self.titleTextField.stringValue isEqualToString:NSLocalizedString(@"OCR", nil)]) {
  248. // self.imageView.image = [NSImage imageNamed:@"KMImageNameUXIconBatchConvertOCR"];
  249. // } else if ([self.titleTextField.stringValue isEqualToString:NSLocalizedString(@"Security", nil)]) {
  250. // self.imageView.image = [NSImage imageNamed:@"KMImageNameUXIconBatchSafe"];
  251. // } else if ([self.titleTextField.stringValue isEqualToString:NSLocalizedString(@"Watermark", nil)]) {
  252. // self.imageView.image = [NSImage imageNamed:@"KMImageNameUXIconBatchWatermark"];
  253. // } else if ([self.titleTextField.stringValue isEqualToString:NSLocalizedString(@"Background", nil)]) {
  254. // self.imageView.image = [NSImage imageNamed:@"KMImageNameUXIconBatchBackground"];
  255. // } else if ([self.titleTextField.stringValue isEqualToString:NSLocalizedString(@"Header & Footer", nil)]) {
  256. // self.imageView.image = [NSImage imageNamed:@"KMImageNameUXIconBatchHeaderandfooter"];
  257. // } else if ([self.titleTextField.stringValue isEqualToString:NSLocalizedString(@"Bates Numbers", nil)]) {
  258. // self.imageView.image = [NSImage imageNamed:@"KMImageNameUXIconBatchBates"];
  259. // }
  260. // } else {
  261. if self.titleTextField.stringValue == KMLocalizedString("Convert", nil) {
  262. self.imageView.image = NSImage(named: "KMImageNameUXIconBatchConvertNor")
  263. } else if self.titleTextField.stringValue == KMLocalizedString("Merge", nil) {
  264. self.imageView.image = NSImage(named: "KMImageNameUXIconBatchMergeNor")
  265. } else if self.titleTextField.stringValue == KMLocalizedString("Compress", nil) {
  266. self.imageView.image = NSImage(named: "KMImageNameUXIconBatchOptimizeNor")
  267. } else if self.titleTextField.stringValue == KMLocalizedString("OCR", nil) {
  268. self.imageView.image = NSImage(named: "KMImageNameUXIconBatchConvertOCRNor")
  269. } else if self.titleTextField.stringValue == KMLocalizedString("Security", nil) {
  270. self.imageView.image = NSImage(named: "KMImageNameUXIconBatchSafeNor")
  271. } else if self.titleTextField.stringValue == KMLocalizedString("Watermark", nil) {
  272. self.imageView.image = NSImage(named: "KMImageNameUXIconBatchWatermarkNor")
  273. } else if self.titleTextField.stringValue == KMLocalizedString("Background", nil) {
  274. self.imageView.image = NSImage(named: "KMImageNameUXIconBatchBackgroundNor")
  275. } else if self.titleTextField.stringValue == KMLocalizedString("Header & Footer", nil) {
  276. self.imageView.image = NSImage(named: "KMImageNameUXIconBatchHeaderandfooterNor")
  277. } else if self.titleTextField.stringValue == KMLocalizedString("Bates Numbers", nil) {
  278. self.imageView.image = NSImage(named: "KMImageNameUXIconBatchBatesNor")
  279. }
  280. // }
  281. }
  282. @objc private func _closePop() {
  283. self.popOver?.close()
  284. self._state = .normal
  285. }
  286. private func _showPop() {
  287. if (self.delegate == nil || self.dataSource == nil) {
  288. return
  289. }
  290. let menuViewController = KMCustomButtonPopMenuViewController()
  291. menuViewController.delegate = self
  292. menuViewController.dataSources = self
  293. if (self.popOver == nil) {
  294. self.popOver = NSPopover()
  295. }
  296. self.popOver?.delegate = self
  297. self.popOver?.contentViewController = menuViewController
  298. self.popOver?.animates = false
  299. self.popOver?.behavior = .semitransient
  300. self.popOver?.contentSize = menuViewController.view.frame.size
  301. var sourcesRect = self.bounds
  302. sourcesRect = self.convert(sourcesRect, to: nil)
  303. sourcesRect.origin.y -= 20
  304. sourcesRect.size.height+=20
  305. self.window?.popover = self.popOver
  306. self.window?.sourcesRect = sourcesRect
  307. self.popOver?.show(relativeTo: CGRectInset(self.bounds, 0, 5), of: self, preferredEdge: .minY)
  308. }
  309. private func _addTrackingArea() {
  310. let trackingArea = NSTrackingArea(rect: self.bounds, options: [.mouseEnteredAndExited, .inVisibleRect, .activeAlways,.mouseMoved], owner: self)
  311. self.addTrackingArea(trackingArea)
  312. }
  313. }
  314. // MARK: - NSPopoverDelegate
  315. extension KMCustomViewButton: NSPopoverDelegate {
  316. func popoverDidShow(_ notification: Notification) {
  317. self._showMenuFlag = true
  318. }
  319. func popoverDidClose(_ notification: Notification) {
  320. self._showMenuFlag = false
  321. self._state = .normal
  322. }
  323. }
  324. // MARK: - KMCustomButtonPopMenuViewControllerDelegate, KMCustomButtonPopMenuViewControllerDataSources
  325. extension KMCustomViewButton: KMCustomButtonPopMenuViewControllerDelegate, KMCustomButtonPopMenuViewControllerDataSources {
  326. func customViewButtonPopDidSelectIndex(_ index: Int) {
  327. if let _ = self.delegate?.customViewButton(self, didSelectIndex: index) {
  328. self._closePop()
  329. }
  330. }
  331. func numberOfLine() -> Int {
  332. if let data = self.dataSource?.numberOfLine(in: self) {
  333. return data
  334. }
  335. return 0
  336. }
  337. /// pop框某行显示的文字
  338. func stringForLine(at index: Int) -> String? {
  339. if let data = self.dataSource?.string(for: self, index: index) {
  340. return data
  341. }
  342. return nil;
  343. }
  344. /// 某行是否需要下划线
  345. func needInsertSeperateLine(at index: Int) -> Bool {
  346. if let data = self.dataSource?.needInsertSeperateLine(self, index: index) {
  347. return data
  348. }
  349. return false
  350. }
  351. /// 某行是否需要选取
  352. func needHightLightLine(at index: Int) -> Bool {
  353. if let data = self.dataSource?.needHightLightLine(self, index: index) {
  354. return data
  355. }
  356. return false
  357. }
  358. func imageForLine(at index: Int) -> NSImage? {
  359. return nil
  360. }
  361. func itemEnable(at index: Int) -> Bool {
  362. return true
  363. }
  364. }
  365. // MARK: - Appearance
  366. extension KMCustomViewButton {
  367. func configuAppearance(type: KMCustomViewButtonType) {
  368. if (type == .batchToolbar) {
  369. self.backLayer = CALayer()
  370. self.backLayer?.frame = self.layer?.frame ?? NSRect.zero
  371. self.backLayer?.autoresizingMask = [.layerWidthSizable, .layerHeightSizable]
  372. self.layer?.addSublayer(self.backLayer!)
  373. self.backLayer?.cornerRadius = 6.0;
  374. self.selectColor = KMAppearance.Status.selColor()
  375. self.highLightColor = KMAppearance.Status.selColor()
  376. self.mouseInColor = KMAppearance.Status.selColor()
  377. } else if (type == .menuItem) {
  378. self.alignCenter(margin: 10)
  379. self.changeTopMargin(5)
  380. }
  381. }
  382. /// 调整按钮左右间距并居中
  383. func alignCenter(margin: CGFloat) {
  384. self.changeLeftMargin(margin)
  385. self.changeRightMargin(margin)
  386. }
  387. /// 调整顶部间距离
  388. func changeTopMargin(_ topMargin: CGFloat) {
  389. let v = self._leftestView()
  390. if self.imageView.isEqual(to: v) {
  391. self.imageView.mas_updateConstraints { make in
  392. make?.top.equalTo()(self)?.offset()(topMargin)
  393. }
  394. } else if self.titleTextField.isEqual(to: v) {
  395. self.titleTextField.mas_updateConstraints { make in
  396. make?.top.equalTo()(self)?.offset()(topMargin)
  397. }
  398. } else if self.indicateImageView.isEqual(to: v) {
  399. }
  400. }
  401. /// 调整按钮左边间距
  402. func changeLeftMargin(_ leftMargin: CGFloat) {
  403. let v = self._leftestView()
  404. if self.imageView.isEqual(to: v) {
  405. self.imageView.mas_updateConstraints { make in
  406. self.frontImageLeftConstraint = make?.left.equalTo()(self)?.offset()(leftMargin)
  407. }
  408. } else if self.titleTextField.isEqual(to: v) {
  409. self.titleTextField.mas_updateConstraints { make in
  410. self.titleLeftConstraint = make?.left.equalTo()(self)?.offset()(leftMargin)
  411. }
  412. } else if self.indicateImageView.isEqual(to: v) {
  413. self.indicateImageView.mas_updateConstraints { make in
  414. self.backImageLeftConstraint = make?.left.equalTo()(self)?.offset()(leftMargin)
  415. }
  416. }
  417. }
  418. /// 调整按钮右边间距
  419. func changeRightMargin(_ rightMargin: CGFloat) {
  420. let v = self._rightestView()
  421. if self.imageView.isEqual(to: v) {
  422. self.imageView.mas_updateConstraints { make in
  423. make?.right.equalTo()(self)?.offset()(-rightMargin)
  424. }
  425. } else if self.titleTextField.isEqual(to: v) {
  426. self.titleTextField.mas_updateConstraints { make in
  427. make?.right.equalTo()(self)?.offset()(-rightMargin)
  428. }
  429. } else if self.indicateImageView.isEqual(to: v) {
  430. self.indicateImageView.mas_updateConstraints { make in
  431. make?.right.equalTo()(self)?.offset()(-rightMargin)
  432. }
  433. }
  434. }
  435. private func _leftestView() -> NSView? {
  436. if self.subviews.contains(self.imageView) {
  437. return self.imageView
  438. } else if self.subviews.contains(self.titleTextField) {
  439. return self.titleTextField
  440. } else if (self.subviews.contains(self.indicateImageView)) {
  441. return self.indicateImageView
  442. }
  443. return nil
  444. }
  445. private func _rightestView() -> NSView? {
  446. if self.subviews.contains(self.indicateImageView) {
  447. return self.indicateImageView
  448. } else if self.subviews.contains(self.titleTextField) {
  449. return self.titleTextField
  450. } else if self.subviews.contains(self.imageView) {
  451. return self.imageView
  452. }
  453. return nil
  454. }
  455. }