KMAddBackgroundView.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912
  1. //
  2. // KMAddBackgroundView.swift
  3. // PDF Master
  4. //
  5. // Created by lizhe on 2023/11/14.
  6. //
  7. import Cocoa
  8. enum KMBackgroundManagerType: Int {
  9. case add = 0
  10. case edit
  11. case use
  12. }
  13. typealias KMAddBackgroundViewOperateCallBack = (_ background: KMBackgroundModel, _ countType: Int) -> ()
  14. typealias KMAddBackgroundViewBatchAction = (_ view: KMAddBackgroundView, _ files: [KMFileAttribute]) -> Void
  15. typealias KMAddBackgroundViewCancelAction = (_ view: KMAddBackgroundView) -> Void
  16. class KMAddBackgroundView: KMBaseXibView, NSComboBoxDelegate {
  17. @IBOutlet weak var pdfView: KMWatermarkPDFView!
  18. @IBOutlet weak var previousButton: NSButton!
  19. @IBOutlet weak var nextButton: NSButton!
  20. @IBOutlet weak var currentPageIndexTextField: NSTextField!
  21. @IBOutlet weak var totalPageCountlabel: NSTextField!
  22. @IBOutlet weak var typeBox: NSBox!
  23. @IBOutlet weak var colorButton: NSButton!
  24. @IBOutlet weak var colorWell: NSColorWell!
  25. @IBOutlet weak var fileButton: NSButton!
  26. @IBOutlet weak var filePathLabel: NSTextField!
  27. @IBOutlet weak var browseButton: NSButton!
  28. @IBOutlet weak var ratioLabel: NSTextField!
  29. @IBOutlet weak var ratioTextField: NSTextField!
  30. @IBOutlet weak var ratioStepper: NSStepper!
  31. @IBOutlet weak var appearanceBox: NSBox!
  32. @IBOutlet weak var angleLabel: NSTextField!
  33. @IBOutlet weak var angleTextField: NSTextField!
  34. @IBOutlet weak var angleStepper: NSStepper!
  35. @IBOutlet weak var left45IndicateView: KMAngleIndicateView!
  36. @IBOutlet weak var horizontalIndicateView: KMAngleIndicateView!
  37. @IBOutlet weak var right45IndicateView: KMAngleIndicateView!
  38. @IBOutlet weak var alphaLabel: NSTextField!
  39. @IBOutlet weak var alphaSlider: NSSlider!
  40. @IBOutlet weak var alphaTextField: NSTextField!
  41. @IBOutlet weak var alphaStepper: NSStepper!
  42. @IBOutlet weak var postionView: KMPostionIndicateView!
  43. @IBOutlet weak var verticalGapLabel: NSTextField!
  44. @IBOutlet weak var verticalGapTextField: NSTextField!
  45. @IBOutlet weak var verticalStepper: NSStepper!
  46. @IBOutlet weak var horizontalGapLabel: NSTextField!
  47. @IBOutlet weak var horizontalGapTextField: NSTextField!
  48. @IBOutlet weak var horizontalStepper: NSStepper!
  49. @IBOutlet weak var pageRangeComboBox: NSComboBox!
  50. @IBOutlet weak var pageRangeLabel: NSTextField!
  51. @IBOutlet weak var saveToTemplateButton: NSButton!
  52. @IBOutlet weak var templateNameLabel: NSTextField!
  53. @IBOutlet weak var templateNameTextField: NSTextField!
  54. @IBOutlet weak var doneButton: NSButton!
  55. @IBOutlet weak var cancelButton: NSButton!
  56. @IBOutlet weak var batchButton: NSButton!
  57. var isHiddenBatchBtn: Bool = false
  58. lazy var background: KMBackgroundModel = {
  59. var bg = KMBackgroundModel()
  60. bg.type = .color
  61. bg.color = .red
  62. bg.opacity = 1.0
  63. bg.scale = 1.0
  64. bg.verticalMode = 1
  65. bg.horizontalMode = 1
  66. bg.backgroundID = KMBackgroundManager.defaultManager.fetchAvailableName()
  67. self.initialID = bg.backgroundID
  68. bg.pagesString = ""
  69. bg.pageRangeType = .all
  70. return bg
  71. }()
  72. var originalBackground: KMBackgroundModel = KMBackgroundModel()
  73. var filePath: String = Bundle.main.path(forResource: "Quick Start Guide", ofType: "pdf") ?? ""
  74. var password: String = ""
  75. var type: KMBackgroundManagerType = .use
  76. var pdfDocument: CPDFDocument? {
  77. didSet {
  78. self.pdfView.document = pdfDocument
  79. self.reloadData()
  80. }
  81. }
  82. var backgroundType: KMBackgroundType = .color
  83. var initialID: String!
  84. var currentType: Int = 0
  85. var cancelAction: KMAddBackgroundViewCancelAction?
  86. var batchAction: KMAddBackgroundViewCancelAction?
  87. var operateCallBack: KMAddBackgroundViewOperateCallBack?
  88. var onlyManagerTemplate: Bool = true
  89. // MARK: - Dealloc
  90. deinit {
  91. NotificationCenter.default.removeObserver(self)
  92. }
  93. // MARK: - Init Methods
  94. convenience init?(baseFile filePath: String, background backgroundObject: KMBackgroundModel, password: String, type: KMBackgroundManagerType, fileType countType: Int) {
  95. self.init()
  96. self.filePath = filePath
  97. self.password = password
  98. self.background = backgroundObject
  99. self.originalBackground = backgroundObject
  100. self.initialID = backgroundObject.backgroundID
  101. self.type = type
  102. self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: self.filePath))
  103. if pdfDocument!.isLocked {
  104. pdfDocument!.unlock(withPassword: password)
  105. }
  106. if pdfDocument!.isLocked {
  107. return nil
  108. }
  109. }
  110. override func setup() {
  111. // pdfView.background = background
  112. // pdfView.document = pdfDocument
  113. pdfView.autoScales = true
  114. pdfView.setDisplay(.singlePage)
  115. // pdfView.documentView?.enclosingScrollView?.hasVerticalScroller = false
  116. // pdfView.documentView?.enclosingScrollView?.hasHorizontalScroller = false
  117. for i in 0..<3 {
  118. for j in 0..<3 {
  119. if i == Int(background.horizontalMode) && j == Int(background.verticalMode) {
  120. postionView.style = KMPositionIndicateViewStyle(rawValue: i + 3 * j)!
  121. }
  122. }
  123. }
  124. postionView.styleChangedCallBack = { [weak self] in
  125. guard let self = self else { return }
  126. self.background.horizontalMode = self.postionView.style.rawValue % 3
  127. self.background.verticalMode = self.postionView.style.rawValue / 3
  128. self.self.updatePDFView()
  129. if self.filePathLabel.stringValue.count > 0 {
  130. self.doneButton.isEnabled = true
  131. }
  132. }
  133. currentPageIndexTextField.stringValue = "1"
  134. // let numberFormatter = currentPageIndexTextField.formatter as! NumberFormatter
  135. // numberFormatter.maximum = NSNumber(value: pdfDocument.pageCount)
  136. left45IndicateView.style = .left45
  137. left45IndicateView.touchCallBack = { [weak self] in
  138. guard let self = self else { return }
  139. self.background.rotation = 45
  140. self.angleStepper.doubleValue = 45
  141. self.angleTextField.stringValue = "\(45)"
  142. self.checkAngle()
  143. if self.filePathLabel.stringValue.count > 0 {
  144. self.doneButton.isEnabled = true
  145. }
  146. self.updatePDFView()
  147. }
  148. horizontalIndicateView.style = .horizontal
  149. horizontalIndicateView.touchCallBack = { [weak self] in
  150. guard let self = self else { return }
  151. self.background.rotation = 0
  152. self.angleStepper.doubleValue = 0
  153. self.angleTextField.stringValue = "\(0)"
  154. self.checkAngle()
  155. if self.filePathLabel.stringValue.count > 0 {
  156. self.doneButton.isEnabled = true
  157. }
  158. self.updatePDFView()
  159. }
  160. right45IndicateView.style = .right45
  161. right45IndicateView.touchCallBack = { [weak self] in
  162. guard let self = self else { return }
  163. self.background.rotation = -45
  164. self.angleStepper.doubleValue = -45
  165. self.angleTextField.stringValue = "\(-45)"
  166. self.checkAngle()
  167. if self.filePathLabel.stringValue.count > 0 {
  168. self.doneButton.isEnabled = true
  169. }
  170. self.updatePDFView()
  171. }
  172. checkAngle()
  173. typeBox.titleFont = NSFont.systemFont(ofSize: 13)
  174. colorWell.color = background.color ?? NSColor.red
  175. templateNameTextField.stringValue = background.backgroundID
  176. appearanceBox.titleFont = NSFont.systemFont(ofSize: 13)
  177. saveToTemplateButton.isEnabled = onlyManagerTemplate
  178. // if type == .use {
  179. // saveToTemplateButton.isHidden = true
  180. // saveToTemplateButton.state = .off
  181. // } else {
  182. // saveToTemplateButton.isHidden = false
  183. // saveToTemplateButton.state = .on
  184. // }
  185. pageRangeComboBox.removeAllItems()
  186. pageRangeComboBox.addItems(withObjectValues: [
  187. NSLocalizedString("All Pages", comment: ""),
  188. NSLocalizedString("Odd Pages Only", comment: ""),
  189. NSLocalizedString("Even Pages Only", comment: ""),
  190. NSLocalizedString("e.g. 1,3-5,10", comment: "")
  191. ])
  192. pageRangeComboBox.placeholderString = NSLocalizedString("e.g. 1,3-5,10", comment: "")
  193. pageRangeComboBox.delegate = nil
  194. pageRangeComboBox.selectItem(at: 0)
  195. pageRangeComboBox.isEditable = false
  196. pageRangeComboBox.delegate = self
  197. }
  198. override func addNotification() {
  199. NotificationCenter.default.addObserver(self, selector: #selector(pageChangeNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.pdfView)
  200. }
  201. override func updateLanguage() {
  202. typeBox.title = NSLocalizedString("Source", comment: "")
  203. batchButton.title = NSLocalizedString("Batch", comment: "");
  204. cancelButton.title = NSLocalizedString("Cancel", comment: "");
  205. colorButton.title = NSLocalizedString("Color", comment: "")
  206. fileButton.title = NSLocalizedString("File", comment: "")
  207. browseButton.title = NSLocalizedString("Choose...", comment: "")
  208. ratioLabel.stringValue = "\(NSLocalizedString("Ratio", comment: "")):"
  209. appearanceBox.title = NSLocalizedString("Appearance", comment: "")
  210. angleLabel.stringValue = "\(NSLocalizedString("Rotation", comment: "")):"
  211. alphaLabel.stringValue = "\(NSLocalizedString("Opacity", comment: "")):"
  212. pageRangeLabel.stringValue = "\(NSLocalizedString("Page Range", comment: "")):"
  213. horizontalGapLabel.stringValue = "X:"
  214. verticalGapLabel.stringValue = "Y:"
  215. saveToTemplateButton.title = NSLocalizedString("Add to Template", comment: "")
  216. if (self.type == .add) {
  217. self.doneButton.title = NSLocalizedString("Apply", comment: "");
  218. self.batchButton.isHidden = true
  219. } else if (self.type == .edit) {
  220. self.doneButton.title = NSLocalizedString("Apply", comment: "");
  221. self.batchButton.isHidden = true
  222. } else if (self.type == .use) {
  223. self.doneButton.title = NSLocalizedString("Save & Apply", comment: "");
  224. }
  225. }
  226. private func checkAngle() {
  227. left45IndicateView.isSelcted = false
  228. horizontalIndicateView.isSelcted = false
  229. right45IndicateView.isSelcted = false
  230. if background.rotation == -45 {
  231. right45IndicateView.isSelcted = true
  232. } else if background.rotation == 0 {
  233. horizontalIndicateView.isSelcted = true
  234. } else if background.rotation == 45 {
  235. left45IndicateView.isSelcted = true
  236. }
  237. }
  238. override func reloadData() {
  239. guard let pdfDocument = pdfDocument else { return }
  240. totalPageCountlabel.stringValue = "/ \(pdfDocument.pageCount)"
  241. templateNameTextField.stringValue = background.backgroundID
  242. colorWell.color = background.color ?? NSColor.red
  243. filePathLabel.stringValue = background.imagePath
  244. filePathLabel.placeholderString = NSLocalizedString("Select a File", comment: "")
  245. angleStepper.doubleValue = Double(-background.rotation)
  246. angleTextField.stringValue = "\(angleStepper.doubleValue)"
  247. alphaSlider.doubleValue = background.opacity
  248. alphaStepper.doubleValue = background.opacity
  249. let opacity = round(background.opacity * 100) / 100
  250. alphaTextField.stringValue = "\(Int(opacity * 100))%"
  251. ratioStepper.doubleValue = background.scale
  252. ratioTextField.stringValue = "\(Int(background.scale * 100))%"
  253. if currentType == 0 {
  254. changeTypeBoxState(true)
  255. } else {
  256. changeTypeBoxState(false)
  257. }
  258. pageRangeComboBox.delegate = nil
  259. switch background.pageRangeType {
  260. case .all:
  261. pageRangeComboBox.isEditable = false
  262. pageRangeComboBox.selectItem(at: 0)
  263. case .odd:
  264. pageRangeComboBox.isEditable = false
  265. pageRangeComboBox.selectItem(at: 1)
  266. case .even:
  267. pageRangeComboBox.isEditable = false
  268. pageRangeComboBox.selectItem(at: 2)
  269. case .other:
  270. pageRangeComboBox.isEditable = true
  271. pageRangeComboBox.selectItem(at: 3)
  272. pageRangeComboBox.stringValue = background.pagesString
  273. window?.makeFirstResponder(pageRangeComboBox)
  274. }
  275. pageRangeComboBox.delegate = self
  276. verticalStepper.doubleValue = background.verticalSpace
  277. verticalGapTextField.stringValue = "\(verticalStepper.doubleValue)"
  278. horizontalStepper.doubleValue = background.horizontalSpace
  279. horizontalGapTextField.stringValue = "\(horizontalStepper.doubleValue)"
  280. batchButton.isHidden = isHiddenBatchBtn
  281. }
  282. private func changeTypeBoxState(_ isColor: Bool) {
  283. if isColor {
  284. currentType = 0
  285. colorButton.state = .on
  286. colorWell.isEnabled = true
  287. fileButton.state = .off
  288. browseButton.isEnabled = false
  289. ratioTextField.isEnabled = false
  290. ratioStepper.isEnabled = false
  291. background.color = colorWell.color
  292. background.type = .color
  293. background.scale = 1
  294. doneButton.isEnabled = true
  295. } else {
  296. currentType = 1
  297. colorButton.state = .off
  298. colorWell.isEnabled = false
  299. fileButton.state = .on
  300. browseButton.isEnabled = true
  301. ratioTextField.isEnabled = true
  302. ratioStepper.isEnabled = true
  303. background.color = nil
  304. background.type = .file
  305. background.scale = ratioStepper.doubleValue
  306. doneButton.isEnabled = filePathLabel.stringValue.count > 0
  307. }
  308. self.updatePDFView()
  309. }
  310. func updatePDFView() {
  311. // pdfView.needsDisplay = true
  312. // pdfView.layoutDocumentView()
  313. // pdfView.setNeedsDisplayForVisiblePages()
  314. let document = CPDFDocument(url: self.pdfDocument?.documentURL)
  315. guard let document = document else { return }
  316. document.unlock(withPassword: self.pdfDocument?.password)
  317. let tBackground: CPDFBackground = document.background()
  318. tBackground.opacity = background.opacity
  319. tBackground.scale = background.scale
  320. tBackground.rotation = CGFloat(-background.rotation)
  321. tBackground.horizontalAlignment = UInt(background.horizontalMode)
  322. tBackground.verticalAlignment = UInt(background.verticalMode)
  323. tBackground.xOffset = background.horizontalSpace
  324. tBackground.yOffset = background.verticalSpace
  325. if let color = background.color {
  326. tBackground.color = color
  327. tBackground.type = .color
  328. } else if background.imagePath.count != 0 {
  329. let image = NSImage(contentsOfFile: background.imagePath)!
  330. tBackground.setImage(image)
  331. tBackground.type = .image
  332. }
  333. if background.pagesString.count != 0 {
  334. tBackground.pageString = background.pagesString
  335. } else {
  336. let pageString = "0-\(document.pageCount - 1)"
  337. tBackground.pageString = pageString
  338. }
  339. tBackground.update()
  340. self.pdfView.document = document
  341. // // Save to temporary path
  342. // let documentPath = NSTemporaryDirectory()
  343. // let tempPath = (documentPath as NSString).appendingPathComponent((path as NSString).lastPathComponent)
  344. // try? FileManager.default.removeItem(atPath: tempPath)
  345. //
  346. // let result = document.write(to: URL(fileURLWithPath: tempPath))
  347. // if result {
  348. // if FileManager.default.fileExists(atPath: path) {
  349. // try? FileManager.default.removeItem(atPath: path)
  350. // }
  351. // try? FileManager.default.moveItem(atPath: tempPath, toPath: path)
  352. // } else {
  353. // try? FileManager.default.removeItem(atPath: tempPath)
  354. // }
  355. }
  356. // Other methods...
  357. @objc func controlTextDidEndEditing(_ notification: Notification) {
  358. guard let textField = notification.object as? NSTextField else { return }
  359. switch textField {
  360. case ratioTextField:
  361. let formatter = textField.formatter as? NumberFormatter
  362. if let floatValue = formatter?.number(from: textField.stringValue)?.floatValue {
  363. ratioStepper.doubleValue = Double(floatValue)
  364. background.scale = Double(floatValue)
  365. self.updatePDFView()
  366. }
  367. case angleTextField:
  368. if let integerValue = Int(textField.stringValue) {
  369. background.rotation = CGFloat(-integerValue)
  370. angleStepper.doubleValue = Double(-background.rotation)
  371. checkAngle()
  372. self.updatePDFView()
  373. }
  374. case alphaTextField:
  375. let formatter = textField.formatter as? NumberFormatter
  376. if let floatValue = formatter?.number(from: textField.stringValue)?.floatValue {
  377. alphaSlider.doubleValue = Double(floatValue)
  378. alphaStepper.doubleValue = Double(floatValue)
  379. background.opacity = Double(floatValue)
  380. self.updatePDFView()
  381. }
  382. case pageRangeComboBox:
  383. if pageRangeComboBox.indexOfSelectedItem == -1 {
  384. if !checkPageRangeValidate(pageRangeComboBox.stringValue) {
  385. let alert = NSAlert()
  386. alert.alertStyle = .critical
  387. alert.messageText = "\(pdfDocument!.documentURL.lastPathComponent) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  388. alert.runModal()
  389. window?.makeFirstResponder(pageRangeComboBox)
  390. return
  391. } else {
  392. background.pagesString = pageRangeComboBox.stringValue
  393. self.updatePDFView()
  394. }
  395. }
  396. case verticalGapTextField:
  397. if let integerValue = Int(verticalGapTextField.stringValue) {
  398. background.verticalSpace = CGFloat(integerValue)
  399. verticalStepper.doubleValue = background.verticalSpace
  400. self.updatePDFView()
  401. }
  402. case horizontalGapTextField:
  403. if let integerValue = Int(horizontalGapTextField.stringValue) {
  404. background.horizontalSpace = CGFloat(integerValue)
  405. horizontalStepper.doubleValue = background.horizontalSpace
  406. self.updatePDFView()
  407. }
  408. case currentPageIndexTextField:
  409. if let pageIndex = Int(currentPageIndexTextField.stringValue), let page = pdfDocument!.page(at: UInt(pageIndex - 1)) {
  410. pdfView.go(to: page)
  411. }
  412. default:
  413. break
  414. }
  415. if filePathLabel.stringValue.count > 0 {
  416. doneButton.isEnabled = true
  417. }
  418. }
  419. @objc func comboBoxSelectionDidChange(_ notification: Notification) {
  420. guard notification.object as? NSComboBox == pageRangeComboBox else { return }
  421. pageRangeComboBox.isEditable = false
  422. switch pageRangeComboBox.indexOfSelectedItem {
  423. case 0:
  424. background.pageRangeType = .all
  425. case 1:
  426. background.pageRangeType = .odd
  427. case 2:
  428. background.pageRangeType = .even
  429. default:
  430. background.pageRangeType = .other
  431. pageRangeComboBox.stringValue = ""
  432. pageRangeComboBox.isEditable = true
  433. window?.makeFirstResponder(pageRangeComboBox)
  434. }
  435. if filePathLabel.stringValue.count > 0 {
  436. doneButton.isEnabled = true
  437. }
  438. }
  439. func checkPageRangeValidate(_ pageRangeString: String) -> Bool {
  440. let fileAttribute = KMFileAttribute()
  441. fileAttribute.filePath = pdfDocument!.documentURL.path
  442. fileAttribute.bAllPage = false
  443. fileAttribute.pagesString = pageRangeComboBox.stringValue
  444. return fileAttribute.fetchSelectPages().count != 0
  445. }
  446. func saveAsPDF(with background: KMBackgroundModel, to path: String, autoOpen: Bool) {
  447. DispatchQueue.global(qos: .default).async { [unowned self] in
  448. var filePath = self.pdfDocument!.documentURL?.path
  449. let password = self.password
  450. if filePath == nil {
  451. let writeSuccess = self.pdfDocument!.write(to: URL(fileURLWithPath: kNewDocumentTempSavePath(NSLocalizedString("Untitled", comment: ""))))
  452. if writeSuccess {
  453. self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: kNewDocumentTempSavePath(NSLocalizedString("Untitled", comment: ""))))!
  454. filePath = self.pdfDocument!.documentURL?.path
  455. }
  456. }
  457. let document = CPDFDocument(url: URL(fileURLWithPath: filePath!))!
  458. document.unlock(withPassword: password)
  459. let tBackground: CPDFBackground = document.background()
  460. tBackground.opacity = background.opacity
  461. tBackground.scale = background.scale
  462. tBackground.rotation = CGFloat(-background.rotation)
  463. tBackground.horizontalAlignment = UInt(background.horizontalMode)
  464. tBackground.verticalAlignment = UInt(background.verticalMode)
  465. tBackground.xOffset = background.horizontalSpace
  466. tBackground.yOffset = background.verticalSpace
  467. if let color = background.color {
  468. tBackground.color = color
  469. tBackground.type = .color
  470. } else if background.imagePath.count != 0 {
  471. let image = NSImage(contentsOfFile: background.imagePath)!
  472. tBackground.setImage(image)
  473. tBackground.type = .image
  474. }
  475. if background.pagesString.count != 0 {
  476. tBackground.pageString = background.pagesString
  477. } else {
  478. let pageString = "0-\(document.pageCount - 1)"
  479. tBackground.pageString = pageString
  480. }
  481. tBackground.update()
  482. // Save to temporary path
  483. let documentPath = NSTemporaryDirectory()
  484. let tempPath = (documentPath as NSString).appendingPathComponent((path as NSString).lastPathComponent)
  485. try? FileManager.default.removeItem(atPath: tempPath)
  486. let result = document.write(to: URL(fileURLWithPath: tempPath))
  487. if result {
  488. if FileManager.default.fileExists(atPath: path) {
  489. try? FileManager.default.removeItem(atPath: path)
  490. }
  491. try? FileManager.default.moveItem(atPath: tempPath, toPath: path)
  492. } else {
  493. try? FileManager.default.removeItem(atPath: tempPath)
  494. }
  495. if result {
  496. DispatchQueue.main.async {
  497. let needSave = self.saveToTemplateButton.state == .on
  498. if needSave {
  499. if self.checkPageRangeValidate(self.pageRangeComboBox.stringValue) && self.pageRangeComboBox.indexOfSelectedItem == -1 {
  500. self.background.pagesString = self.pageRangeComboBox.stringValue
  501. }
  502. KMBackgroundManager.defaultManager.addTemplate(model: self.background)
  503. NotificationCenter.default.post(name: NSNotification.Name("KMBatchOperateWatermarksNotification"), object: self)
  504. }
  505. self.cancelAction?(self)
  506. if autoOpen {
  507. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { _, _, _ in }
  508. } else {
  509. NSWorkspace.shared.selectFile(path, inFileViewerRootedAtPath: "")
  510. }
  511. }
  512. }
  513. }
  514. }
  515. static func saveAsPDFRemoveAllBackground(PDFDocument: CPDFDocument, password: String?, toPath path: String, completionHandler handler: ((Int) -> Void)?) {
  516. DispatchQueue.global(qos: .default).async {
  517. guard let filePath = PDFDocument.documentURL?.path else {
  518. return
  519. }
  520. let document = CPDFDocument(url: URL(fileURLWithPath: filePath))
  521. if let password = password {
  522. document?.unlock(withPassword: password)
  523. }
  524. let tBackground: CPDFBackground = document!.background()
  525. tBackground.clear()
  526. // Save to a temporary path
  527. let documentPath = NSTemporaryDirectory()
  528. let tempPath = (documentPath as NSString).appendingPathComponent((path as NSString).lastPathComponent)
  529. if FileManager.default.fileExists(atPath: tempPath) {
  530. try? FileManager.default.removeItem(atPath: tempPath)
  531. }
  532. if let result = document?.write(to: URL(fileURLWithPath: tempPath)) {
  533. if FileManager.default.fileExists(atPath: path) {
  534. try? FileManager.default.removeItem(atPath: path)
  535. }
  536. try? FileManager.default.moveItem(atPath: tempPath, toPath: path)
  537. DispatchQueue.main.async {
  538. handler?(1)
  539. }
  540. } else {
  541. try? FileManager.default.removeItem(atPath: tempPath)
  542. DispatchQueue.main.async {
  543. handler?(0)
  544. }
  545. }
  546. }
  547. }
  548. func kNewDocumentTempSavePath(_ fileName: String) -> String {
  549. let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  550. let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  551. let append2 = append1!.stringByAppendingPathComponent(String(format: "%@", fileName))
  552. return append2
  553. }
  554. func isDamageImage(_ image: NSImage, imagePath path: String) -> Bool {
  555. let addImageAnnotation = (NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("addImageAnnotation")
  556. if !FileManager.default.fileExists(atPath: addImageAnnotation) {
  557. try? FileManager.default.createDirectory(atPath: addImageAnnotation, withIntermediateDirectories: false, attributes: nil)
  558. }
  559. let data = image.tiffRepresentation!
  560. let imageRep = NSBitmapImageRep(data: data)!
  561. imageRep.size = image.size
  562. var imageData: Data?
  563. if path.lowercased() == "png" {
  564. imageData = imageRep.representation(using: .png, properties: [:])
  565. } else {
  566. imageData = imageRep.representation(using: .jpeg, properties: [:])
  567. }
  568. let rPath = (addImageAnnotation as NSString).appendingPathComponent(tagString() + ".png")
  569. return ((try? imageData?.write(to: URL(fileURLWithPath: rPath), options: .atomic)) == nil)
  570. }
  571. func tagString() -> String {
  572. let dateFormatter = DateFormatter()
  573. dateFormatter.dateFormat = "yyMMddHHmmss"
  574. return String(format: "%@%04d", dateFormatter.string(from: Date()), arc4random() % 10000)
  575. }
  576. // ... (remaining methods)
  577. @objc func pageChangeNotification(notification: NSNotification) {
  578. currentPageIndexTextField.stringValue = "\(pdfView.currentPage().pageIndex() + 1)"
  579. }
  580. }
  581. extension KMAddBackgroundView {
  582. @IBAction func cancelButtonAction(_ sender: Any) {
  583. guard let callBack = cancelAction else { return }
  584. callBack(self)
  585. }
  586. @IBAction func buttonClicked_SwitchBackgroundType(_ sender: Any) {
  587. changeTypeBoxState(sender as? NSObject == colorButton)
  588. }
  589. @IBAction func colorWellChanged(_ sender: NSColorWell) {
  590. background.color = sender.color
  591. self.updatePDFView()
  592. }
  593. @IBAction func radioStepperAction(_ sender: NSStepper) {
  594. ratioTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  595. background.scale = sender.doubleValue
  596. self.updatePDFView()
  597. if filePathLabel.stringValue.count > 0 {
  598. doneButton.isEnabled = true
  599. }
  600. }
  601. @IBAction func angleStepperAction(_ sender: NSStepper) {
  602. angleTextField.stringValue = "\(sender.doubleValue)"
  603. background.rotation = CGFloat(Int(sender.doubleValue))
  604. checkAngle()
  605. self.updatePDFView()
  606. if filePathLabel.stringValue.count > 0 {
  607. doneButton.isEnabled = true
  608. }
  609. }
  610. @IBAction func alphaSliderAction(_ sender: NSSlider) {
  611. background.opacity = sender.doubleValue
  612. alphaStepper.doubleValue = sender.doubleValue
  613. alphaTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  614. if filePathLabel.stringValue.count > 0 {
  615. doneButton.isEnabled = true
  616. }
  617. self.updatePDFView()
  618. }
  619. @IBAction func verticalStepperAction(_ sender: NSStepper) {
  620. verticalGapTextField.stringValue = "\(sender.doubleValue)"
  621. background.verticalSpace = sender.doubleValue
  622. self.updatePDFView()
  623. if filePathLabel.stringValue.count > 0 {
  624. doneButton.isEnabled = true
  625. }
  626. }
  627. @IBAction func horizentalStepperAction(_ sender: NSStepper) {
  628. horizontalGapTextField.stringValue = "\(sender.doubleValue)"
  629. background.horizontalSpace = sender.doubleValue
  630. self.updatePDFView()
  631. if filePathLabel.stringValue.count > 0 {
  632. doneButton.isEnabled = true
  633. }
  634. }
  635. @IBAction func alphaSteperAction(_ sender: NSStepper) {
  636. alphaTextField.stringValue = "\(Int(sender.doubleValue * 100))%"
  637. background.opacity = sender.doubleValue
  638. alphaStepper.doubleValue = sender.doubleValue
  639. self.updatePDFView()
  640. if filePathLabel.stringValue.count > 0 {
  641. doneButton.isEnabled = true
  642. }
  643. }
  644. @IBAction func goPrevious(_ sender: Any) {
  645. if pdfView.canGoToPreviousPage() {
  646. pdfView.goToPreviousPage(nil)
  647. }
  648. let index = pdfDocument!.index(for: pdfView.currentPage())
  649. currentPageIndexTextField.stringValue = "\(index + 1)"
  650. }
  651. @IBAction func goNext(_ sender: Any) {
  652. if pdfView.canGoToNextPage() {
  653. pdfView.goToNextPage(nil)
  654. }
  655. let index = pdfDocument!.index(for: pdfView.currentPage())
  656. currentPageIndexTextField.stringValue = "\(index + 1)"
  657. }
  658. @IBAction func buttonClicked_BrowserFile(_ sender: Any) {
  659. let openPanel = NSOpenPanel()
  660. openPanel.canChooseDirectories = false
  661. openPanel.canChooseFiles = true
  662. openPanel.allowsMultipleSelection = false
  663. openPanel.allowedFileTypes = ["jpg", "cur", "bmp", "jpeg", "gif", "png", "tiff", "tif", "ico", "icns", "tga", "psd", "eps", "hdr", "jp2", "jpc", "pict", "sgi", "pdf"]
  664. openPanel.beginSheetModal(for: window!) { (result) in
  665. if result == .OK {
  666. guard let url = openPanel.url else { return }
  667. let filePath: NSString = url.path as NSString
  668. if filePath.pathExtension.lowercased() == "pdf" {
  669. let pdf = CPDFDocument(url: url)
  670. if pdf?.isEncrypted == true {
  671. return
  672. }
  673. }
  674. if let image = NSImage(contentsOfFile: url.path), !self.isDamageImage(image, imagePath: url.path) {
  675. self.filePathLabel.stringValue = url.path
  676. self.doneButton.isEnabled = true
  677. self.background.imagePath = url.path
  678. self.background.image = image
  679. self.background.backgroundID = url.path.lastPathComponent.deletingPathExtension
  680. self.templateNameTextField.stringValue = url.path.lastPathComponent.deletingPathExtension
  681. self.self.updatePDFView()
  682. }
  683. }
  684. }
  685. }
  686. // ... (remaining IBActions)
  687. @IBAction func buttonClicked_Batch(_ sender: Any) {
  688. if background.type == .color {
  689. background.imagePath = ""
  690. } else {
  691. background.color = nil
  692. if background.image == nil {
  693. return
  694. }
  695. }
  696. if templateNameTextField.stringValue.count < 1 {
  697. background.backgroundID = initialID
  698. } else {
  699. background.backgroundID = templateNameTextField.stringValue
  700. }
  701. let needSave = saveToTemplateButton.state == .on
  702. if needSave {
  703. KMBackgroundManager.defaultManager.addTemplate(model: background)
  704. }
  705. operateCallBack?(background, currentType)
  706. }
  707. @IBAction func buttonClicked_Done(_ sender: Any) {
  708. guard let pdfDocument = pdfDocument else { return }
  709. if background.type == .color {
  710. background.imagePath = ""
  711. } else {
  712. background.color = nil
  713. if background.image == nil {
  714. return
  715. }
  716. }
  717. if templateNameTextField.stringValue.isEmpty {
  718. background.backgroundID = initialID
  719. } else {
  720. background.backgroundID = templateNameTextField.stringValue
  721. }
  722. // Avoid showing the page range alert twice
  723. if checkPageRangeValidate(pageRangeComboBox.stringValue) {
  724. background.pagesString = pageRangeComboBox.stringValue
  725. self.updatePDFView()
  726. window?.makeFirstResponder(self)
  727. }
  728. let needSave = saveToTemplateButton.state == .on
  729. var pages = [Int]()
  730. switch pageRangeComboBox.indexOfSelectedItem {
  731. case 0:
  732. pages = Array(0..<Int(pdfDocument.pageCount))
  733. case 1:
  734. pages = Array(stride(from: 0, to: Int(pdfDocument.pageCount), by: 2))
  735. case 2:
  736. pages = Array(stride(from: 1, to: Int(pdfDocument.pageCount), by: 2))
  737. default:
  738. let fileAttribute = KMFileAttribute()
  739. fileAttribute.filePath = pdfDocument.documentURL?.path ?? ""
  740. fileAttribute.bAllPage = false
  741. fileAttribute.pagesString = pageRangeComboBox.stringValue
  742. let selectPages = fileAttribute.fetchSelectPages()
  743. if selectPages.count != 0 {
  744. pages = selectPages.map { $0.intValue - 1 }
  745. } else {
  746. let alert = NSAlert()
  747. alert.alertStyle = .critical
  748. alert.messageText = "\(fileAttribute.filePath.lastPathComponent) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  749. alert.runModal()
  750. return
  751. }
  752. }
  753. background.pagesString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  754. switch type {
  755. case .add:
  756. if needSave {
  757. if checkPageRangeValidate(pageRangeComboBox.stringValue) && pageRangeComboBox.indexOfSelectedItem == -1 {
  758. background.pagesString = pageRangeComboBox.stringValue
  759. }
  760. KMBackgroundManager.defaultManager.addTemplate(model: background)
  761. }
  762. operateCallBack?(background, currentType)
  763. case .edit:
  764. if needSave {
  765. if checkPageRangeValidate(pageRangeComboBox.stringValue) && pageRangeComboBox.indexOfSelectedItem == -1 {
  766. background.pagesString = pageRangeComboBox.stringValue
  767. }
  768. originalBackground = (background.copy() as? KMBackgroundModel)!
  769. // KMBackgroundManager.defaultManager.store()
  770. }
  771. operateCallBack?(originalBackground, currentType)
  772. case .use:
  773. let fileName = "\(pdfDocument.documentURL?.lastPathComponent ?? NSLocalizedString("Untitled", comment: ""))_Background"
  774. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  775. let savePanel = NSSavePanel()
  776. savePanel.nameFieldStringValue = fileName
  777. savePanel.allowedFileTypes = ["pdf"]
  778. savePanel.accessoryView = savePanelAccessoryViewController.view
  779. savePanel.beginSheetModal(for: window!) { result in
  780. if result == .OK {
  781. self.saveAsPDF(with: self.background, to: savePanel.url?.path ?? "", autoOpen: savePanelAccessoryViewController.openAutomaticButton.state == .on ? true : false)
  782. }
  783. }
  784. }
  785. }
  786. }