KMBackgroundPropertyController.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  1. //
  2. // KMBackgroundPropertyController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by Niehaoyu on 2024/11/6.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. @objc protocol KMBackgroundPropertyControllerDelegate: AnyObject {
  10. //水印数据有更新
  11. @objc optional func backgroundPropertyControllerDidUpdate(_ controller: KMBackgroundPropertyController)
  12. //切换到模板界面
  13. @objc optional func backgroundPropertyControllerDidChangetoTemplate(_ controller: KMBackgroundPropertyController)
  14. //成功保存到模板
  15. @objc optional func backgroundPropertyControllerSaveTemplateSuccess(_ controller: KMBackgroundPropertyController, _ data: KMBackgroundModel)
  16. //取消修改模板信息
  17. @objc optional func backgroundPropertyControllerCancelTemplateEdit(_ controller: KMBackgroundPropertyController)
  18. //修改完成模板信息
  19. @objc optional func backgroundPropertyControllerFinishTemplateEdit(_ controller: KMBackgroundPropertyController)
  20. }
  21. class KMBackgroundPropertyController: NSViewController {
  22. @IBOutlet var contendView: NSView!
  23. @IBOutlet var leftTopButton: ComponentButton!
  24. @IBOutlet var titleLabel: NSTextField!
  25. @IBOutlet var templateButton: ComponentButton!
  26. @IBOutlet var typeTabsBGView: NSView!
  27. @IBOutlet var typeTabs: ComponentTabs!
  28. @IBOutlet var infoContendView: NSView!
  29. @IBOutlet var infoContendTopConst: NSLayoutConstraint!
  30. @IBOutlet var infoContendBottomConst: NSLayoutConstraint!
  31. //Text
  32. @IBOutlet var textBGView: NSView!
  33. @IBOutlet var colorLabel: NSTextField!
  34. @IBOutlet var fontColorGroup: ComponentCColorGroup!
  35. //File
  36. @IBOutlet var fileBGView: NSView!
  37. @IBOutlet var fileInputView: ComponentInput!
  38. @IBOutlet var fileInputAddonView: ComponentInputAddon!
  39. //Appearance
  40. @IBOutlet var appearanceBGView: NSView!
  41. @IBOutlet var appearanceLabel: NSTextField!
  42. @IBOutlet var appearance_RotateSelect: ComponentSelect!
  43. @IBOutlet var appearance_OpacitySelect: ComponentSelect!
  44. @IBOutlet var appearanceScaleCheckbox: ComponentCheckBox!
  45. @IBOutlet var appearanceScaleSelect: ComponentSelect!
  46. @IBOutlet var appearanceBGTopConst: NSLayoutConstraint!
  47. //Position
  48. @IBOutlet var positionBGView: NSView!
  49. @IBOutlet var positionLabel: NSTextField!
  50. @IBOutlet var positionItemView: ComponentCPosition!
  51. @IBOutlet var positionXInput: ComponentInputNumber!
  52. @IBOutlet var positionYInput: ComponentInputNumber!
  53. //Save
  54. @IBOutlet var saveTemplateBGView: NSView!
  55. @IBOutlet var saveButton: ComponentButton!
  56. private var textTabProperty = ComponentTabsProperty(tabsType: .underline_Fill, state: .normal, showIcon: false, title: KMLocalizedString("Color"))
  57. private var fileTabProperty = ComponentTabsProperty(tabsType: .underline_Fill, state: .normal, showIcon: false, title: KMLocalizedString("File"))
  58. weak open var delegate: KMBackgroundPropertyControllerDelegate?
  59. var chooseFileURL: URL?
  60. var originalDataDict: Dictionary<String, Any>?
  61. var backgroundData: KMBackgroundModel = KMBackgroundModel()
  62. var editSubType: KMPDFEditSubModeType = .none
  63. var isInBatchMode: Bool = false
  64. //MARK: - func
  65. override func viewDidLoad() {
  66. super.viewDidLoad()
  67. // Do view setup here.
  68. setupProperty()
  69. }
  70. func setupProperty() {
  71. contendView.wantsLayer = true
  72. contendView.layer?.backgroundColor = ComponentLibrary.shared.getComponentColorFromKey("colorBg/layout-middle").cgColor
  73. titleLabel.textColor = ComponentLibrary.shared.getComponentColorFromKey("colorText/2")
  74. titleLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-m-bold")
  75. leftTopButton.properties = ComponentButtonProperty(type: .text_gray, size: .xxs, onlyIcon: true, icon: NSImage(named: "watermark_arrowLeft"), keepPressState: false)
  76. leftTopButton.setTarget(self, action: #selector(leftTopButtonClicked(_:)))
  77. templateButton.properties = ComponentButtonProperty(type: .text_gray, size: .xxs, onlyIcon: true, icon: NSImage(named: "icon_wm_template"), keepPressState: false)
  78. templateButton.setTarget(self, action: #selector(templateButtonClicked(_:)))
  79. typeTabs.updateItemProperty([textTabProperty, fileTabProperty])
  80. typeTabs.delegate = self
  81. //Text
  82. let colorAProperty = ComponentCColorProperty(colorType: .color, state: .normal, isCustom: false, color: KMAnnotationPropertiesColorManager.manager.backgroundColors[0])
  83. let colorBProperty = ComponentCColorProperty(colorType: .color, state: .normal, isCustom: false, color: KMAnnotationPropertiesColorManager.manager.backgroundColors[1])
  84. let colorCProperty = ComponentCColorProperty(colorType: .color, state: .normal, isCustom: false, color: KMAnnotationPropertiesColorManager.manager.backgroundColors[2])
  85. let colorDProperty = ComponentCColorProperty(colorType: .color, state: .normal, isCustom: false, color: KMAnnotationPropertiesColorManager.manager.backgroundColors[3])
  86. let colorEProperty = ComponentCColorProperty(colorType: .color, state: .normal, isCustom: true, color: KMAnnotationPropertiesColorManager.manager.backgroundColors[4])
  87. fontColorGroup.setUpWithColorPropertys([colorAProperty, colorBProperty, colorCProperty, colorDProperty], customItemProperty: colorEProperty)
  88. fontColorGroup.delegate = self
  89. //File
  90. fileInputView.properties = ComponentInputProperty(size: .s,
  91. state:.pressed ,
  92. placeholder: "Select Source File...",
  93. text: "",
  94. creatable: false)
  95. fileInputView.properties.propertyInfo.cornerRadius_topLeft = 0
  96. fileInputView.properties.propertyInfo.cornerRadius_topRight = 0
  97. fileInputView.properties.propertyInfo.cornerRadius_bottomLeft = 0
  98. fileInputView.properties.propertyInfo.cornerRadius_bottomRight = 0
  99. fileInputView.reloadData()
  100. fileInputView.delegate = self
  101. fileInputAddonView.properties = ComponentInputAddonProperty(size: .s,
  102. state: .normal,
  103. addOnBefore: false,
  104. onlyRead: false,
  105. addonType: .imageWithColor,
  106. iconImage: NSImage(named: "icon_folder"))
  107. fileInputAddonView.setTarget(self, action: #selector(chooseURLAction(_ :)))
  108. //Appearance
  109. appearanceLabel.stringValue = KMLocalizedString("Appearance")
  110. appearanceLabel.textColor = ComponentLibrary.shared.getComponentColorFromKey("colorText/2")
  111. appearanceLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
  112. appearance_RotateSelect.properties = ComponentSelectProperties(size: .s,
  113. state: .normal,
  114. creatable: true,
  115. text: "0°",
  116. textUnit: "°",
  117. regexString: "0123456789-")
  118. var rotateItems: [ComponentMenuitemProperty] = []
  119. for string in ["0°", "45°", "-45°", "90°", "-90°"] {
  120. let item = ComponentMenuitemProperty(type: .normal, text: string)
  121. rotateItems.append(item)
  122. }
  123. appearance_RotateSelect.updateMenuItemsArr(rotateItems)
  124. appearance_RotateSelect.delegate = self
  125. appearance_OpacitySelect.properties = ComponentSelectProperties(size: .s,
  126. state: .normal,
  127. creatable: true,
  128. text: "100%",
  129. textUnit: "%",
  130. regexString: "0123456789")
  131. var opacityItems: [ComponentMenuitemProperty] = []
  132. for string in ["25%", "50%", "75%", "100%"] {
  133. let item = ComponentMenuitemProperty(type: .normal, text: string)
  134. opacityItems.append(item)
  135. }
  136. appearance_OpacitySelect.updateMenuItemsArr(opacityItems)
  137. appearance_OpacitySelect.delegate = self
  138. appearanceScaleCheckbox.properties = ComponentCheckBoxProperty(size: .s, text: KMLocalizedString("Scale relative to target page"), checkboxType: .normal)
  139. appearanceScaleCheckbox.setTarget(self, action: #selector(checkBoxClicked(_:)))
  140. appearanceScaleSelect.properties = ComponentSelectProperties(size: .s,
  141. state: .normal,
  142. creatable: true,
  143. text: "100%",
  144. textUnit: "%",
  145. regexString: "0123456789")
  146. var appearanceScaleItems: [ComponentMenuitemProperty] = []
  147. for string in ["25%", "50%", "75%", "100%", "125%", "150%","200%"] {
  148. let item = ComponentMenuitemProperty(type: .normal, text: string)
  149. appearanceScaleItems.append(item)
  150. }
  151. appearanceScaleSelect.updateMenuItemsArr(appearanceScaleItems)
  152. appearanceScaleSelect.delegate = self
  153. //Position
  154. positionLabel.stringValue = KMLocalizedString("Position (mm)")
  155. positionLabel.textColor = ComponentLibrary.shared.getComponentColorFromKey("colorText/2")
  156. positionLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
  157. positionItemView.properties = ComponentCPositionProperty(rowCount: 3, columnCount: 3, dash: false, selRow: 1, selColumn: 1)
  158. positionItemView.delegate = self
  159. positionXInput.properties = ComponentInputNumberProperty(alignment: .left,
  160. size: .s,
  161. minSize: -1000,
  162. maxSize: 1000,
  163. text: "0")
  164. positionXInput.delegate = self
  165. positionYInput.properties = ComponentInputNumberProperty(alignment: .left,
  166. size: .s,
  167. minSize: -1000,
  168. maxSize: 1000,
  169. text: "0")
  170. positionYInput.delegate = self
  171. //Save
  172. saveTemplateBGView.wantsLayer = true
  173. saveTemplateBGView.layer?.backgroundColor = ComponentLibrary.shared.getComponentColorFromKey("colorBg/layout-middle").cgColor
  174. saveButton.properties = ComponentButtonProperty(type: .default_tertiary, size: .m, showLeftIcon: true, buttonText: KMLocalizedString("Save as Template"), icon: NSImage(named: "icon_wm_template_save"), keepPressState: false)
  175. saveButton.setTarget(self, action: #selector(saveButtonClicked(_:)))
  176. }
  177. func reloadData() {
  178. titleLabel.stringValue = KMLocalizedString("Add Background")
  179. leftTopButton.isHidden = true
  180. saveTemplateBGView.isHidden = false
  181. templateButton.properties.icon = NSImage(named: "icon_wm_template")
  182. templateButton.properties.isDisabled = false
  183. if self.isInBatchMode {
  184. infoContendBottomConst.constant = 0
  185. saveTemplateBGView.isHidden = true
  186. } else {
  187. infoContendBottomConst.constant = 72
  188. saveTemplateBGView.isHidden = false
  189. }
  190. infoContendTopConst.constant = 56
  191. typeTabsBGView.isHidden = false
  192. if editSubType == .edit {
  193. infoContendTopConst.constant = 8
  194. typeTabsBGView.isHidden = true
  195. titleLabel.stringValue = KMLocalizedString("Edit Background")
  196. leftTopButton.isHidden = false
  197. saveTemplateBGView.isHidden = true
  198. templateButton.properties.icon = NSImage(named: "edit_save")
  199. var isChanged = false
  200. if let dict = self.originalDataDict {
  201. isChanged = KMBackgroundManager.compareIsChangedModel(backgroundData, withDict: dict as NSDictionary)
  202. }
  203. if isChanged == false {
  204. templateButton.properties.isDisabled = true
  205. }
  206. if backgroundData.type == .image && backgroundData.imagePath == nil {
  207. templateButton.properties.isDisabled = true
  208. }
  209. }
  210. templateButton.reloadData()
  211. fileBGView.isHidden = true
  212. textBGView.isHidden = true
  213. textTabProperty.state = .normal
  214. fileTabProperty.state = .normal
  215. if backgroundData.type == .color {
  216. textBGView.isHidden = false
  217. appearanceBGTopConst.constant = 88
  218. textTabProperty.state = .pressed
  219. } else if backgroundData.type == .image {
  220. fileBGView.isHidden = false
  221. appearanceBGTopConst.constant = 48
  222. fileTabProperty.state = .pressed
  223. }
  224. typeTabs.refreshItems()
  225. //Text
  226. fontColorGroup.currentColor = backgroundData.color
  227. fontColorGroup.refreshUI()
  228. //File
  229. fileInputView.properties.text = backgroundData.imagePath ?? ""
  230. fileInputView.reloadData()
  231. //Appearance
  232. appearance_RotateSelect.properties.text = String(format: "%.0f", backgroundData.rotation) + "°"
  233. appearance_RotateSelect.reloadData()
  234. if backgroundData.opacity > 1 {
  235. backgroundData.opacity = 1
  236. }
  237. appearance_OpacitySelect.properties.text = String(format: "%.0f", backgroundData.opacity*100) + "%"
  238. appearance_OpacitySelect.reloadData()
  239. appearanceScaleCheckbox.properties.checkboxType = backgroundData.isScale ? .selected : .normal
  240. appearanceScaleCheckbox.reloadData()
  241. appearanceScaleSelect.properties.isDisabled = backgroundData.isScale ? false : true
  242. appearanceScaleSelect.properties.text = String(format: "%.0f", backgroundData.scale*100) + "%"
  243. appearanceScaleSelect.reloadData()
  244. //Position
  245. if backgroundData.verticalMode == 2 {
  246. positionItemView.properties.selRow = 0
  247. } else if backgroundData.verticalMode == 1 {
  248. positionItemView.properties.selRow = 1
  249. } else if backgroundData.verticalMode == 0 {
  250. positionItemView.properties.selRow = 2
  251. }
  252. if backgroundData.horizontalMode == 0 {
  253. positionItemView.properties.selColumn = 0
  254. } else if backgroundData.horizontalMode == 1 {
  255. positionItemView.properties.selColumn = 1
  256. } else if backgroundData.horizontalMode == 2 {
  257. positionItemView.properties.selColumn = 2
  258. }
  259. positionItemView.reloadData()
  260. positionXInput.properties.text = String(format: "%.0f", backgroundData.horizontalSpace)
  261. positionXInput.reloadData()
  262. positionYInput.properties.text = String(format: "%.0f", backgroundData.verticalSpace)
  263. positionYInput.reloadData()
  264. if backgroundData.type == .color {
  265. saveButton.properties.isDisabled = false
  266. } else if backgroundData.type == .image {
  267. if backgroundData.imagePath != nil {
  268. saveButton.properties.isDisabled = false
  269. } else {
  270. saveButton.properties.isDisabled = true
  271. }
  272. }
  273. saveButton.reloadData()
  274. }
  275. //MARK: - Action
  276. @objc func leftTopButtonClicked(_ sender: ComponentButton) {
  277. if sender == leftTopButton {
  278. var isChanged = false
  279. if let dict = self.originalDataDict {
  280. isChanged = KMBackgroundManager.compareIsChangedModel(backgroundData, withDict: dict as NSDictionary)
  281. }
  282. if isChanged == true {
  283. let alert = NSAlert()
  284. alert.alertStyle = .critical
  285. alert.messageText = KMLocalizedString("Save template changes?")
  286. alert.informativeText = KMLocalizedString("Cancel and they will not be saved.")
  287. alert.addButton(withTitle: KMLocalizedString("Save"))
  288. alert.addButton(withTitle: KMLocalizedString("Cancel"))
  289. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  290. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  291. let _ = KMBackgroundManager.defaultManager.updateTemplate(model: self.backgroundData)
  292. self.delegate?.backgroundPropertyControllerFinishTemplateEdit?(self)
  293. } else {
  294. if let dict = self.originalDataDict {
  295. KMBackgroundManager.defaultManager.updateModel(self.backgroundData, withDict: dict as NSDictionary)
  296. let _ = KMBackgroundManager.defaultManager.updateTemplate(model: self.backgroundData)
  297. }
  298. self.delegate?.backgroundPropertyControllerFinishTemplateEdit?(self)
  299. }
  300. }
  301. } else {
  302. delegate?.backgroundPropertyControllerCancelTemplateEdit?(self)
  303. }
  304. }
  305. }
  306. @objc func templateButtonClicked(_ sender: ComponentButton) {
  307. if editSubType == .add {
  308. delegate?.backgroundPropertyControllerDidChangetoTemplate?(self)
  309. } else if editSubType == .edit {
  310. let _ = KMBackgroundManager.defaultManager.updateTemplate(model: self.backgroundData)
  311. delegate?.backgroundPropertyControllerFinishTemplateEdit?(self)
  312. }
  313. }
  314. @objc func checkBoxClicked(_ sender: ComponentCheckBox) {
  315. if sender == appearanceScaleCheckbox {
  316. backgroundData.isScale = appearanceScaleCheckbox.properties.checkboxType == .selected ? true : false
  317. if backgroundData.isScale == false {
  318. backgroundData.scale = 1
  319. }
  320. }
  321. reloadData()
  322. delegate?.backgroundPropertyControllerDidUpdate?(self)
  323. }
  324. @objc func saveButtonClicked(_ sender: ComponentButton) {
  325. let saveWindow: KMWatermarkSaveWindow = KMWatermarkSaveWindow(windowNibName: "KMWatermarkSaveWindow")
  326. if backgroundData.type == .color {
  327. saveWindow.nameValue = KMBackgroundManager.defaultManager.fetchAvailableBackgroundName()
  328. } else if backgroundData.type == .image {
  329. if let value = backgroundData.imagePath?.lastPathComponent {
  330. saveWindow.nameValue = String.deletingPathExtension(value)
  331. } else {
  332. saveWindow.nameValue = ""
  333. }
  334. }
  335. saveWindow.saveHandler = {[weak self] string in
  336. guard let weakSelf = self else { return }
  337. DispatchQueue.main.async {
  338. weakSelf.backgroundData.name = string ?? ""
  339. if KMBackgroundManager.defaultManager.addTemplate(model: weakSelf.backgroundData) {
  340. weakSelf.delegate?.backgroundPropertyControllerSaveTemplateSuccess?(weakSelf, weakSelf.backgroundData)
  341. }
  342. }
  343. }
  344. saveWindow.own_beginSheetModal(for: view.window) { string in
  345. }
  346. saveWindow.titleLabel.stringValue = KMLocalizedString("Add Background")
  347. }
  348. @objc func chooseURLAction(_ sender: NSView) {
  349. self.chooseURLAction(sender, nil)
  350. }
  351. func chooseURLAction(_ sender: NSView, _ filePath: String? = nil) {
  352. let openPanel = NSOpenPanel()
  353. openPanel.canChooseDirectories = false
  354. openPanel.canChooseFiles = true
  355. openPanel.allowsMultipleSelection = false
  356. openPanel.allowedFileTypes = ["jpg", "jpeg", "png", "pdf"]
  357. if let path = filePath {
  358. openPanel.directoryURL = NSURL.fileURL(withPath: path)
  359. }
  360. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  361. if result == NSApplication.ModalResponse.OK {
  362. guard let url = openPanel.url else { return }
  363. self.chooseFileURL = url
  364. let filePath = url.path
  365. let outFolder = KMBackgroundManager.defaultManager.kBackgroundImageFolder
  366. let fileName = filePath.getLastComponentDeleteExtension
  367. if filePath.extension.lowercased() == ".pdf" {
  368. let pdf = CPDFDocument(url: url)
  369. guard !pdf!.isEncrypted else { return }
  370. if let image = self.generateThumbnail(for: url) {
  371. if let outFolderPath = outFolder?.stringByAppendingPathComponent(fileName + ".png") {
  372. try?image.pngData()?.write(to: URL(fileURLWithPath: outFolderPath))
  373. if FileManager.default.fileExists(atPath: outFolderPath) {
  374. self.backgroundData.imagePath = outFolderPath
  375. self.delegate?.backgroundPropertyControllerDidUpdate?(self)
  376. self.reloadData()
  377. }
  378. }
  379. }
  380. } else {
  381. let image = NSImage(contentsOfFile: url.path)
  382. if image == nil || NSImage.isDamageImage(image, imagePath: url.path) {
  383. let alert = NSAlert()
  384. alert.alertStyle = .critical
  385. alert.messageText = "The file \"\(url.lastPathComponent)\" could not be opened."
  386. alert.informativeText = "It may be damaged or use a file format that PDF Reader Pro doesn’t recognize."
  387. alert.addButton(withTitle: "Cancel")
  388. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  389. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  390. // Cancel button clicked
  391. }
  392. }
  393. return
  394. }
  395. if let resultPath = outFolder?.stringByAppendingPathComponent(fileName + ".png") {
  396. try?FileManager.default.copyItem(atPath: url.path, toPath: resultPath)
  397. self.backgroundData.imagePath = resultPath
  398. }
  399. self.delegate?.backgroundPropertyControllerDidUpdate?(self)
  400. self.reloadData()
  401. }
  402. }
  403. }
  404. }
  405. func generateThumbnail(for pdfURL: URL) -> NSImage? {
  406. // 创建PDF文档
  407. guard let pdfDocument = CGPDFDocument(pdfURL as CFURL),
  408. let pdfPage = pdfDocument.page(at: 1) else {
  409. print("打开PDF文件失败")
  410. return nil
  411. }
  412. // 获取页面尺寸
  413. let pageRect = pdfPage.getBoxRect(.mediaBox)
  414. // 创建图形上下文
  415. let size = NSSize(width: 200, height: 300)
  416. let bitsPerComponent = 8
  417. let bytesPerPixel = 4
  418. let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
  419. let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: bitsPerComponent, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo)
  420. // 绘制PDF页面
  421. context?.saveGState()
  422. context?.translateBy(x: 0, y: size.height)
  423. context?.scaleBy(x: 1.0, y: -1.0) // 反转坐标系
  424. context?.scaleBy(x: size.width / pageRect.width, y: size.height / pageRect.height) // 缩放
  425. context?.drawPDFPage(pdfPage)
  426. context?.restoreGState()
  427. // 创建NSImage
  428. if let cgImage = context?.makeImage() {
  429. return NSImage(cgImage: cgImage, size: NSSize(width: size.width, height: size.height))
  430. } else {
  431. return nil
  432. }
  433. }
  434. //MARK: - Mouse
  435. override func mouseDown(with event: NSEvent) {
  436. super.mouseDown(with: event)
  437. view.window?.makeFirstResponder(nil)
  438. }
  439. }
  440. //MARK: - ComponentTabsDelegate
  441. extension KMBackgroundPropertyController: ComponentTabsDelegate {
  442. func componentTabsDidSelected(_ view: ComponentTabs, _ property: ComponentTabsProperty) {
  443. if property == textTabProperty {
  444. backgroundData.type = .color
  445. } else if property == fileTabProperty {
  446. backgroundData.type = .image
  447. }
  448. reloadData()
  449. delegate?.backgroundPropertyControllerDidUpdate?(self)
  450. }
  451. }
  452. //MARK: - ComponentCColorDelegate
  453. extension KMBackgroundPropertyController: ComponentCColorDelegate {
  454. func componentCColorDidChooseColor(_ view: NSView, _ color: NSColor?) {
  455. if view == fontColorGroup {
  456. backgroundData.color = color ?? NSColor.clear
  457. }
  458. reloadData()
  459. delegate?.backgroundPropertyControllerDidUpdate?(self)
  460. }
  461. func componentCColorGroupColorsUpdates(_ view: NSView, _ colors: [NSColor]) {
  462. KMAnnotationPropertiesColorManager.manager.updateDefaultColors(colors, forKey: KM_Background_default_ColorsKey)
  463. }
  464. }
  465. //MARK: - ComponentSelectDelegate
  466. extension KMBackgroundPropertyController: ComponentSelectDelegate {
  467. func componentSelectDidSelect(view: ComponentSelect?, menuItemProperty: ComponentMenuitemProperty?) {
  468. if view == appearance_OpacitySelect {
  469. if let text = menuItemProperty?.text {
  470. let result = text.stringByDeleteCharString("%")
  471. backgroundData.opacity = result.stringToCGFloat()/100
  472. }
  473. } else if view == appearance_RotateSelect {
  474. if let text = menuItemProperty?.text {
  475. let result = text.stringByDeleteCharString("°")
  476. backgroundData.rotation = result.stringToCGFloat()
  477. }
  478. } else if view == appearanceScaleSelect {
  479. if let text = menuItemProperty?.text {
  480. let result = text.stringByDeleteCharString("%")
  481. backgroundData.scale = result.stringToCGFloat()/100
  482. }
  483. }
  484. reloadData()
  485. delegate?.backgroundPropertyControllerDidUpdate?(self)
  486. }
  487. func componentSelectTextDidEndEditing(_ view: ComponentSelect) {
  488. if view == appearance_OpacitySelect {
  489. if let text = appearance_OpacitySelect.properties.text {
  490. let result = text.stringByDeleteCharString("%")
  491. backgroundData.opacity = result.stringToCGFloat()/100
  492. }
  493. } else if view == appearance_RotateSelect {
  494. if let text = appearance_RotateSelect.properties.text {
  495. let result = text.stringByDeleteCharString("°")
  496. backgroundData.rotation = result.stringToCGFloat()
  497. }
  498. } else if view == appearanceScaleSelect {
  499. if let text = appearanceScaleSelect.properties.text {
  500. let result = text.stringByDeleteCharString("%")
  501. backgroundData.scale = min(10, result.stringToCGFloat()/100)
  502. }
  503. }
  504. reloadData()
  505. delegate?.backgroundPropertyControllerDidUpdate?(self)
  506. }
  507. }
  508. //MARK: - ComponentCPositionDelegate
  509. extension KMBackgroundPropertyController: ComponentCPositionDelegate {
  510. func componentCPositionDidChoose(_ view: NSView, _ row: Int, _ column: Int) {
  511. if view == positionItemView {
  512. if row == 0 {
  513. backgroundData.verticalMode = 2
  514. } else if row == 1 {
  515. backgroundData.verticalMode = 1
  516. } else if row == 2 {
  517. backgroundData.verticalMode = 0
  518. }
  519. if column == 0 {
  520. backgroundData.horizontalMode = 0
  521. } else if column == 1 {
  522. backgroundData.horizontalMode = 1
  523. } else if column == 2 {
  524. backgroundData.horizontalMode = 2
  525. }
  526. }
  527. reloadData()
  528. delegate?.backgroundPropertyControllerDidUpdate?(self)
  529. }
  530. }
  531. //MARK: - ComponentInputNumberDelegate
  532. extension KMBackgroundPropertyController: ComponentInputNumberDelegate {
  533. func componentInputNumberDidValueChanged(inputNumber: ComponentInputNumber?) {
  534. if inputNumber == positionXInput {
  535. if let text = inputNumber?.properties.text {
  536. backgroundData.horizontalSpace = text.stringToCGFloat()
  537. }
  538. } else if inputNumber == positionYInput {
  539. if let text = inputNumber?.properties.text {
  540. backgroundData.verticalSpace = text.stringToCGFloat()
  541. }
  542. }
  543. reloadData()
  544. delegate?.backgroundPropertyControllerDidUpdate?(self)
  545. }
  546. }
  547. //MARK: - ComponentInputDelegate
  548. extension KMBackgroundPropertyController: ComponentInputDelegate {
  549. func componentInputDidCoverButtonClicked(inputView: ComponentInput) {
  550. if let fileURL = self.chooseFileURL, inputView.properties.creatable == false {
  551. self.chooseURLAction(inputView, fileURL.path)
  552. }
  553. }
  554. }