KMHeaderFooterView.swift 55 KB

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