KMAddBackgroundView.swift 34 KB

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