KMBackgroundPropertyController.swift 31 KB

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