KMAddBackgroundView.swift 36 KB

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