KMNWatermarkPropertyController.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  1. //
  2. // KMNWatermarkPropertyController.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by Niehaoyu on 2024/11/1.
  6. //
  7. import Cocoa
  8. import KMComponentLibrary
  9. @objc protocol KMNWatermarkPropertyControllerDelegate: AnyObject {
  10. @objc optional func watermarkPropertyControllerDidRemoveWatermark(_ controller: KMNWatermarkPropertyController, _ type: CPDFWatermarkType)
  11. //水印数据有更新
  12. @objc optional func watermarkPropertyControllerDidUpdate(_ controller: KMNWatermarkPropertyController)
  13. //切换到模板界面
  14. @objc optional func watermarkPropertyControllerDidChangetoTemplate(_ controller: KMNWatermarkPropertyController)
  15. //成功保存到模板
  16. @objc optional func watermarkPropertyControllerSaveTemplateSuccess(_ controller: KMNWatermarkPropertyController, _ data: KMPDFWatermarkData)
  17. //取消修改模板信息
  18. @objc optional func watermarkPropertyControllerCancelTemplateEdit(_ controller: KMNWatermarkPropertyController)
  19. }
  20. class KMNWatermarkPropertyController: NSViewController {
  21. @IBOutlet var contendView: NSView!
  22. @IBOutlet var leftTopButton: ComponentButton!
  23. @IBOutlet var titleLabel: NSTextField!
  24. @IBOutlet var templateButton: ComponentButton!
  25. @IBOutlet var typeTabsBGView: NSView!
  26. @IBOutlet var typeTabs: ComponentTabs!
  27. @IBOutlet var infoContendView: NSView!
  28. @IBOutlet var infoScrollView: KMScrollView!
  29. @IBOutlet var infoScrollTopConst: NSLayoutConstraint!
  30. @IBOutlet var infoContendBottomConst: NSLayoutConstraint!
  31. //Text
  32. @IBOutlet var textBGView: NSView!
  33. @IBOutlet var text_textareaView: ComponentTextarea!
  34. @IBOutlet var fontNameSelect: ComponentSelect!
  35. @IBOutlet var fontStyleSelect: ComponentSelect!
  36. @IBOutlet var fontSizeSelect: ComponentSelect!
  37. @IBOutlet var fontColorGroup: ComponentCColorGroup!
  38. //File
  39. @IBOutlet var fileBGView: NSView!
  40. @IBOutlet var fileInputView: ComponentInput!
  41. @IBOutlet var fileInputAddonView: ComponentInputAddon!
  42. //Appearance
  43. @IBOutlet var appearanceBGView: NSView!
  44. @IBOutlet var appearanceLabel: NSTextField!
  45. @IBOutlet var appearance_RotateSelect: ComponentSelect!
  46. @IBOutlet var appearance_OpacitySelect: ComponentSelect!
  47. @IBOutlet var appearanceScaleCheckbox: ComponentCheckBox!
  48. @IBOutlet var appearanceScaleSelect: ComponentSelect!
  49. @IBOutlet var appearanceTopPageRadio: ComponentRadio!
  50. @IBOutlet var appearanceBottomPageRadio: ComponentRadio!
  51. @IBOutlet var appearanceBGTopConst: NSLayoutConstraint!
  52. //Position
  53. @IBOutlet var positionBGView: NSView!
  54. @IBOutlet var positionLabel: NSTextField!
  55. @IBOutlet var positionItemView: ComponentCPosition!
  56. @IBOutlet var positionXInput: ComponentInputNumber!
  57. @IBOutlet var positionYInput: ComponentInputNumber!
  58. @IBOutlet var positionTileCheckbox: ComponentCheckBox!
  59. @IBOutlet var positionTileHorImage: NSImageView!
  60. @IBOutlet var positionTileVertImage: NSImageView!
  61. @IBOutlet var positionTileHoriInput: ComponentInputNumber!
  62. @IBOutlet var positionTileVertInput: ComponentInputNumber!
  63. //Save
  64. @IBOutlet var saveTemplateBGView: NSView!
  65. @IBOutlet var saveButton: ComponentButton!
  66. private var textTabProperty = ComponentTabsProperty(tabsType: .underline_Fill, state: .normal, showIcon: false, title: KMLocalizedString("Text"))
  67. private var fileTabProperty = ComponentTabsProperty(tabsType: .underline_Fill, state: .normal, showIcon: false, title: KMLocalizedString("File"))
  68. private var familyNames = CPDFFont.familyNames
  69. var watermarkData: KMPDFWatermarkData = KMWatermarkManager.defaultManager.defaultWatermarkData
  70. public var editSubType: KMPDFEditSubModeType = .add
  71. public var isInBatchMode: Bool = false
  72. var originalDataDict: Dictionary<String, Any>?
  73. weak open var delegate: KMNWatermarkPropertyControllerDelegate?
  74. //MARK: - func
  75. override func viewDidLoad() {
  76. super.viewDidLoad()
  77. // Do view setup here.
  78. infoScrollView.documentView = infoContendView
  79. infoScrollView.scrollerStyle = .overlay
  80. infoScrollView.layout()
  81. setupProperty()
  82. reloadData()
  83. refreshScrollView()
  84. }
  85. func setupProperty() {
  86. contendView.wantsLayer = true
  87. contendView.layer?.backgroundColor = ComponentLibrary.shared.getComponentColorFromKey("colorBg/layout-middle").cgColor
  88. titleLabel.textColor = ComponentLibrary.shared.getComponentColorFromKey("colorText/2")
  89. titleLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-m-bold")
  90. leftTopButton.properties = ComponentButtonProperty(type: .text_gray, size: .xxs, onlyIcon: true, icon: NSImage(named: "watermark_arrowLeft"), keepPressState: false)
  91. leftTopButton.setTarget(self, action: #selector(leftTopButtonClicked(_:)))
  92. templateButton.properties = ComponentButtonProperty(type: .text_gray, size: .xxs, onlyIcon: true, icon: NSImage(named: "icon_wm_template"), keepPressState: false)
  93. templateButton.setTarget(self, action: #selector(templateButtonClicked(_:)))
  94. typeTabs.updateItemProperty([textTabProperty, fileTabProperty])
  95. typeTabs.delegate = self
  96. //Text
  97. text_textareaView.properties = ComponentTextareaProperty(size: .s, placeholderString: KMLocalizedString("Please enter..."), totalCount: -1, text: "")
  98. text_textareaView.delegate = self
  99. fontNameSelect.properties = ComponentSelectProperties(size: .s,
  100. state: .normal,
  101. text: "")
  102. var menuItemArr: [ComponentMenuitemProperty] = []
  103. for string in familyNames {
  104. let item = ComponentMenuitemProperty(type: .normal, text: string, identifier: string)
  105. menuItemArr.append(item)
  106. }
  107. fontNameSelect.updateMenuItemsArr(menuItemArr)
  108. fontNameSelect.selectItemAtIndex(0)
  109. fontNameSelect.delegate = self
  110. fontStyleSelect.properties = ComponentSelectProperties(size: .s,
  111. state: .normal,
  112. text: "")
  113. fontStyleSelect.delegate = self
  114. fontSizeSelect.properties = ComponentSelectProperties(size: .s,
  115. state: .normal,
  116. creatable: true,
  117. text: "12 pt",
  118. textUnit: " pt",
  119. regexString: "0123456789 pt")
  120. var sizeItemArr: [ComponentMenuitemProperty] = []
  121. for string in ["6","8","10","12","14",
  122. "16","18","20","22","24",
  123. "26","28","30","32","34",
  124. "36","40","48","64","80",
  125. "96","112"] {
  126. let item = ComponentMenuitemProperty(type: .normal, text: string, identifier: string)
  127. sizeItemArr.append(item)
  128. }
  129. fontSizeSelect.updateMenuItemsArr(sizeItemArr)
  130. fontSizeSelect.selectItemAtIndex(0)
  131. fontSizeSelect.delegate = self
  132. let colorAProperty = ComponentCColorProperty(colorType: .color, state: .normal, isCustom: false, color: KMAnnotationPropertiesColorManager.manager.watermark_Colors[0])
  133. let colorBProperty = ComponentCColorProperty(colorType: .color, state: .normal, isCustom: false, color: KMAnnotationPropertiesColorManager.manager.watermark_Colors[1])
  134. let colorCProperty = ComponentCColorProperty(colorType: .color, state: .normal, isCustom: false, color: KMAnnotationPropertiesColorManager.manager.watermark_Colors[2])
  135. let colorDProperty = ComponentCColorProperty(colorType: .color, state: .normal, isCustom: false, color: KMAnnotationPropertiesColorManager.manager.watermark_Colors[3])
  136. let colorEProperty = ComponentCColorProperty(colorType: .color, state: .normal, isCustom: true, color: KMAnnotationPropertiesColorManager.manager.watermark_Colors[4])
  137. fontColorGroup.setUpWithColorPropertys([colorAProperty, colorBProperty, colorCProperty, colorDProperty], customItemProperty: colorEProperty)
  138. fontColorGroup.delegate = self
  139. //File
  140. fileInputView.properties = ComponentInputProperty(size: .s,
  141. state:.pressed ,
  142. placeholder: "Select Source File...",
  143. text: "",
  144. creatable: false)
  145. fileInputView.properties.propertyInfo.cornerRadius_topLeft = 0
  146. fileInputView.properties.propertyInfo.cornerRadius_topRight = 0
  147. fileInputView.properties.propertyInfo.cornerRadius_bottomLeft = 0
  148. fileInputView.properties.propertyInfo.cornerRadius_bottomRight = 0
  149. fileInputView.reloadData()
  150. fileInputView.delegate = self
  151. fileInputAddonView.properties = ComponentInputAddonProperty(size: .s,
  152. state: .normal,
  153. addOnBefore: false,
  154. onlyRead: false,
  155. addonType: .imageWithColor,
  156. iconImage: NSImage(named: "icon_folder"))
  157. fileInputAddonView.setTarget(self, action: #selector(chooseURLAction(_ :)))
  158. //Appearance
  159. appearanceLabel.stringValue = KMLocalizedString("Appearance")
  160. appearanceLabel.textColor = ComponentLibrary.shared.getComponentColorFromKey("colorText/2")
  161. appearanceLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
  162. appearance_RotateSelect.properties = ComponentSelectProperties(size: .s,
  163. state: .normal,
  164. creatable: true,
  165. text: "0°",
  166. textUnit: "°",
  167. regexString: "0123456789°-")
  168. var rotateItems: [ComponentMenuitemProperty] = []
  169. for string in ["0°", "45°", "-45°", "90°", "-90°"] {
  170. let item = ComponentMenuitemProperty(type: .normal, text: string)
  171. rotateItems.append(item)
  172. }
  173. appearance_RotateSelect.updateMenuItemsArr(rotateItems)
  174. appearance_RotateSelect.delegate = self
  175. appearance_OpacitySelect.properties = ComponentSelectProperties(size: .s,
  176. state: .normal,
  177. creatable: true,
  178. text: "100%",
  179. textUnit: "%",
  180. regexString: "0123456789%")
  181. var opacityItems: [ComponentMenuitemProperty] = []
  182. for string in ["25%", "50%", "75%", "100%"] {
  183. let item = ComponentMenuitemProperty(type: .normal, text: string)
  184. opacityItems.append(item)
  185. }
  186. appearance_OpacitySelect.updateMenuItemsArr(opacityItems)
  187. appearance_OpacitySelect.delegate = self
  188. appearanceScaleCheckbox.properties = ComponentCheckBoxProperty(size: .s, text: KMLocalizedString("Scale relative to target page"), checkboxType: .normal)
  189. appearanceScaleCheckbox.setTarget(self, action: #selector(checkBoxClicked(_:)))
  190. appearanceScaleSelect.properties = ComponentSelectProperties(size: .s,
  191. state: .normal,
  192. creatable: true,
  193. text: "100%",
  194. textUnit: "%",
  195. regexString: "0123456789%")
  196. var appearanceScaleItems: [ComponentMenuitemProperty] = []
  197. for string in ["25%", "50%", "75%", "100%", "125%", "150%","200%"] {
  198. let item = ComponentMenuitemProperty(type: .normal, text: string)
  199. appearanceScaleItems.append(item)
  200. }
  201. appearanceScaleSelect.updateMenuItemsArr(appearanceScaleItems)
  202. appearanceScaleSelect.delegate = self
  203. appearanceTopPageRadio.properties = ComponentCheckBoxProperty(size: .s, text: KMLocalizedString("At the top of the page"), checkboxType: .normal)
  204. appearanceTopPageRadio.setTarget(self, action: #selector(radioClicked(_:)))
  205. appearanceBottomPageRadio.properties = ComponentCheckBoxProperty(size: .s, text: KMLocalizedString("At the bottom of the page"), checkboxType: .normal)
  206. appearanceBottomPageRadio.setTarget(self, action: #selector(radioClicked(_:)))
  207. //Position
  208. positionLabel.stringValue = KMLocalizedString("Position (mm)")
  209. positionLabel.textColor = ComponentLibrary.shared.getComponentColorFromKey("colorText/2")
  210. positionLabel.font = ComponentLibrary.shared.getFontFromKey("mac/body-s-medium")
  211. positionItemView.properties = ComponentCPositionProperty(rowCount: 3, columnCount: 3, dash: false, selRow: 1, selColumn: 1)
  212. positionItemView.delegate = self
  213. positionXInput.properties = ComponentInputNumberProperty(alignment: .left,
  214. size: .s,
  215. minSize: -1000,
  216. maxSize: 1000,
  217. text: "0")
  218. positionXInput.delegate = self
  219. positionYInput.properties = ComponentInputNumberProperty(alignment: .left,
  220. size: .s,
  221. minSize: -1000,
  222. maxSize: 1000,
  223. text: "0")
  224. positionYInput.delegate = self
  225. positionTileCheckbox.properties = ComponentCheckBoxProperty(size: .s, text: KMLocalizedString("Tile"), checkboxType: .normal)
  226. positionTileCheckbox.setTarget(self, action: #selector(checkBoxClicked(_:)))
  227. positionTileHoriInput.properties = ComponentInputNumberProperty(alignment: .left,
  228. size: .s,
  229. minSize: 0,
  230. maxSize: 1000,
  231. text: "0")
  232. positionTileHoriInput.delegate = self
  233. positionTileVertInput.properties = ComponentInputNumberProperty(alignment: .left,
  234. size: .s,
  235. minSize: 0,
  236. maxSize: 1000,
  237. text: "0")
  238. positionTileVertInput.delegate = self
  239. //Save
  240. saveTemplateBGView.wantsLayer = true
  241. saveTemplateBGView.layer?.backgroundColor = ComponentLibrary.shared.getComponentColorFromKey("colorBg/layout-middle").cgColor
  242. saveButton.properties = ComponentButtonProperty(type: .default_tertiary, size: .m, showLeftIcon: true, buttonText: KMLocalizedString("Save as Template"), icon: NSImage(named: "icon_wm_template_save"), keepPressState: false)
  243. saveButton.setTarget(self, action: #selector(saveButtonClicked(_:)))
  244. }
  245. func refreshScrollView() {
  246. infoScrollView.contentViewSize = CGSizeMake(264, 672)
  247. if watermarkData.watermarkType == .text {
  248. infoScrollView.contentViewSize = CGSizeMake(264, 672)
  249. } else if watermarkData.watermarkType == .image {
  250. infoScrollView.contentViewSize = CGSizeMake(264, 512)
  251. }
  252. infoScrollView.scrollToTop()
  253. }
  254. func reloadData() {
  255. titleLabel.stringValue = KMLocalizedString("Add Watermark")
  256. leftTopButton.isHidden = true
  257. saveTemplateBGView.isHidden = false
  258. templateButton.properties.icon = NSImage(named: "icon_wm_template")
  259. typeTabsBGView.isHidden = false
  260. infoScrollTopConst.constant = 56
  261. if editSubType == .edit {
  262. typeTabsBGView.isHidden = true
  263. infoScrollTopConst.constant = 8
  264. titleLabel.stringValue = KMLocalizedString("Edit Template")
  265. leftTopButton.isHidden = false
  266. saveTemplateBGView.isHidden = true
  267. templateButton.properties.icon = NSImage(named: "edit_save")
  268. }
  269. templateButton.reloadData()
  270. if self.isInBatchMode {
  271. infoContendBottomConst.constant = 0
  272. saveTemplateBGView.isHidden = true
  273. } else {
  274. infoContendBottomConst.constant = 72
  275. saveTemplateBGView.isHidden = false
  276. }
  277. fileBGView.isHidden = true
  278. textBGView.isHidden = true
  279. textTabProperty.state = .normal
  280. fileTabProperty.state = .normal
  281. if watermarkData.watermarkType == .text {
  282. textBGView.isHidden = false
  283. appearanceBGTopConst.constant = 200
  284. textTabProperty.state = .pressed
  285. } else if watermarkData.watermarkType == .image {
  286. fileBGView.isHidden = false
  287. appearanceBGTopConst.constant = 48
  288. fileTabProperty.state = .pressed
  289. }
  290. typeTabs.refreshItems()
  291. //Text
  292. text_textareaView.properties.text = watermarkData.text ?? ""
  293. text_textareaView.reloadData()
  294. if let index = familyNames.firstIndex(of: watermarkData.fontName) {
  295. fontNameSelect.selectItemAtIndex(index)
  296. }
  297. fontNameSelect.properties.text = watermarkData.fontName
  298. fontNameSelect.reloadData()
  299. let styleNames = CPDFFont.fontNames(forFamilyName: watermarkData.fontName)
  300. var menuItemArr: [ComponentMenuitemProperty] = []
  301. for string in styleNames {
  302. let item = ComponentMenuitemProperty(type: .normal, text: string, identifier: string)
  303. menuItemArr.append(item)
  304. }
  305. fontStyleSelect.updateMenuItemsArr(menuItemArr)
  306. if watermarkData.fontStyle == nil {
  307. fontStyleSelect.selectItemAtIndex(0)
  308. watermarkData.fontStyle = styleNames.first
  309. } else {
  310. fontStyleSelect.properties.text = watermarkData.fontStyle
  311. fontStyleSelect.reloadData()
  312. }
  313. positionTileCheckbox.properties.isDisabled = false
  314. let fontSizeStr = String(format: "%.0f", watermarkData.fontSize)
  315. if let index = KMWatermarkManager.getFontSize().firstIndex(of: fontSizeStr) {
  316. fontSizeSelect.selectItemAtIndex(index)
  317. }
  318. fontSizeSelect.properties.text = String(format: "%.0f", watermarkData.fontSize) + " pt"
  319. fontSizeSelect.properties.isDisabled = false
  320. if watermarkData.isScale {
  321. fontSizeSelect.properties.isDisabled = true
  322. positionTileCheckbox.properties.isDisabled = true
  323. watermarkData.isTilePage = false
  324. }
  325. fontSizeSelect.reloadData()
  326. fontColorGroup.currentColor = watermarkData.textColor
  327. fontColorGroup.refreshUI()
  328. //File
  329. fileInputView.properties.text = watermarkData.imagePath ?? ""
  330. fileInputView.reloadData()
  331. //Appearance
  332. appearance_RotateSelect.properties.text = String(format: "%.0f", watermarkData.rotation) + "°"
  333. appearance_RotateSelect.reloadData()
  334. if watermarkData.opacity > 1 {
  335. watermarkData.opacity = 1
  336. }
  337. appearance_OpacitySelect.properties.text = String(format: "%.0f", watermarkData.opacity*100) + "%"
  338. appearance_OpacitySelect.reloadData()
  339. appearanceScaleCheckbox.properties.checkboxType = watermarkData.isScale ? .selected : .normal
  340. appearanceScaleCheckbox.reloadData()
  341. appearanceScaleSelect.properties.isDisabled = watermarkData.isScale ? false : true
  342. appearanceScaleSelect.properties.text = String(format: "%.0f", watermarkData.scale*100) + "%"
  343. appearanceScaleSelect.reloadData()
  344. appearanceTopPageRadio.properties.checkboxType = watermarkData.isFront ? .selected : .normal
  345. appearanceTopPageRadio.reloadData()
  346. appearanceBottomPageRadio.properties.checkboxType = watermarkData.isFront ? .normal : .selected
  347. appearanceBottomPageRadio.reloadData()
  348. //Position
  349. positionXInput.properties.text = String(format: "%.0f", watermarkData.tx)
  350. positionXInput.reloadData()
  351. positionYInput.properties.text = String(format: "%.0f", watermarkData.ty)
  352. positionYInput.reloadData()
  353. positionTileHoriInput.properties.text = String(format: "%.0f", watermarkData.horizontalSpacing)
  354. positionTileVertInput.properties.text = String(format: "%.0f", watermarkData.verticalSpacing)
  355. if watermarkData.isTilePage {
  356. positionTileHorImage.image = NSImage(named: "tile_spacing_horiz")
  357. positionTileVertImage.image = NSImage(named: "tile_spacing_vert")
  358. positionTileHoriInput.properties.isDisabled = false
  359. positionTileVertInput.properties.isDisabled = false
  360. } else {
  361. positionTileHorImage.image = NSImage(named: "tile_spacing_horiz_dis")
  362. positionTileVertImage.image = NSImage(named: "tile_spacing_vert_dis")
  363. positionTileHoriInput.properties.isDisabled = true
  364. positionTileVertInput.properties.isDisabled = true
  365. }
  366. positionTileHoriInput.reloadData()
  367. positionTileVertInput.reloadData()
  368. positionTileCheckbox.properties.checkboxType = watermarkData.isTilePage ? .selected : .normal
  369. positionTileCheckbox.reloadData()
  370. saveButton.properties.isDisabled = false
  371. if watermarkData.watermarkType == .text {
  372. if watermarkData.text?.count == 0 {
  373. saveButton.properties.isDisabled = true
  374. }
  375. } else if watermarkData.watermarkType == .image {
  376. if watermarkData.imagePath == nil {
  377. saveButton.properties.isDisabled = true
  378. }
  379. }
  380. saveButton.reloadData()
  381. }
  382. func clearData() {
  383. watermarkData = KMPDFWatermarkData()
  384. reloadData()
  385. }
  386. //MARK: - Action
  387. @objc func leftTopButtonClicked(_ sender: ComponentButton) {
  388. if sender == leftTopButton {
  389. var isChanged = false
  390. if let dict = self.originalDataDict {
  391. isChanged = KMWatermarkManager.compareIsChangedModel(watermarkData, withDict: dict as NSDictionary)
  392. }
  393. if isChanged == true {
  394. let alert = NSAlert()
  395. alert.alertStyle = .critical
  396. alert.messageText = KMLocalizedString("Save template changes?")
  397. alert.informativeText = KMLocalizedString("Cancel and they will not be saved.")
  398. alert.addButton(withTitle: KMLocalizedString("Save"))
  399. alert.addButton(withTitle: KMLocalizedString("Cancel"))
  400. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  401. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  402. self.templateButtonClicked(self.templateButton)
  403. } else {
  404. if let dict = self.originalDataDict {
  405. KMWatermarkManager.defaultManager.setDictToWatermarK(dict: dict as NSDictionary, self.watermarkData)
  406. let _ = KMWatermarkManager.defaultManager.updateWatermark(watermark: self.watermarkData)
  407. }
  408. self.delegate?.watermarkPropertyControllerCancelTemplateEdit?(self)
  409. }
  410. }
  411. } else {
  412. delegate?.watermarkPropertyControllerCancelTemplateEdit?(self)
  413. }
  414. }
  415. }
  416. @objc func templateButtonClicked(_ sender: ComponentButton) {
  417. if editSubType == .edit {
  418. let _ = KMWatermarkManager.defaultManager.updateWatermark(watermark: watermarkData)
  419. delegate?.watermarkPropertyControllerSaveTemplateSuccess?(self, self.watermarkData)
  420. } else {
  421. if watermarkData.watermarkType == .image, let _ = watermarkData.imagePath {
  422. watermarkData.text = nil
  423. watermarkData.watermarkType = .image
  424. } else {
  425. watermarkData.watermarkType = .text
  426. watermarkData.imagePath = nil
  427. }
  428. delegate?.watermarkPropertyControllerDidChangetoTemplate?(self)
  429. }
  430. }
  431. @objc func checkBoxClicked(_ sender: ComponentCheckBox) {
  432. if sender == appearanceScaleCheckbox {
  433. watermarkData.isScale = appearanceScaleCheckbox.properties.checkboxType == .selected ? true : false
  434. } else if sender == positionTileCheckbox {
  435. watermarkData.isTilePage = positionTileCheckbox.properties.checkboxType == .selected ? true : false
  436. }
  437. reloadData()
  438. delegate?.watermarkPropertyControllerDidUpdate?(self)
  439. }
  440. @objc func radioClicked(_ sender: ComponentRadio) {
  441. if sender == appearanceTopPageRadio {
  442. watermarkData.isFront = true
  443. } else if sender == appearanceBottomPageRadio {
  444. watermarkData.isFront = false
  445. }
  446. reloadData()
  447. delegate?.watermarkPropertyControllerDidUpdate?(self)
  448. }
  449. @objc func saveButtonClicked(_ sender: ComponentButton) {
  450. let saveWindow: KMWatermarkSaveWindow = KMWatermarkSaveWindow(windowNibName: "KMWatermarkSaveWindow")
  451. if watermarkData.watermarkType == .image {
  452. saveWindow.nameValue = watermarkData.imagePath?.lastPathComponent ?? ""
  453. } else if watermarkData.watermarkType == .text {
  454. saveWindow.nameValue = watermarkData.text ?? ""
  455. }
  456. saveWindow.saveHandler = {[weak self] string in
  457. guard let weakSelf = self else { return }
  458. DispatchQueue.main.async {
  459. weakSelf.watermarkData.watermarkName = string ?? ""
  460. if KMWatermarkManager.defaultManager.addWatermark(watermark: weakSelf.watermarkData) == true {
  461. weakSelf.delegate?.watermarkPropertyControllerSaveTemplateSuccess?(weakSelf, weakSelf.watermarkData)
  462. }
  463. }
  464. }
  465. saveWindow.own_beginSheetModal(for: view.window) { string in
  466. }
  467. }
  468. @objc func chooseURLAction(_ sender: NSView) {
  469. self.chooseURLAction(sender, nil)
  470. }
  471. func chooseURLAction(_ sender: NSView, _ filePath: String? = nil) {
  472. let openPanel = NSOpenPanel()
  473. openPanel.canChooseDirectories = false
  474. openPanel.canChooseFiles = true
  475. openPanel.allowsMultipleSelection = false
  476. openPanel.allowedFileTypes = ["jpg", "jpeg", "png", "pdf"]
  477. openPanel.beginSheetModal(for: self.view.window!) { (result) in
  478. if result == NSApplication.ModalResponse.OK {
  479. guard let url = openPanel.url else { return }
  480. let filePath = url.path
  481. let outFolder = KMWatermarkManager.defaultManager.watermarkImageFolder
  482. let fileName = filePath.getLastComponentDeleteExtension
  483. if filePath.extension.lowercased() == ".pdf" {
  484. let pdf = CPDFDocument(url: url)
  485. guard !pdf!.isEncrypted else { return }
  486. if let image = self.generateThumbnail(for: url) {
  487. if let outFolderPath = outFolder?.stringByAppendingPathComponent(fileName + ".png") {
  488. try?image.pngData()?.write(to: URL(fileURLWithPath: outFolderPath))
  489. if FileManager.default.fileExists(atPath: outFolderPath) {
  490. self.watermarkData.imagePath = outFolderPath
  491. }
  492. self.delegate?.watermarkPropertyControllerDidUpdate?(self)
  493. self.reloadData()
  494. }
  495. }
  496. } else {
  497. let image = NSImage(contentsOfFile: url.path)
  498. if image == nil || NSImage.isDamageImage(image, imagePath: url.path) {
  499. let alert = NSAlert()
  500. alert.alertStyle = .critical
  501. alert.messageText = "The file \"\(url.lastPathComponent)\" could not be opened."
  502. alert.informativeText = "It may be damaged or use a file format that PDF Reader Pro doesn’t recognize."
  503. alert.addButton(withTitle: "Cancel")
  504. alert.beginSheetModal(for: NSApp.mainWindow!) { (response) in
  505. if response == NSApplication.ModalResponse.alertFirstButtonReturn {
  506. // Cancel button clicked
  507. }
  508. }
  509. return
  510. }
  511. if let resultPath = outFolder?.stringByAppendingPathComponent(fileName + ".png") {
  512. try?FileManager.default.copyItem(atPath: url.path, toPath: resultPath)
  513. self.watermarkData.imagePath = resultPath
  514. }
  515. self.delegate?.watermarkPropertyControllerDidUpdate?(self)
  516. self.reloadData()
  517. }
  518. }
  519. }
  520. }
  521. func generateThumbnail(for pdfURL: URL) -> NSImage? {
  522. // 创建PDF文档
  523. guard let pdfDocument = CGPDFDocument(pdfURL as CFURL),
  524. let pdfPage = pdfDocument.page(at: 1) else {
  525. print("打开PDF文件失败")
  526. return nil
  527. }
  528. // 获取页面尺寸
  529. let pageRect = pdfPage.getBoxRect(.mediaBox)
  530. // 创建图形上下文
  531. let size = NSSize(width: 200, height: 300)
  532. let bitsPerComponent = 8
  533. let bytesPerPixel = 4
  534. let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue
  535. let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height), bitsPerComponent: bitsPerComponent, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: bitmapInfo)
  536. // 绘制PDF页面
  537. context?.saveGState()
  538. context?.translateBy(x: 0, y: size.height)
  539. context?.scaleBy(x: 1.0, y: -1.0) // 反转坐标系
  540. context?.scaleBy(x: size.width / pageRect.width, y: size.height / pageRect.height) // 缩放
  541. context?.drawPDFPage(pdfPage)
  542. context?.restoreGState()
  543. // 创建NSImage
  544. if let cgImage = context?.makeImage() {
  545. return NSImage(cgImage: cgImage, size: NSSize(width: size.width, height: size.height))
  546. } else {
  547. return nil
  548. }
  549. }
  550. //MARK: - Mouse
  551. override func mouseDown(with event: NSEvent) {
  552. super.mouseDown(with: event)
  553. view.window?.makeFirstResponder(nil)
  554. }
  555. }
  556. //MARK: - ComponentTabsDelegate
  557. extension KMNWatermarkPropertyController: ComponentTabsDelegate {
  558. func componentTabsDidSelected(_ view: ComponentTabs, _ property: ComponentTabsProperty) {
  559. if property == textTabProperty {
  560. if watermarkData.watermarkType != .text {
  561. delegate?.watermarkPropertyControllerDidRemoveWatermark?(self, .text)
  562. }
  563. watermarkData.watermarkType = .text
  564. } else if property == fileTabProperty {
  565. if watermarkData.watermarkType != .image {
  566. delegate?.watermarkPropertyControllerDidRemoveWatermark?(self, .image)
  567. }
  568. watermarkData.watermarkType = .image
  569. }
  570. reloadData()
  571. delegate?.watermarkPropertyControllerDidUpdate?(self)
  572. refreshScrollView()
  573. }
  574. }
  575. //MARK: - ComponentTextareaDelegate
  576. extension KMNWatermarkPropertyController: ComponentTextareaDelegate {
  577. func componentTextareaTextDidChange(_ view: ComponentTextarea) {
  578. watermarkData.text = view.properties.text
  579. delegate?.watermarkPropertyControllerDidUpdate?(self)
  580. }
  581. func componentTextareaTextDidEndEditing(_ view: ComponentTextarea) {
  582. watermarkData.text = view.properties.text
  583. delegate?.watermarkPropertyControllerDidUpdate?(self)
  584. }
  585. }
  586. //MARK: - ComponentCColorDelegate
  587. extension KMNWatermarkPropertyController: ComponentCColorDelegate {
  588. func componentCColorDidChooseColor(_ view: NSView, _ color: NSColor?) {
  589. if view == fontColorGroup {
  590. watermarkData.textColor = color ?? NSColor.clear
  591. }
  592. reloadData()
  593. delegate?.watermarkPropertyControllerDidUpdate?(self)
  594. }
  595. }
  596. //MARK: - ComponentSelectDelegate
  597. extension KMNWatermarkPropertyController: ComponentSelectDelegate {
  598. func componentSelectDidSelect(view: ComponentSelect?, menuItemProperty: ComponentMenuitemProperty?) {
  599. if view == fontNameSelect {
  600. watermarkData.fontName = menuItemProperty?.text ?? "Helvetica"
  601. watermarkData.fontStyle = nil
  602. } else if view == fontStyleSelect {
  603. watermarkData.fontStyle = menuItemProperty?.text
  604. } else if view == fontSizeSelect {
  605. if let text = menuItemProperty?.text {
  606. let result = text.stringByDeleteCharString(" pt")
  607. watermarkData.fontSize = result.stringToCGFloat()
  608. }
  609. } else if view == appearance_OpacitySelect {
  610. if let text = menuItemProperty?.text {
  611. let result = text.stringByDeleteCharString("%")
  612. watermarkData.opacity = result.stringToCGFloat()/100
  613. }
  614. } else if view == appearance_RotateSelect {
  615. if let text = menuItemProperty?.text {
  616. let result = text.stringByDeleteCharString("°")
  617. watermarkData.rotation = result.stringToCGFloat()
  618. }
  619. } else if view == appearanceScaleSelect {
  620. if let text = menuItemProperty?.text {
  621. let result = text.stringByDeleteCharString("%")
  622. watermarkData.scale = result.stringToCGFloat()/100
  623. }
  624. }
  625. reloadData()
  626. delegate?.watermarkPropertyControllerDidUpdate?(self)
  627. }
  628. func componentSelectTextDidChange(_ view: ComponentSelect) {
  629. if view == fontSizeSelect {
  630. if let string = view.properties.text {
  631. let size = string.stringToCGFloat()
  632. watermarkData.fontSize = size
  633. delegate?.watermarkPropertyControllerDidUpdate?(self)
  634. }
  635. }
  636. }
  637. func componentSelectTextDidEndEditing(_ view: ComponentSelect) {
  638. if view == fontSizeSelect {
  639. if let string = view.properties.text {
  640. let result = string.stringByDeleteCharString(" pt")
  641. let size = result.stringToCGFloat()
  642. watermarkData.fontSize = size
  643. }
  644. } else if view == appearance_OpacitySelect {
  645. if let text = appearance_OpacitySelect.properties.text {
  646. let result = text.stringByDeleteCharString("%")
  647. watermarkData.opacity = result.stringToCGFloat()/100
  648. }
  649. } else if view == appearance_RotateSelect {
  650. if let text = appearance_RotateSelect.properties.text {
  651. let result = text.stringByDeleteCharString("°")
  652. watermarkData.rotation = result.stringToCGFloat()
  653. }
  654. } else if view == appearanceScaleSelect {
  655. if let text = appearanceScaleSelect.properties.text {
  656. let result = text.stringByDeleteCharString("%")
  657. watermarkData.scale = result.stringToCGFloat()/100
  658. }
  659. }
  660. reloadData()
  661. delegate?.watermarkPropertyControllerDidUpdate?(self)
  662. }
  663. }
  664. //MARK: - ComponentCPositionDelegate
  665. extension KMNWatermarkPropertyController: ComponentCPositionDelegate {
  666. func componentCPositionDidChoose(_ view: NSView, _ row: Int, _ column: Int) {
  667. if view == positionItemView {
  668. if row == 0 {
  669. watermarkData.verticalPosition = .bottom
  670. } else if row == 1 {
  671. watermarkData.verticalPosition = .center
  672. } else if row == 2 {
  673. watermarkData.verticalPosition = .top
  674. }
  675. if column == 0 {
  676. watermarkData.horizontalPosition = .left
  677. } else if column == 1 {
  678. watermarkData.horizontalPosition = .center
  679. } else if column == 2 {
  680. watermarkData.horizontalPosition = .right
  681. }
  682. }
  683. reloadData()
  684. delegate?.watermarkPropertyControllerDidUpdate?(self)
  685. }
  686. }
  687. //MARK: - ComponentInputNumberDelegate
  688. extension KMNWatermarkPropertyController: ComponentInputNumberDelegate {
  689. func componentInputNumberDidValueChanged(inputNumber: ComponentInputNumber?) {
  690. if inputNumber == positionXInput {
  691. if let text = inputNumber?.properties.text {
  692. watermarkData.tx = text.stringToCGFloat()
  693. }
  694. } else if inputNumber == positionYInput {
  695. if let text = inputNumber?.properties.text {
  696. watermarkData.ty = text.stringToCGFloat()
  697. }
  698. } else if inputNumber == positionTileHoriInput {
  699. if let text = inputNumber?.properties.text {
  700. watermarkData.horizontalSpacing = text.stringToCGFloat()
  701. }
  702. } else if inputNumber == positionTileVertInput {
  703. if let text = inputNumber?.properties.text {
  704. watermarkData.verticalSpacing = text.stringToCGFloat()
  705. }
  706. }
  707. reloadData()
  708. delegate?.watermarkPropertyControllerDidUpdate?(self)
  709. }
  710. }
  711. //MARK: - ComponentInputDelegate
  712. extension KMNWatermarkPropertyController: ComponentInputDelegate {
  713. func componentInputDidCoverButtonClicked(inputView: ComponentInput) {
  714. if inputView.properties.text.count > 0 && inputView.properties.creatable == false {
  715. self.chooseURLAction(inputView, inputView.properties.text)
  716. }
  717. }
  718. }