KMBackgroundPropertyController.swift 32 KB

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