KMHeaderFooterView.swift 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. //
  2. // KMHeaderFooterView.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2023/11/24.
  6. //
  7. import Cocoa
  8. import Foundation
  9. let kHeaderFooterFileSavePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("HeaderFooterpdf.pdf")
  10. let dateFormatArray: [String] = [
  11. "m/d",
  12. "m/d/yy",
  13. "m/d/yyyy",
  14. "mm/dd/yy",
  15. "mm/dd/yyyy",
  16. "d/m/yy",
  17. "d/m/yyyy",
  18. "dd/mm/yy",
  19. "dd/mm/yyyy",
  20. "mm/yy",
  21. "mm/yyyy",
  22. "m.d.yy",
  23. "m.d.yyyy",
  24. "mm.dd.yy",
  25. "mm.dd.yyyy",
  26. "mm.yy",
  27. "mm.yyyy",
  28. "d.m.yy",
  29. "d.m.yyyy",
  30. "dd.mm.yy",
  31. "dd.mm.yyyy",
  32. "yy-mm-dd",
  33. "yyyy-mm-dd"
  34. ]
  35. let pageFormatArray: [String] = [
  36. "1",
  37. "1 of n",
  38. "1/n",
  39. "Page 1",
  40. "Page 1 of n"
  41. ]
  42. let fontSizeArray: [String] = [
  43. "8",
  44. "9",
  45. "10",
  46. "11",
  47. "12",
  48. "14",
  49. "16",
  50. "18",
  51. "20",
  52. "22",
  53. "24",
  54. "26",
  55. "28",
  56. "36",
  57. "48",
  58. "72",
  59. "144",
  60. "288",
  61. ]
  62. func convertDateFormat(_ oldString: String) -> String {
  63. var newString = oldString
  64. for dateFormat in dateFormatArray {
  65. if newString.contains(dateFormat) {
  66. let formatString = dateFormat.replacingOccurrences(of: "m", with: "M")
  67. let replace = "<<\(dateFormat)>>"
  68. let date = Date()
  69. let dateFormatter = DateFormatter()
  70. dateFormatter.dateFormat = formatString
  71. let dateString = dateFormatter.string(from: date)
  72. newString = newString.replacingOccurrences(of: replace, with: dateString)
  73. }
  74. }
  75. return newString
  76. }
  77. typealias KMHeaderFooterViewDoneAction = ( _ model: KMHeaderFooterObject) -> ()
  78. typealias KMHeaderFooterViewCancelAction = (_ view: KMHeaderFooterView) -> Void
  79. class KMHeaderFooterView: KMBaseXibView, NSTextViewDelegate, NSComboBoxDelegate {
  80. @IBOutlet weak var pdfView: KMWatermarkPDFView!
  81. @IBOutlet weak var currentPageIndexTextField: NSTextField!
  82. @IBOutlet weak var totalPageCountLabel: NSTextField!
  83. @IBOutlet weak var textBox: NSBox!
  84. @IBOutlet weak var textLabel: NSTextField!
  85. @IBOutlet weak var fontSizeLabel: NSTextField!
  86. @IBOutlet weak var fontSizeCombobox: NSComboBox!
  87. @IBOutlet weak var textColorLabel: NSTextField!
  88. @IBOutlet weak var textColorWell: NSColorWell!
  89. @IBOutlet weak var marginBox: NSBox!
  90. @IBOutlet weak var marginLabel: NSTextField!
  91. @IBOutlet weak var topMarginLabel: NSTextField!
  92. @IBOutlet weak var topMargintextField: NSTextField!
  93. @IBOutlet weak var topMarginStepper: NSStepper!
  94. @IBOutlet weak var bottomMarginLabel: NSTextField!
  95. @IBOutlet weak var bottomMarginTextField: NSTextField!
  96. @IBOutlet weak var bottomMarginStepper: NSStepper!
  97. @IBOutlet weak var leftMarginLabel: NSTextField!
  98. @IBOutlet weak var leftMarginTextField: NSTextField!
  99. @IBOutlet weak var leftMarginStepper: NSStepper!
  100. @IBOutlet weak var rightMarginLabel: NSTextField!
  101. @IBOutlet weak var rightMarginTextField: NSTextField!
  102. @IBOutlet weak var rightMarginStepper: NSStepper!
  103. @IBOutlet weak var formatBox: NSBox!
  104. @IBOutlet weak var formatLabel: NSTextField!
  105. @IBOutlet weak var dateFormateLabel: NSTextField!
  106. @IBOutlet weak var dateFormateCombobox: NSComboBox!
  107. @IBOutlet weak var pageLabel: NSTextField!
  108. @IBOutlet weak var pageCombobox: NSComboBox!
  109. @IBOutlet weak var beginPageLabel: NSTextField!
  110. @IBOutlet weak var beginPageCombobox: NSComboBox!
  111. @IBOutlet weak var topLeftLabel: NSTextField!
  112. @IBOutlet weak var topLeftTextView: NSTextView!
  113. @IBOutlet weak var topCenterLabel: NSTextField!
  114. @IBOutlet weak var topCenterTextView: NSTextView!
  115. @IBOutlet weak var topRightLabel: NSTextField!
  116. @IBOutlet weak var topRightTextView: NSTextView!
  117. @IBOutlet weak var bottomLeftLabel: NSTextField!
  118. @IBOutlet weak var bottomLeftTextView: NSTextView!
  119. @IBOutlet weak var bottomCenterLabel: NSTextField!
  120. @IBOutlet weak var BottomCenterTextView: NSTextView!
  121. @IBOutlet weak var bottomRightLabel: NSTextField!
  122. @IBOutlet weak var bottomRightTextView: NSTextView!
  123. @IBOutlet weak var pageRangeLabel: NSTextField!
  124. @IBOutlet weak var pageRangeCombobox: NSComboBox!
  125. @IBOutlet weak var saveToTemplateButton: NSButton!
  126. @IBOutlet weak var templateNameLabel: NSTextField!
  127. @IBOutlet weak var templateNameTextField: NSTextField!
  128. @IBOutlet weak var topLeftButton: NSButton!
  129. @IBOutlet weak var topCentButton: NSButton!
  130. @IBOutlet weak var topRightButton: NSButton!
  131. @IBOutlet weak var bottomLeftButton: NSButton!
  132. @IBOutlet weak var bottomCenterButton: NSButton!
  133. @IBOutlet weak var bottomRightButton: NSButton!
  134. @IBOutlet weak var batchButton: NSButton!
  135. @IBOutlet weak var cancelButton: NSButton!
  136. @IBOutlet weak var applyButton: NSButton!
  137. @IBOutlet weak var batesBox: NSBox!
  138. @IBOutlet weak var prefixLabel: NSTextField!
  139. @IBOutlet weak var prefixTextField: NSTextField!
  140. @IBOutlet weak var suffixLabel: NSTextField!
  141. @IBOutlet weak var suffixTextField: NSTextField!
  142. @IBOutlet weak var batesNumberLabel: NSTextField!
  143. @IBOutlet weak var batesNumberTextField: NSTextField!
  144. @IBOutlet weak var batesNumberStepper: NSStepper!
  145. @IBOutlet weak var batesStartPageLabel: NSTextField!
  146. @IBOutlet weak var batesStartpageCombobox: NSComboBox!
  147. @IBOutlet weak var constraint: NSLayoutConstraint!
  148. @IBOutlet weak var loadingView: KMLoadingView!
  149. var isHiddenBatchBtn: Bool = false
  150. var initialID: String = ""
  151. var filePath: String = Bundle.main.path(forResource: NSLocalizedString("Quick Start Guide.pdf", comment: ""), ofType: "") ?? ""
  152. var password: String = ""
  153. var type: KMBatchModifyTemplateType = .Use // Replace with the actual type
  154. var pdfDocument: CPDFDocument? {
  155. didSet {
  156. self.pdfView.document = self.pdfDocument
  157. self.pdfView.headerFooter = self.headerFooterObj
  158. self.password = self.pdfDocument?.password ?? ""
  159. self._fileAttri = KMFileAttribute()
  160. self._fileAttri?.filePath = self.pdfDocument?.documentURL.path ?? ""
  161. self.reloadData()
  162. }
  163. }
  164. var headerFooterObj: KMHeaderFooterObject = KMHeaderFooterObject()
  165. var originalHeaderFooterObj: KMHeaderFooterObject = KMHeaderFooterObject()
  166. var dateFormatArray: [Any] {
  167. get {
  168. return KMHeaderFooterManager.defaultManager.dateFormatArray
  169. }
  170. }
  171. var onlyManagerTemplate: Bool = true
  172. var isBates: Bool = false {
  173. didSet {
  174. if (self.isBates) {
  175. headerFooterObj.id = KMHeaderFooterManager.defaultManager.fetchBatesAvailableName()
  176. } else {
  177. headerFooterObj.id = KMHeaderFooterManager.defaultManager.fetchHeaderFooterAvailableName()
  178. }
  179. headerFooterObj.isBates = self.isBates
  180. self.reloadData()
  181. }
  182. }
  183. private var _fileAttri: KMFileAttribute?
  184. var cancelAction: KMHeaderFooterViewCancelAction?
  185. var operateCallBack: KMHeaderFooterViewDoneAction?
  186. deinit {
  187. NotificationCenter.default.removeObserver(self)
  188. }
  189. convenience init?(baseFile filePath: String, headerFooter object: KMHeaderFooterObject, password: String, type: KMBatchModifyTemplateType) {
  190. self.init()
  191. self.filePath = filePath
  192. self.password = password
  193. self.headerFooterObj = object.copy() as! KMHeaderFooterObject
  194. self.originalHeaderFooterObj = object
  195. self.initialID = object.id
  196. self.type = type
  197. self.pdfDocument = CPDFDocument(url: URL(fileURLWithPath: self.filePath))
  198. if self.pdfDocument!.isLocked {
  199. self.pdfDocument!.unlock(withPassword: password)
  200. }
  201. if self.pdfDocument!.isLocked {
  202. return nil
  203. }
  204. }
  205. override func setup() {
  206. let buttons = [
  207. topLeftButton, topCentButton, topRightButton,
  208. bottomLeftButton, bottomCenterButton, bottomRightButton
  209. ]
  210. for button in buttons {
  211. button?.wantsLayer = true
  212. button?.layer?.borderWidth = 1.0
  213. button?.layer?.cornerRadius = 1.0
  214. }
  215. let textViewArr: [NSTextView] = [
  216. self.topLeftTextView, self.topCenterTextView, self.topRightTextView,
  217. self.bottomLeftTextView, self.BottomCenterTextView, self.bottomRightTextView
  218. ]
  219. for textView in textViewArr {
  220. textView.wantsLayer = true
  221. textView.delegate = self
  222. // textView?.layer?.borderWidth = 1.0
  223. // textView?.layer?.borderColor = NSColor.gridColor.cgColor
  224. }
  225. self.textColorWell.color = self.headerFooterObj.getTextColor()
  226. self.pdfView.autoScales = true
  227. self.pdfView.setDisplay(.singlePage)
  228. // self.pdfView.documentView?.enclosingScrollView?.hasVerticalScroller = false
  229. // self.pdfView.documentView?.enclosingScrollView?.hasHorizontalScroller = false
  230. self.topMarginLabel.allowsExpansionToolTips = true
  231. self.bottomMarginLabel.allowsExpansionToolTips = true
  232. self.leftMarginLabel.allowsExpansionToolTips = true
  233. self.rightMarginLabel.allowsExpansionToolTips = true
  234. self.formatLabel.allowsExpansionToolTips = true
  235. self.dateFormateLabel.allowsExpansionToolTips = true
  236. self.pageLabel.allowsExpansionToolTips = true
  237. self.beginPageLabel.allowsExpansionToolTips = true
  238. self.topLeftLabel.allowsExpansionToolTips = true
  239. self.topCenterLabel.allowsExpansionToolTips = true
  240. self.topRightLabel.allowsExpansionToolTips = true
  241. self.bottomLeftLabel.allowsExpansionToolTips = true
  242. self.bottomCenterLabel.allowsExpansionToolTips = true
  243. self.bottomRightLabel.allowsExpansionToolTips = true
  244. self.saveToTemplateButton.isEnabled = onlyManagerTemplate
  245. self.pageRangeCombobox.removeAllItems()
  246. self.pageRangeCombobox.addItems(withObjectValues: [
  247. NSLocalizedString("All Pages", comment: ""),
  248. NSLocalizedString("Odd Pages Only", comment: ""),
  249. NSLocalizedString("Even Pages Only", comment: ""),
  250. NSLocalizedString("e.g. 1,3-5,10", comment: "")
  251. ])
  252. self.pageRangeCombobox.placeholderString = NSLocalizedString("e.g. 1,3-5,10", comment: "")
  253. self.pageRangeCombobox.selectItem(at: 0)
  254. self.pageRangeCombobox.isEditable = false
  255. self.pageRangeCombobox.delegate = self
  256. pageRangeCombobox.wantsLayer = true
  257. pageRangeCombobox.layer?.cornerRadius = 3.0
  258. self.batchButton.isHidden = true
  259. if self.type == .Use {
  260. self.batchButton.isHidden = false
  261. }
  262. self.fontSizeCombobox.removeAllItems()
  263. self.fontSizeCombobox.addItems(withObjectValues: fontSizeArray)
  264. // self.fontSizeCombobox.isEditable = false
  265. self.fontSizeCombobox.delegate = self
  266. }
  267. override func reloadData() {
  268. guard let pdfDocument = pdfDocument else { return }
  269. updateViewColor()
  270. self.totalPageCountLabel.stringValue = String(format: "/ %ld", pdfDocument.pageCount)
  271. self.leftMarginTextField.stringValue = self.headerFooterObj.leftMargin.description
  272. self.rightMarginTextField.stringValue = self.headerFooterObj.rightMargin.description
  273. self.topMargintextField.stringValue = self.headerFooterObj.topMargin.description
  274. self.bottomMarginTextField.stringValue = self.headerFooterObj.bottomMargin.description
  275. self.leftMarginStepper.integerValue = Int(self.headerFooterObj.leftMargin)
  276. self.rightMarginStepper.integerValue = Int(self.headerFooterObj.rightMargin)
  277. self.topMarginStepper.integerValue = Int(self.headerFooterObj.topMargin)
  278. self.bottomMarginStepper.integerValue = Int(self.headerFooterObj.bottomMargin)
  279. let string = Int(self.headerFooterObj.getTextFontSize()).description
  280. let index = self.fontSizeCombobox.indexOfItem(withObjectValue: string)
  281. if index != NSNotFound {
  282. self.fontSizeCombobox.selectItem(withObjectValue: string)
  283. } else {
  284. self.fontSizeCombobox.stringValue = string
  285. }
  286. self.textColorWell.color = self.headerFooterObj.getTextColor()
  287. self.dateFormateCombobox.removeAllItems()
  288. self.dateFormateCombobox.addItems(withObjectValues: self.dateFormatArray)
  289. self.dateFormateCombobox.selectItem(withObjectValue: self.headerFooterObj.dateFormatString)
  290. let containsItem = self.pageCombobox.objectValues.contains { item in
  291. return item as? String == self.headerFooterObj.pageFormatString
  292. }
  293. if containsItem {
  294. self.pageCombobox.selectItem(withObjectValue: self.headerFooterObj.pageFormatString)
  295. } else {
  296. self.pageCombobox.stringValue = ""
  297. }
  298. var pages = [Any]()
  299. for i in 0..<self.pdfDocument!.pageCount {
  300. pages.append(String(i + 1))
  301. }
  302. self.beginPageCombobox.formatter = TextFieldFormatter()
  303. self.beginPageCombobox.isEditable = false
  304. self.beginPageCombobox.removeAllItems()
  305. self.beginPageCombobox.addItems(withObjectValues: pages)
  306. let indexOfObject = self.beginPageCombobox.objectValues.contains { item in
  307. return item as? String == self.headerFooterObj.startString
  308. }
  309. if indexOfObject {
  310. self.beginPageCombobox.selectItem(withObjectValue: self.headerFooterObj.startString)
  311. }
  312. self.batesStartpageCombobox.formatter = TextFieldFormatter()
  313. self.batesStartpageCombobox.isEditable = false
  314. self.batesStartpageCombobox.removeAllItems()
  315. self.batesStartpageCombobox.addItems(withObjectValues: pages)
  316. let batesIndexOfObject = self.batesStartpageCombobox.objectValues.contains { item in
  317. return item as? String == self.headerFooterObj.startString
  318. }
  319. if batesIndexOfObject {
  320. self.batesStartpageCombobox.selectItem(withObjectValue: self.headerFooterObj.startString)
  321. }
  322. switch self.headerFooterObj.pageRangeType {
  323. case .all:
  324. self.pageRangeCombobox.isEditable = false
  325. self.pageRangeCombobox.selectItem(at: 0)
  326. case .odd:
  327. self.pageRangeCombobox.isEditable = false
  328. self.pageRangeCombobox.selectItem(at: 1)
  329. case .even:
  330. self.pageRangeCombobox.isEditable = false
  331. self.pageRangeCombobox.selectItem(at: 2)
  332. case .other:
  333. self.pageRangeCombobox.isEditable = true
  334. self.pageRangeCombobox.selectItem(at: 3)
  335. self.pageRangeCombobox.stringValue = self.headerFooterObj.pageRangeString
  336. let sting = self.headerFooterObj.pageRangeString
  337. if sting.count > 0 {
  338. let array = sting.components(separatedBy: ",")
  339. var pagesString = ""
  340. for i in 0..<(array.count - 1) {
  341. let index = array[i]
  342. if i == array.count - 1 {
  343. pagesString = String(format: "%@%ld", pagesString, (Int(index ) ?? 0) + 1)
  344. } else {
  345. pagesString = String(format: "%@%ld,", pagesString, (Int(index) ?? 0 ) + 1)
  346. }
  347. }
  348. self.pageRangeCombobox.stringValue = pagesString
  349. }
  350. }
  351. self.topLeftTextView.string = self.headerFooterObj.topLeftString
  352. self.topCenterTextView.string = self.headerFooterObj.topCenterString
  353. self.topRightTextView.string = self.headerFooterObj.topRightString
  354. self.bottomLeftTextView.string = self.headerFooterObj.bottomLeftString
  355. self.BottomCenterTextView.string = self.headerFooterObj.bottomCenterString
  356. self.bottomRightTextView.string = self.headerFooterObj.bottomRightString
  357. self.templateNameTextField.stringValue = self.headerFooterObj.id
  358. if self.topLeftTextView.string.count <= 0 &&
  359. self.topCenterTextView.string.count <= 0 &&
  360. self.topRightTextView.string.count <= 0 &&
  361. self.bottomLeftTextView.string.count <= 0 &&
  362. self.BottomCenterTextView.string.count <= 0 &&
  363. self.bottomRightTextView.string.count <= 0 {
  364. self.applyButton.isEnabled = false
  365. } else {
  366. self.applyButton.isEnabled = true
  367. }
  368. if self.isBates {
  369. self.constraint.constant = 49
  370. self.formatBox.isHidden = true
  371. self.batesBox.isHidden = false
  372. } else {
  373. self.constraint.constant = 20
  374. self.formatBox.isHidden = false
  375. self.batesBox.isHidden = true
  376. }
  377. self.batchButton.isHidden = isHiddenBatchBtn
  378. if !isHiddenBatchBtn {
  379. self.batchButton.isHidden = type != .Use
  380. }
  381. }
  382. func updateViewColor() {
  383. let borderColor: CGColor
  384. let backgroundColor: CGColor
  385. if KMAppearance.isDarkMode() {
  386. borderColor = NSColor.white.withAlphaComponent(0.3).cgColor
  387. backgroundColor = NSColor(red: 54 / 255.0, green: 54 / 255.0, blue: 54 / 255.0, alpha: 0.85).cgColor
  388. } else {
  389. borderColor = NSColor.white.withAlphaComponent(0.3).cgColor
  390. backgroundColor = NSColor(red: 238 / 255.0, green: 238 / 255.0, blue: 238 / 255.0, alpha: 0.85).cgColor
  391. }
  392. let buttons = [
  393. topLeftButton, topCentButton, topRightButton,
  394. bottomLeftButton, bottomCenterButton, bottomRightButton
  395. ]
  396. for button in buttons {
  397. button?.layer?.borderColor = borderColor
  398. button?.layer?.backgroundColor = backgroundColor
  399. }
  400. }
  401. override func updateLanguage() {
  402. self.currentPageIndexTextField.stringValue = NSLocalizedString("1", comment: "")
  403. self.batesStartPageLabel.stringValue = String(format: "%@:", NSLocalizedString("Start Page Number", comment: ""))
  404. self.textLabel.stringValue = NSLocalizedString("Font Size", comment: "")
  405. self.fontSizeLabel.stringValue = String(format: "%@:", NSLocalizedString("Size", comment: ""))
  406. self.textColorLabel.stringValue = String(format: "%@:", NSLocalizedString("Color", comment: ""))
  407. self.marginLabel.stringValue = NSLocalizedString("Margin", comment: "")
  408. self.topMarginLabel.stringValue = String(format: "%@:", NSLocalizedString("Top", comment: ""))
  409. self.bottomMarginLabel.stringValue = String(format: "%@:", NSLocalizedString("Bottom", comment: ""))
  410. self.leftMarginLabel.stringValue = String(format: "%@:", NSLocalizedString("Left", comment: ""))
  411. self.rightMarginLabel.stringValue = String(format: "%@:", NSLocalizedString("Right", comment: ""))
  412. self.topMarginLabel.toolTip = String(format: "%@:", NSLocalizedString("Top", comment: ""))
  413. self.bottomMarginLabel.toolTip = String(format: "%@:", NSLocalizedString("Bottom", comment: ""))
  414. self.leftMarginLabel.toolTip = String(format: "%@:", NSLocalizedString("Left", comment: ""))
  415. self.rightMarginLabel.toolTip = String(format: "%@:", NSLocalizedString("Right", comment: ""))
  416. self.formatLabel.stringValue = NSLocalizedString("Page Number and Date Format", comment: "")
  417. self.dateFormateLabel.stringValue = String(format: "%@:", NSLocalizedString("Date", comment: ""))
  418. self.pageLabel.stringValue = String(format: "%@:", NSLocalizedString("Page", comment: ""))
  419. self.beginPageLabel.stringValue = String(format: "%@:", NSLocalizedString("Start Page Number", comment: ""))
  420. self.formatLabel.toolTip = NSLocalizedString("Page Number and Date Format", comment: "")
  421. self.dateFormateLabel.toolTip = String(format: "%@:", NSLocalizedString("Date", comment: ""))
  422. self.pageLabel.toolTip = String(format: "%@:", NSLocalizedString("Page", comment: ""))
  423. self.beginPageLabel.toolTip = String(format: "%@:", NSLocalizedString("Start Page Number", comment: ""))
  424. self.topLeftLabel.stringValue = NSLocalizedString("Left Header Text", comment: "")
  425. self.topCenterLabel.stringValue = NSLocalizedString("Center Header Text", comment: "")
  426. self.topRightLabel.stringValue = NSLocalizedString("Right Header Text", comment: "")
  427. self.bottomLeftLabel.stringValue = NSLocalizedString("Left Footer Text", comment: "")
  428. self.bottomCenterLabel.stringValue = NSLocalizedString("Center Footer Text", comment: "")
  429. self.bottomRightLabel.stringValue = NSLocalizedString("Right Footer Text", comment: "")
  430. self.topLeftLabel.toolTip = NSLocalizedString("Left Header Text", comment: "")
  431. self.topCenterLabel.toolTip = NSLocalizedString("Center Header Text", comment: "")
  432. self.topRightLabel.toolTip = NSLocalizedString("Right Header Text", comment: "")
  433. self.bottomLeftLabel.toolTip = NSLocalizedString("Left Footer Text", comment: "")
  434. self.bottomCenterLabel.toolTip = NSLocalizedString("Center Footer Text", comment: "")
  435. self.bottomRightLabel.toolTip = NSLocalizedString("Right Footer Text", comment: "")
  436. self.pageRangeLabel.stringValue = String(format: "%@:", NSLocalizedString("Page Range", comment: ""))
  437. self.saveToTemplateButton.title = NSLocalizedString("Add to Template", comment: "")
  438. self.templateNameLabel.stringValue = NSLocalizedString("Name:", comment: "")
  439. self.batchButton.title = NSLocalizedString("Batch", comment: "")
  440. self.cancelButton.title = NSLocalizedString("Cancel", comment: "")
  441. self.applyButton.title = NSLocalizedString("Apply", comment: "")
  442. self.batesBox.title = NSLocalizedString("Bates Settings", comment: "")
  443. self.prefixLabel.stringValue = String(format: "%@:", NSLocalizedString("Prefix", comment: ""))
  444. self.prefixLabel.toolTip = String(format: "%@:", NSLocalizedString("Prefix", comment: ""))
  445. self.prefixTextField.stringValue = self.headerFooterObj.batesPrefixString
  446. self.suffixLabel.stringValue = String(format: "%@:", NSLocalizedString("Suffix", comment: ""))
  447. self.suffixLabel.toolTip = String(format: "%@:", NSLocalizedString("Suffix", comment: ""))
  448. self.suffixTextField.stringValue = self.headerFooterObj.batesSuffixString
  449. self.batesNumberLabel.stringValue = String(format: "%@:", NSLocalizedString("Number of Digits", comment: ""))
  450. self.batesNumberStepper.integerValue = self.headerFooterObj.batesDigits
  451. self.batesNumberTextField.integerValue = self.headerFooterObj.batesDigits
  452. }
  453. override func addNotification() {
  454. NotificationCenter.default.addObserver(self, selector: #selector(pageChangeNotification), name: NSNotification.Name.CPDFViewPageChanged, object: self.pdfView)
  455. // NotificationCenter.default.addObserver(self, selector: #selector(themeChanged), name: Notification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
  456. DistributedNotificationCenter.default().addObserver(self, selector: #selector(themeChanged), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
  457. }
  458. func checkPageRangeValidate(pageRangeString: String) -> Bool {
  459. var fileAttribute = self._fileAttri
  460. if fileAttribute == nil {
  461. fileAttribute = KMFileAttribute()
  462. self._fileAttri = fileAttribute
  463. fileAttribute?.filePath = self.pdfDocument?.documentURL?.path ?? ""
  464. }
  465. fileAttribute?.bAllPage = false
  466. var pageRange: KMPageRange = .all
  467. let pageRangeType: KMWatermarkeModelPageRangeType = headerFooterObj.pageRangeType
  468. if pageRangeType == .all {
  469. pageRange = .all
  470. } else if pageRangeType == .even {
  471. pageRange = .even
  472. } else if pageRangeType == .odd {
  473. pageRange = .odd
  474. } else if pageRangeType == .other {
  475. pageRange = .custom
  476. }
  477. fileAttribute?.pagesType = pageRange
  478. fileAttribute?.pagesString = self.pageRangeCombobox.stringValue
  479. if let cnt = fileAttribute?.fetchSelectPages().count, cnt == 0 {
  480. return false
  481. }
  482. return true
  483. }
  484. func popMenu(sender: NSButton) {
  485. if self.isBates {
  486. let menu = NSMenu()
  487. let title = NSLocalizedString("Insert Bates", comment: "")
  488. let item = menu.addItem(withTitle: title, action: #selector(menuItem_InsertBates), keyEquivalent: "")
  489. item.target = self
  490. item.representedObject = sender
  491. menu.popUp(positioning: menu.item(at: 0), at: NSPoint(x: 0, y: 15), in: sender)
  492. } else {
  493. let dateMenu = NSMenu()
  494. var title = NSLocalizedString("Insert Page Number", comment: "")
  495. var item = dateMenu.addItem(withTitle: title, action: #selector(menuItem_InsertPage), keyEquivalent: "")
  496. item.target = self
  497. item.representedObject = sender
  498. title = NSLocalizedString("Insert Date", comment: "")
  499. item = dateMenu.addItem(withTitle: title, action: #selector(menuItem_InsertDate), keyEquivalent: "")
  500. item.target = self
  501. item.representedObject = sender
  502. dateMenu.popUp(positioning: dateMenu.item(at: 0), at: NSPoint(x: 0, y: 15), in: sender)
  503. }
  504. }
  505. @objc func menuItem_InsertBates(_ sender: NSMenuItem) {
  506. guard let button = sender.representedObject as? NSButton else { return }
  507. self.window?.makeFirstResponder(self)
  508. self.headerFooterObj.batesDigits = self.batesNumberTextField.integerValue
  509. var tString = "<<#\((self.batesNumberTextField.integerValue))#\(self.batesStartpageCombobox.stringValue)"
  510. if !self.prefixTextField.stringValue.isEmpty {
  511. tString += "#\(self.prefixTextField.stringValue)"
  512. } else if self.prefixTextField.stringValue.isEmpty && !self.suffixTextField.stringValue.isEmpty {
  513. tString += "#"
  514. }
  515. if !self.suffixTextField.stringValue.isEmpty {
  516. tString += "#\(self.suffixTextField.stringValue)"
  517. }
  518. tString += ">>"
  519. if let textView = self.fetchTargetTextView(tag: button.tag) {
  520. textView.string = textView.string + tString
  521. self.updateHeaderFooterString(newString: textView.string, tag: button.tag)
  522. }
  523. self.applyButton.isEnabled = true
  524. self.updatePDFView()
  525. }
  526. @objc func menuItem_InsertPage(_ sender: NSMenuItem) {
  527. guard let button = sender.representedObject as? NSButton else { return }
  528. let tString = "<<\(self.pageCombobox.stringValue)>>"
  529. if let textView = self.fetchTargetTextView(tag: button.tag) {
  530. textView.string = textView.string + tString
  531. self.updateHeaderFooterString(newString: textView.string, tag: button.tag)
  532. }
  533. self.applyButton.isEnabled = true
  534. self.updatePDFView()
  535. }
  536. @objc func menuItem_InsertDate(_ sender: NSMenuItem) {
  537. guard let button = sender.representedObject as? NSButton else { return }
  538. let tString = "<<\(self.headerFooterObj.dateFormatString)>>"
  539. if let textView = self.fetchTargetTextView(tag: button.tag) {
  540. textView.string = textView.string + tString
  541. self.updateHeaderFooterString(newString: textView.string, tag: button.tag)
  542. }
  543. self.applyButton.isEnabled = true
  544. self.updatePDFView()
  545. }
  546. func fetchTargetTextView(tag: Int) -> NSTextView? {
  547. var textView: NSTextView?
  548. switch tag {
  549. case 0:
  550. textView = self.topLeftTextView
  551. case 1:
  552. textView = self.topCenterTextView
  553. case 2:
  554. textView = self.topRightTextView
  555. case 3:
  556. textView = self.bottomLeftTextView
  557. case 4:
  558. textView = self.BottomCenterTextView
  559. case 5:
  560. textView = self.bottomRightTextView
  561. default:
  562. break
  563. }
  564. return textView
  565. }
  566. func updateHeaderFooterString(newString: String, tag: Int) {
  567. switch tag {
  568. case 0:
  569. self.headerFooterObj.topLeftString = newString
  570. case 1:
  571. self.headerFooterObj.topCenterString = newString
  572. case 2:
  573. self.headerFooterObj.topRightString = newString
  574. case 3:
  575. self.headerFooterObj.bottomLeftString = newString
  576. case 4:
  577. self.headerFooterObj.bottomCenterString = newString
  578. case 5:
  579. self.headerFooterObj.bottomRightString = newString
  580. default:
  581. break
  582. }
  583. }
  584. func textDidChange(_ notification: Notification) {
  585. guard let textView = notification.object as? NSTextView else {
  586. return
  587. }
  588. switch textView {
  589. case topLeftTextView:
  590. headerFooterObj.topLeftString = topLeftTextView.string
  591. case topCenterTextView:
  592. headerFooterObj.topCenterString = topCenterTextView.string
  593. case topRightTextView:
  594. headerFooterObj.topRightString = topRightTextView.string
  595. case bottomLeftTextView:
  596. headerFooterObj.bottomLeftString = bottomLeftTextView.string
  597. case BottomCenterTextView:
  598. headerFooterObj.bottomCenterString = BottomCenterTextView.string
  599. case bottomRightTextView:
  600. headerFooterObj.bottomRightString = bottomRightTextView.string
  601. default:
  602. break
  603. }
  604. applyButton.isEnabled = !(
  605. topLeftTextView.string.isEmpty &&
  606. topCenterTextView.string.isEmpty &&
  607. topRightTextView.string.isEmpty &&
  608. bottomLeftTextView.string.isEmpty &&
  609. BottomCenterTextView.string.isEmpty &&
  610. bottomRightTextView.string.isEmpty
  611. )
  612. self.updatePDFView()
  613. }
  614. func saveAsPDFToPath(_ path: String, autoOpen: Bool) {
  615. self.loadingView.isHidden = false
  616. self.loadingView.startAnimation()
  617. DispatchQueue.global(qos: .default).async { [unowned self] in
  618. var filePath = self.pdfDocument?.documentURL?.path
  619. let password = self.password
  620. if filePath == nil {
  621. let writeSuccess = self.pdfDocument!.write(to: URL(fileURLWithPath: kNewDocumentTempSavePath(NSLocalizedString("Untitled", comment: ""))))
  622. if writeSuccess {
  623. let newDocument = CPDFDocument(url: URL(fileURLWithPath: kNewDocumentTempSavePath(NSLocalizedString("Untitled", comment: ""))))
  624. filePath = newDocument?.documentURL?.path
  625. } else {
  626. return
  627. }
  628. }
  629. guard let filePath = filePath else { return }
  630. let document = CPDFDocument(url: NSURL.fileURL(withPath: filePath))
  631. document?.unlock(withPassword: password)
  632. let font = NSFont.boldSystemFont(ofSize: self.headerFooterObj.getTextFontSize())
  633. let style = NSMutableParagraphStyle()
  634. style.alignment = .center
  635. style.lineBreakMode = .byCharWrapping
  636. let dictionary: [NSAttributedString.Key: Any] = [.paragraphStyle: style, .font: font]
  637. let size = ("text" as NSString).boundingRect(with: CGSize(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude),
  638. options: [.usesLineFragmentOrigin, .usesFontLeading],
  639. attributes: dictionary).size
  640. if self.isBates {
  641. if let bates = document?.bates() {
  642. bates.margin = NSEdgeInsets(top: max(CGFloat(self.headerFooterObj.topMargin) - size.height, 0),
  643. left: CGFloat(self.headerFooterObj.leftMargin),
  644. bottom: max(CGFloat(self.headerFooterObj.bottomMargin) - size.height, 0),
  645. right: CGFloat(self.headerFooterObj.rightMargin))
  646. let pagesString = self.headerFooterObj.pageRangeString
  647. if pagesString.count != 0 {
  648. bates.pageString = pagesString
  649. } else {
  650. let pageString = "0-\(document!.pageCount - 1)"
  651. bates.pageString = pageString
  652. }
  653. let items = [self.headerFooterObj.topLeftString,
  654. self.headerFooterObj.topCenterString,
  655. self.headerFooterObj.topRightString,
  656. self.headerFooterObj.bottomLeftString,
  657. self.headerFooterObj.bottomCenterString,
  658. self.headerFooterObj.bottomRightString]
  659. for i in 0..<items.count {
  660. let text = items[i]
  661. bates.setText(text, at: UInt(i))
  662. bates.setTextColor(self.headerFooterObj.getTextColor(), at: UInt(i))
  663. bates.setFontSize(self.headerFooterObj.getTextFontSize(), at: UInt(i))
  664. }
  665. bates.update()
  666. }
  667. } else {
  668. print(document?.headerFooter())
  669. if let headerFooter = document?.headerFooter() {
  670. headerFooter.margin = NSEdgeInsets(top: max(CGFloat(self.headerFooterObj.topMargin) - size.height, 0),
  671. left: CGFloat(self.headerFooterObj.leftMargin),
  672. bottom: max(CGFloat(self.headerFooterObj.bottomMargin) - size.height, 0),
  673. right: CGFloat(self.headerFooterObj.rightMargin))
  674. let pagesString = self.headerFooterObj.pageRangeString
  675. if pagesString.count != 0 {
  676. headerFooter.pageString = pagesString
  677. } else {
  678. let pageString = "0-\(document!.pageCount - 1)"
  679. headerFooter.pageString = pageString
  680. }
  681. let pageCount = self.pdfView.document?.pageCount ?? UInt(0 + (self.headerFooterObj.startString as NSString).integerValue - 1)
  682. let topLeftString = self.convertPageFormat(self.headerFooterObj.topLeftString, startPage: self.headerFooterObj.startString, pageCount: "\(pageCount)")
  683. let topCenterString = self.convertPageFormat(self.headerFooterObj.topCenterString, startPage: self.headerFooterObj.startString, pageCount: "\(pageCount)")
  684. let topRightString = self.convertPageFormat(self.headerFooterObj.topRightString, startPage: self.headerFooterObj.startString, pageCount: "\(pageCount)")
  685. let bottomLeftString = self.convertPageFormat(self.headerFooterObj.bottomLeftString, startPage: self.headerFooterObj.startString, pageCount: "\(pageCount)")
  686. let bottomCenterString = self.convertPageFormat(self.headerFooterObj.bottomCenterString, startPage: self.headerFooterObj.startString, pageCount: "\(pageCount)")
  687. let bottomRightString = self.convertPageFormat(self.headerFooterObj.bottomRightString, startPage: self.headerFooterObj.startString, pageCount: "\(pageCount)")
  688. let items = [topLeftString, topCenterString, topRightString, bottomLeftString, bottomCenterString, bottomRightString]
  689. for i in 0..<items.count {
  690. let text = items[i]
  691. headerFooter.setText(text, at: UInt(i))
  692. headerFooter.setTextColor(self.headerFooterObj.getTextColor(), at: UInt(i))
  693. headerFooter.setFontSize(self.headerFooterObj.getTextFontSize(), at: UInt(i))
  694. }
  695. headerFooter.update()
  696. }
  697. }
  698. let documentPath = NSTemporaryDirectory()
  699. let tempPath = (documentPath as NSString).appendingPathComponent((filePath as NSString).lastPathComponent)
  700. if FileManager.default.fileExists(atPath: tempPath) {
  701. try? FileManager.default.removeItem(atPath: tempPath)
  702. }
  703. let result = document?.write(to: URL(fileURLWithPath: tempPath)) ?? false
  704. if result {
  705. if FileManager.default.fileExists(atPath: path) {
  706. try? FileManager.default.removeItem(atPath: path)
  707. }
  708. try? FileManager.default.moveItem(atPath: tempPath, toPath: path)
  709. } else {
  710. try? FileManager.default.removeItem(atPath: tempPath)
  711. }
  712. if result {
  713. DispatchQueue.main.async {
  714. self.loadingView.isHidden = true
  715. self.loadingView.stopAnimation()
  716. self.cancelAction?(self)
  717. if autoOpen {
  718. NSDocumentController.shared.openDocument(withContentsOf: URL(fileURLWithPath: path), display: true) { _, _, _ in
  719. }
  720. } else {
  721. NSWorkspace.shared.selectFile(path, inFileViewerRootedAtPath: "")
  722. }
  723. }
  724. } else {
  725. DispatchQueue.main.async {
  726. self.loadingView.isHidden = true
  727. self.loadingView.stopAnimation()
  728. }
  729. }
  730. }
  731. }
  732. func kNewDocumentTempSavePath(_ fileName: String) -> String {
  733. let searchPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true).last
  734. let append1 = searchPath?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!)
  735. let append2 = append1!.stringByAppendingPathComponent(String(format: "%@", fileName))
  736. return append2
  737. }
  738. static func saveAsPDFRemoveAllHeaderFooter(_ PDFDocument: CPDFDocument,
  739. password: String?,
  740. toPath path: String,
  741. completionHandler handler: ((Int) -> Void)?) {
  742. DispatchQueue.global(qos: .default).async {
  743. var filePath = PDFDocument.documentURL?.path
  744. let document = CPDFDocument(url: URL(fileURLWithPath: filePath ?? ""))
  745. if let password = password {
  746. document?.unlock(withPassword: password)
  747. }
  748. if let headerFooter = document?.headerFooter {
  749. headerFooter()?.clear()
  750. }
  751. let documentPath = NSTemporaryDirectory()
  752. let tempPath = (documentPath as NSString).appendingPathComponent((path as NSString).lastPathComponent)
  753. if FileManager.default.fileExists(atPath: tempPath) {
  754. try? FileManager.default.removeItem(atPath: tempPath)
  755. }
  756. let result = document?.write(to: URL(fileURLWithPath: tempPath)) ?? false
  757. if result {
  758. if FileManager.default.fileExists(atPath: path) {
  759. try? FileManager.default.removeItem(atPath: path)
  760. }
  761. try? FileManager.default.moveItem(atPath: tempPath, toPath: path)
  762. } else {
  763. try? FileManager.default.removeItem(atPath: tempPath)
  764. }
  765. DispatchQueue.main.async {
  766. if result {
  767. handler?(1)
  768. } else {
  769. handler?(0)
  770. }
  771. }
  772. }
  773. }
  774. static func saveAsPDFRemoveAllHeaderFooterBates(_ PDFDocument: CPDFDocument,
  775. password: String?,
  776. toPath path: String,
  777. completionHandler handler: ((Int) -> Void)?) {
  778. DispatchQueue.global(qos: .default).async {
  779. var filePath = PDFDocument.documentURL?.path
  780. let document = CPDFDocument(url: URL(fileURLWithPath: filePath ?? ""))
  781. if let password = password {
  782. document?.unlock(withPassword: password)
  783. }
  784. if let bates = document?.bates {
  785. bates()?.clear()
  786. }
  787. let documentPath = NSTemporaryDirectory()
  788. let tempPath = (documentPath as NSString).appendingPathComponent((path as NSString).lastPathComponent)
  789. if FileManager.default.fileExists(atPath: tempPath) {
  790. try? FileManager.default.removeItem(atPath: tempPath)
  791. }
  792. let result = document?.write(to: URL(fileURLWithPath: tempPath)) ?? false
  793. if result {
  794. if FileManager.default.fileExists(atPath: path) {
  795. try? FileManager.default.removeItem(atPath: path)
  796. }
  797. try? FileManager.default.moveItem(atPath: tempPath, toPath: path)
  798. } else {
  799. try? FileManager.default.removeItem(atPath: tempPath)
  800. }
  801. DispatchQueue.main.async {
  802. if result {
  803. handler?(1)
  804. } else {
  805. handler?(0)
  806. }
  807. }
  808. }
  809. }
  810. @objc func controlTextDidEndEditing(_ obj: Notification) {
  811. guard let comboBox = obj.object as? NSComboBox else {
  812. return
  813. }
  814. if comboBox == pageRangeCombobox {
  815. if pageRangeCombobox.indexOfSelectedItem == -1 {
  816. if !checkPageRangeValidate(pageRangeString: comboBox.stringValue) {
  817. let alert = NSAlert()
  818. alert.alertStyle = .critical
  819. alert.messageText = "\(pdfDocument?.documentURL?.lastPathComponent ?? NSLocalizedString("Untitled", comment: "")) \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  820. alert.runModal()
  821. headerFooterObj.pageRangeType = .all
  822. pageRangeCombobox.selectItem(at: 0)
  823. // pageRangeCombobox.isEditable = false
  824. pageRangeCombobox.isSelectable = false
  825. return
  826. } else {
  827. headerFooterObj.pageRangeString = comboBox.stringValue
  828. self.updatePDFView()
  829. }
  830. }
  831. }
  832. }
  833. @objc func comboBoxSelectionDidChange(_ notification: Notification) {
  834. guard let comboBox = notification.object as? NSComboBox else {
  835. return
  836. }
  837. if comboBox == pageRangeCombobox {
  838. pageRangeCombobox.isEditable = false
  839. switch comboBox.indexOfSelectedItem {
  840. case 0:
  841. headerFooterObj.pageRangeType = .all
  842. case 1:
  843. headerFooterObj.pageRangeType = .odd
  844. case 2:
  845. headerFooterObj.pageRangeType = .even
  846. default:
  847. headerFooterObj.pageRangeType = .other
  848. // pageRangeCombobox.stringValue = ""
  849. pageRangeCombobox.isEditable = true
  850. window?.makeFirstResponder(pageRangeCombobox)
  851. }
  852. }
  853. }
  854. @objc func pageChangeNotification(_ notification: Notification) {
  855. currentPageIndexTextField.stringValue = "\(pdfView.currentPage().pageIndex() + 1)"
  856. }
  857. @objc func themeChanged(_ notification: Notification) {
  858. DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
  859. self.updateViewColor()
  860. }
  861. }
  862. func updatePDFView() {
  863. self.pdfView.needsDisplay = true
  864. }
  865. }
  866. extension KMHeaderFooterView {
  867. @IBAction func previousPage(_ sender: Any) {
  868. if pdfView.canGoToPreviousPage() {
  869. pdfView.goToPreviousPage(nil)
  870. }
  871. let index = pdfDocument?.index(for: pdfView.currentPage()) ?? 0
  872. currentPageIndexTextField.stringValue = "\(index + 1)"
  873. }
  874. @IBAction func nextPage(_ sender: Any) {
  875. if pdfView.canGoToNextPage() {
  876. pdfView.goToNextPage(nil)
  877. }
  878. let index = pdfDocument?.index(for: pdfView.currentPage()) ?? 0
  879. currentPageIndexTextField.stringValue = "\(index + 1)"
  880. }
  881. @IBAction func pageIndexTextFieldEndEdit(_ sender: NSTextField) {
  882. pdfView.go(to: pdfDocument?.page(at: UInt(sender.integerValue - 1)))
  883. }
  884. @IBAction func chooseColor(_ sender: NSColorWell) {
  885. if let color = sender.color.usingColorSpaceName(NSColorSpaceName.calibratedRGB) {
  886. headerFooterObj.textColor = KMWatermarkAdjectiveText.color(red: color.redComponent, green: color.greenComponent, blue: color.blueComponent, alpha: color.alphaComponent)
  887. self.updatePDFView()
  888. }
  889. }
  890. @IBAction func chooseFont(_ sender: NSComboBox) {
  891. headerFooterObj.textFont = KMWatermarkAdjectiveText.font(name: "Helvetica", size: sender.stringValue.stringToCGFloat())
  892. self.updatePDFView()
  893. }
  894. @IBAction func topMarginTextFiedEndEdit(_ sender: NSTextField) {
  895. topMarginStepper.integerValue = sender.integerValue
  896. headerFooterObj.topMargin = sender.integerValue
  897. self.updatePDFView()
  898. }
  899. @IBAction func topMarginStepperAction(_ sender: NSStepper) {
  900. topMargintextField.integerValue = sender.integerValue
  901. headerFooterObj.topMargin = sender.integerValue
  902. self.updatePDFView()
  903. }
  904. @IBAction func bottomMarginTextFieldEndEdit(_ sender: NSTextField) {
  905. bottomMarginStepper.integerValue = sender.integerValue
  906. headerFooterObj.bottomMargin = sender.integerValue
  907. self.updatePDFView()
  908. }
  909. @IBAction func bottomMarginStepperAction(_ sender: NSStepper) {
  910. bottomMarginTextField.integerValue = sender.integerValue
  911. headerFooterObj.bottomMargin = sender.integerValue
  912. self.updatePDFView()
  913. }
  914. @IBAction func leftMarginTextFieldEndEdit(_ sender: NSTextField) {
  915. leftMarginStepper.integerValue = sender.integerValue
  916. headerFooterObj.leftMargin = sender.integerValue
  917. self.updatePDFView()
  918. }
  919. @IBAction func leftMarginStepperAction(_ sender: NSStepper) {
  920. leftMarginTextField.integerValue = sender.integerValue
  921. headerFooterObj.leftMargin = sender.integerValue
  922. self.updatePDFView()
  923. }
  924. @IBAction func rightMarginTextFieldEndEdit(_ sender: NSTextField) {
  925. rightMarginStepper.integerValue = sender.integerValue
  926. headerFooterObj.rightMargin = sender.integerValue
  927. self.updatePDFView()
  928. }
  929. @IBAction func rightMarginStepperAction(_ sender: NSStepper) {
  930. rightMarginTextField.integerValue = sender.integerValue
  931. headerFooterObj.rightMargin = sender.integerValue
  932. self.updatePDFView()
  933. }
  934. @IBAction func chooseDateFormate(_ sender: NSComboBox) {
  935. headerFooterObj.dateFormatString = sender.stringValue
  936. self.updatePDFView()
  937. }
  938. @IBAction func choosePageFormate(_ sender: NSComboBox) {
  939. headerFooterObj.pageFormatString = sender.stringValue
  940. self.updatePDFView()
  941. }
  942. @IBAction func chooseStartPage(_ sender: NSComboBox) {
  943. headerFooterObj.startString = sender.stringValue
  944. self.updatePDFView()
  945. }
  946. @IBAction func buttonClicked_AddHeaderFooter(_ sender: NSButton) {
  947. popMenu(sender: sender)
  948. }
  949. @IBAction func saveTemplateOrNot(_ sender: Any) {
  950. }
  951. @IBAction func templateNameTextFieldEndEdit(_ sender: NSTextField) {
  952. headerFooterObj.id = sender.stringValue
  953. }
  954. @IBAction func batch(_ sender: Any) {
  955. if saveToTemplateButton.state == .on {
  956. if templateNameTextField.stringValue.count < 1 {
  957. return
  958. }
  959. headerFooterObj.id = templateNameTextField.stringValue
  960. KMHeaderFooterManager.defaultManager.addHeaderFooter(headerFooterObj)
  961. }
  962. if let operateCallBack = operateCallBack {
  963. operateCallBack(headerFooterObj)
  964. }
  965. }
  966. @IBAction func cancel(_ sender: Any) {
  967. self.cancelAction?(self)
  968. }
  969. @IBAction func apply(_ sender: Any) {
  970. guard let pdfDocument = pdfDocument else { return }
  971. let needSave = saveToTemplateButton.state == .on
  972. var pages = [Int]()
  973. switch pageRangeCombobox.indexOfSelectedItem {
  974. case 0:
  975. pages = Array(0..<Int(pdfDocument.pageCount))
  976. case 1:
  977. pages = Array(stride(from: 0, to: Int(pdfDocument.pageCount), by: 2))
  978. case 2:
  979. pages = Array(stride(from: 1, to: Int(pdfDocument.pageCount), by: 2))
  980. default:
  981. var fileAttribute = self._fileAttri
  982. if fileAttribute == nil {
  983. fileAttribute?.password = self.pdfDocument?.password ?? ""
  984. fileAttribute?.filePath = self.pdfDocument?.documentURL.path ?? ""
  985. self._fileAttri = fileAttribute
  986. }
  987. // fileAttribute.filePath = pdfDocument.documentURL?.path ?? ""
  988. fileAttribute?.bAllPage = false
  989. fileAttribute?.pagesType = .custom
  990. // fileAttribute?.password = pdfDocument.password ?? ""
  991. fileAttribute?.pagesString = pageRangeCombobox.stringValue
  992. let selectPages = fileAttribute?.fetchSelectPages() ?? []
  993. if selectPages.count != 0 {
  994. pages = selectPages.map { $0 - 1 }
  995. } else {
  996. let alert = NSAlert()
  997. alert.alertStyle = .critical
  998. alert.messageText = "\(fileAttribute?.filePath.lastPathComponent ?? "") \(NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: ""))"
  999. alert.runModal()
  1000. return
  1001. }
  1002. }
  1003. headerFooterObj.pageRangeString = pages.isEmpty ? "" : pages.map { "\($0)" }.joined(separator: ",")
  1004. if type == .Add {
  1005. let object = headerFooterObj
  1006. if object.topLeftString.isEmpty && object.topCenterString.isEmpty && object.topRightString.isEmpty &&
  1007. object.bottomLeftString.isEmpty && object.bottomCenterString.isEmpty && object.bottomRightString.isEmpty {
  1008. return
  1009. }
  1010. if needSave {
  1011. if templateNameTextField.stringValue.isEmpty {
  1012. headerFooterObj.id = initialID
  1013. } else {
  1014. headerFooterObj.id = templateNameTextField.stringValue
  1015. }
  1016. KMHeaderFooterManager.defaultManager.addHeaderFooter(headerFooterObj)
  1017. }
  1018. if let operateCallBack = operateCallBack {
  1019. operateCallBack(headerFooterObj)
  1020. }
  1021. } else if type == .Edit {
  1022. if needSave {
  1023. if templateNameTextField.stringValue.isEmpty {
  1024. headerFooterObj.id = initialID
  1025. } else {
  1026. headerFooterObj.id = templateNameTextField.stringValue
  1027. }
  1028. originalHeaderFooterObj = headerFooterObj.copy() as! KMHeaderFooterObject
  1029. KMHeaderFooterManager.defaultManager.store()
  1030. }
  1031. if let operateCallBack = operateCallBack {
  1032. operateCallBack(originalHeaderFooterObj)
  1033. }
  1034. } else if type == .Use {
  1035. var fileName: String?
  1036. if isBates {
  1037. fileName = "\(pdfDocument.documentURL?.deletingPathExtension().lastPathComponent ?? NSLocalizedString("Untitled", comment: ""))_Bates"
  1038. } else {
  1039. fileName = "\(pdfDocument.documentURL?.deletingPathExtension().lastPathComponent ?? NSLocalizedString("Untitled", comment: ""))_Header_Footer"
  1040. }
  1041. let savePanelAccessoryViewController = KMSavePanelAccessoryController()
  1042. let savePanel = NSSavePanel()
  1043. savePanel.nameFieldStringValue = fileName ?? ""
  1044. savePanel.allowedFileTypes = ["pdf"]
  1045. savePanel.accessoryView = savePanelAccessoryViewController.view
  1046. savePanel.beginSheetModal(for: self.window!) { result in
  1047. if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
  1048. self.saveAsPDFToPath(savePanel.url!.path, autoOpen: savePanelAccessoryViewController.openAutomaticButton.state == .on ? true : false)
  1049. if needSave {
  1050. if self.templateNameTextField.stringValue.isEmpty {
  1051. self.headerFooterObj.id = self.initialID
  1052. } else {
  1053. self.headerFooterObj.id = self.templateNameTextField.stringValue
  1054. }
  1055. KMHeaderFooterManager.defaultManager.addHeaderFooter(self.headerFooterObj)
  1056. NotificationCenter.default.post(name: NSNotification.Name("KMBatchOperateHeaderFootersNotification"), object: self)
  1057. }
  1058. }
  1059. }
  1060. }
  1061. }
  1062. @IBAction func batesprefixChanged(_ sender: NSTextField) {
  1063. headerFooterObj.batesPrefixString = sender.stringValue
  1064. self.updatePDFView()
  1065. }
  1066. @IBAction func batesSuffixChanged(_ sender: NSTextField) {
  1067. headerFooterObj.batesSuffixString = sender.stringValue
  1068. self.updatePDFView()
  1069. }
  1070. @IBAction func batesNumberChanged(_ sender: NSTextField) {
  1071. batesNumberStepper.integerValue = sender.integerValue
  1072. headerFooterObj.batesDigits = sender.integerValue
  1073. self.updatePDFView()
  1074. }
  1075. @IBAction func bateNumberStepperAction(_ sender: NSStepper) {
  1076. batesNumberTextField.integerValue = sender.integerValue
  1077. headerFooterObj.batesDigits = sender.integerValue
  1078. self.updatePDFView()
  1079. }
  1080. @IBAction func batesStartPageComboboxChanged(_ sender: NSComboBox) {
  1081. headerFooterObj.startString = sender.stringValue
  1082. self.updatePDFView()
  1083. }
  1084. }
  1085. extension KMHeaderFooterView{
  1086. func convertPageFormat(_ oldString: String, startPage: String, pageCount: String) -> String {
  1087. var newString = oldString
  1088. for pageFormat in pageFormatArray {
  1089. let formattedPage = "<<\(pageFormat)>>"
  1090. if newString.contains(formattedPage) {
  1091. var tString: String?
  1092. switch formattedPage {
  1093. case "<<1>>":
  1094. tString = "<<\(startPage)>>"
  1095. case "<<1 of n>>":
  1096. tString = "<<\(startPage)>> of \(pageCount)"
  1097. case "<<1/n>>":
  1098. tString = "<<\(startPage)>>/\(pageCount)"
  1099. case "<<Page 1>>":
  1100. tString = "Page \(startPage)"
  1101. case "<<Page 1 of n>>":
  1102. tString = "Page \(startPage) of \(pageCount)"
  1103. default:
  1104. break
  1105. }
  1106. if let tString = tString {
  1107. newString = newString.replacingOccurrences(of: formattedPage, with: tString)
  1108. }
  1109. }
  1110. }
  1111. newString = convertDateFormat(newString)
  1112. return newString
  1113. }
  1114. }