KMBackgroundManager.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. //
  2. // KMBackgroundManager.swift
  3. // PDF Master
  4. //
  5. // Created by tangchao on 2022/12/23.
  6. //
  7. import Cocoa
  8. class KMBackgroundManager: NSObject {
  9. let kBackgroundFolderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("background")
  10. let kBackgroundPlistPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("background").stringByAppendingPathComponent("background.plist")
  11. var datas: Array<KMBackgroundModel> = []
  12. static let defaultManager = KMBackgroundManager()
  13. override init() {
  14. super.init()
  15. if (FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  16. let dataDict = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  17. if (dataDict == nil) {
  18. return
  19. }
  20. var deleteKeys: Array<String> = []
  21. for keyIndex in 0 ..< (dataDict?.allKeys.count)! {
  22. let key: String = dataDict?.allKeys[keyIndex] as! String
  23. let backgroundDict: NSDictionary = dataDict?.object(forKey: key) as! NSDictionary
  24. let model = parseDictionary(dict: backgroundDict)
  25. /// 赋值id
  26. model.backgroundID = key
  27. if (model.type == .file) {
  28. if (model.image == nil) {
  29. deleteKeys.append(key)
  30. } else {
  31. self.datas.append(model)
  32. }
  33. } else {
  34. self.datas.append(model)
  35. }
  36. }
  37. if (deleteKeys.count > 0) {
  38. var newDict: NSMutableDictionary = NSMutableDictionary(dictionary: dataDict!)
  39. for key in deleteKeys {
  40. newDict.removeObject(forKey: key)
  41. }
  42. newDict.write(toFile: kBackgroundPlistPath!, atomically: true)
  43. }
  44. }
  45. }
  46. func addTemplate(model: KMBackgroundModel) -> Bool {
  47. if (!FileManager.default.fileExists(atPath: kBackgroundFolderPath!)) {
  48. let create: ()? = try?FileManager.default.createDirectory(atPath: kBackgroundFolderPath!, withIntermediateDirectories: false)
  49. if (create == nil) {
  50. return false
  51. }
  52. }
  53. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  54. let create = try?FileManager.default.createFile(atPath: kBackgroundPlistPath!, contents: nil)
  55. if (create == nil) {
  56. return false
  57. }
  58. }
  59. let dict = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  60. var newDict:NSMutableDictionary!
  61. if (dict != nil) {
  62. newDict = NSMutableDictionary(dictionary: dict!)
  63. } else {
  64. newDict = NSMutableDictionary()
  65. }
  66. let backgroundDict = self.parseModel(model: model)
  67. if (backgroundDict.isEmpty) {
  68. let alert = NSAlert()
  69. alert.alertStyle = .critical
  70. alert.messageText = NSLocalizedString("文件\(model.imagePath.lastPathComponent)已损坏", comment: "")
  71. alert.runModal()
  72. return false
  73. }
  74. let tag = tagString()
  75. newDict.addEntries(from: [tag : backgroundDict])
  76. model.backgroundID = tag
  77. let result = newDict.write(toFile: kBackgroundPlistPath!, atomically: true)
  78. if (result) {
  79. if (self.datas.count < 1) {
  80. self.datas.append(model)
  81. } else {
  82. self.datas.insert(model, at: 0)
  83. }
  84. }
  85. return result
  86. }
  87. func deleteTemplate(model: KMBackgroundModel) -> Bool {
  88. if (model.backgroundID.isEmpty) {
  89. return false
  90. }
  91. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  92. return false
  93. }
  94. let key: String = model.backgroundID
  95. let dictionary = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  96. var newDictionary: NSMutableDictionary!
  97. if (dictionary != nil) {
  98. newDictionary = NSMutableDictionary(dictionary: dictionary!)
  99. } else {
  100. newDictionary = NSMutableDictionary()
  101. }
  102. newDictionary.removeObject(forKey: key)
  103. let result = newDictionary.write(toFile: kBackgroundPlistPath!, atomically: true)
  104. if (result) {
  105. if (model.type == .file) {
  106. let filePath: String = model.imagePath
  107. try?FileManager.default.removeItem(atPath: filePath)
  108. }
  109. if (self.datas.contains(model)) {
  110. self.datas.removeObject(model)
  111. }
  112. }
  113. return result
  114. }
  115. func deleteAllTemplates() -> Bool {
  116. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  117. return false
  118. }
  119. let dictionary = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  120. var newDictionary: NSMutableDictionary!
  121. if (dictionary != nil) {
  122. newDictionary = NSMutableDictionary(dictionary: dictionary!)
  123. } else {
  124. newDictionary = NSMutableDictionary()
  125. }
  126. newDictionary.removeAllObjects()
  127. let result = newDictionary.write(toFile: kBackgroundPlistPath!, atomically: true)
  128. if (result) {
  129. self.datas.removeAll()
  130. }
  131. return result
  132. }
  133. func deleteAllColorTemplates() -> Bool {
  134. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  135. return false
  136. }
  137. let dictionary = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  138. var newDictionary: NSMutableDictionary!
  139. if (dictionary != nil) {
  140. newDictionary = NSMutableDictionary(dictionary: dictionary!)
  141. } else {
  142. newDictionary = NSMutableDictionary()
  143. }
  144. let count = self.datas.count-1
  145. var deleteArray: Array<KMBackgroundModel> = []
  146. for i in 0 ... count {
  147. let model = self.datas[i]
  148. if (model.type == .color) {
  149. newDictionary.removeObject(forKey: model.backgroundID as Any)
  150. deleteArray.append(model)
  151. }
  152. }
  153. let result = newDictionary.write(toFile: kBackgroundPlistPath!, atomically: true)
  154. if (result) {
  155. for model in deleteArray {
  156. self.datas.removeObject(model)
  157. }
  158. }
  159. return result
  160. }
  161. func deleteAllFileTemplates() -> Bool {
  162. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  163. return false
  164. }
  165. let dictionary = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  166. var newDictionary: NSMutableDictionary!
  167. if (dictionary != nil) {
  168. newDictionary = NSMutableDictionary(dictionary: dictionary!)
  169. } else {
  170. newDictionary = NSMutableDictionary()
  171. }
  172. let count = self.datas.count-1
  173. var deleteArray: Array<KMBackgroundModel> = []
  174. for i in 0 ... count {
  175. let model = self.datas[i]
  176. if (model.type == .file) {
  177. newDictionary.removeObject(forKey: model.backgroundID as Any)
  178. deleteArray.append(model)
  179. }
  180. }
  181. let result = newDictionary.write(toFile: kBackgroundPlistPath!, atomically: true)
  182. if (result) {
  183. for model in deleteArray {
  184. self.datas.removeObject(model)
  185. }
  186. }
  187. return result
  188. }
  189. func updateTemplate(model: KMBackgroundModel) -> Bool {
  190. if (!FileManager.default.fileExists(atPath: kBackgroundFolderPath!)) {
  191. let create = try?FileManager.default.createDirectory(atPath: kBackgroundFolderPath!, withIntermediateDirectories: false)
  192. if (create == nil) {
  193. return false
  194. }
  195. }
  196. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  197. let create = try?FileManager.default.createFile(atPath: kBackgroundPlistPath!, contents: nil)
  198. if (create == nil) {
  199. return false
  200. }
  201. }
  202. var flagModel: KMBackgroundModel!
  203. for model_ in self.datas {
  204. if (model_.backgroundID == model.backgroundID) {
  205. flagModel = model_
  206. break
  207. }
  208. }
  209. if (flagModel == nil) {
  210. return false
  211. }
  212. let dict = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  213. var newDict:NSMutableDictionary!
  214. if (dict != nil) {
  215. newDict = NSMutableDictionary(dictionary: dict!)
  216. } else {
  217. newDict = NSMutableDictionary()
  218. }
  219. let modelDict = self.parseModel(model: model)
  220. if (modelDict.isEmpty) {
  221. let alert = NSAlert()
  222. alert.alertStyle = .critical
  223. alert.messageText = NSLocalizedString("文件\(model.imagePath.lastPathComponent)已损坏", comment: "")
  224. alert.runModal()
  225. return false
  226. }
  227. newDict.setObject(modelDict, forKey: flagModel.backgroundID as NSCopying)
  228. let result = newDict.write(toFile: kBackgroundPlistPath!, atomically: true)
  229. if (result) {
  230. let index = self.datas.index(of: flagModel)
  231. self.datas[index!] = model
  232. }
  233. return result
  234. }
  235. /**
  236. `Private Methods`
  237. */
  238. private func parseModel(model: KMBackgroundModel) -> Dictionary<String, Any> {
  239. let tag = tagString()
  240. var dict: [String : Any] = [:]
  241. if (model.type == .color) {
  242. var red: CGFloat = 0.0
  243. var green: CGFloat = 0.0
  244. var blue: CGFloat = 0.0
  245. model.color!.usingColorSpaceName(NSColorSpaceName.calibratedRGB)?.getRed(&red, green: &green, blue: &blue, alpha: nil)
  246. dict["red"] = red
  247. dict["green"] = green
  248. dict["blue"] = blue
  249. } else {
  250. if (!FileManager.default.fileExists(atPath: kBackgroundFolderPath!)) {
  251. try?FileManager.default.createDirectory(atPath: kBackgroundFolderPath!, withIntermediateDirectories: false)
  252. }
  253. let path = kBackgroundFolderPath?.stringByAppendingPathComponent("\(tag).png")
  254. let image = model.image
  255. let data = image?.tiffRepresentation
  256. let imageRep = NSBitmapImageRep(data: data!)
  257. imageRep?.size = image!.size
  258. var imageData: Data!
  259. let pathExtension = model.imagePath.components(separatedBy: ".").last
  260. if (pathExtension?.lowercased() == "png") {
  261. imageData = imageRep?.representation(using: NSBitmapImageRep.FileType.png, properties: [:])
  262. } else {
  263. imageData = imageRep?.representation(using: NSBitmapImageRep.FileType.jpeg, properties: [:])
  264. }
  265. do {
  266. try imageData.write(to: URL(fileURLWithPath: path!))
  267. dict["imagePath"] = path?.lastPathComponent
  268. }
  269. catch {
  270. KMPrint("Failed to write to disk.")
  271. return [:]
  272. }
  273. }
  274. dict["type"] = model.type.rawValue
  275. dict["scale"] = model.scale
  276. dict["opacity"] = model.opacity
  277. dict["rotation"] = model.rotation
  278. dict["horizontalMode"] = model.horizontalMode
  279. dict["horizontalSpace"] = model.horizontalSpace
  280. dict["verticalMode"] = model.verticalMode
  281. dict["verticalSpace"] = model.verticalSpace
  282. dict["pageRangeType"] = model.pageRangeType
  283. dict["pagesString"] = model.pagesString
  284. return dict
  285. }
  286. private func parseDictionary(dict: NSDictionary) -> KMBackgroundModel {
  287. let model = KMBackgroundModel()
  288. model.type = KMBackgroundType(rawValue: dict.object(forKey: "type") as! Int)!
  289. if (model.type == .file) {
  290. let path = kBackgroundFolderPath?.stringByAppendingPathComponent(dict.object(forKey: "imagePath") as! String)
  291. if (FileManager.default.fileExists(atPath: path!)) {
  292. model.image = NSImage(contentsOfFile: path!)
  293. model.imagePath = path!
  294. } else {
  295. model.image = nil
  296. }
  297. } else {
  298. let red: CGFloat = dict.object(forKey: "red") as! CGFloat
  299. let green: CGFloat = dict.object(forKey: "green") as! CGFloat
  300. let blue: CGFloat = dict.object(forKey: "blue") as! CGFloat
  301. model.color = NSColor(red: red, green: green, blue: blue, alpha: 1.0)
  302. }
  303. model.scale = dict.object(forKey: "scale") as! CGFloat
  304. model.rotation = Int(dict.object(forKey: "rotation") as! CGFloat)
  305. model.opacity = (dict.object(forKey: "opacity") as! CGFloat)
  306. model.verticalMode = (dict.object(forKey: "verticalMode") as! Int)
  307. model.verticalSpace = (dict.object(forKey: "verticalSpace") as! CGFloat)
  308. model.horizontalMode = (dict.object(forKey: "horizontalMode") as! Int)
  309. model.horizontalSpace = (dict.object(forKey: "horizontalSpace") as! CGFloat)
  310. model.pageRangeType = (dict.object(forKey: "pageRangeType") as! Int)
  311. model.pagesString = (dict.object(forKey: "pagesString") as! String)
  312. return model
  313. }
  314. private func tagString() -> String {
  315. var result: String = ""
  316. let dateFormatter = DateFormatter()
  317. dateFormatter.dateFormat = "yyMMddHHmmss"
  318. result.append(dateFormatter.string(from: Date()))
  319. result = result.appendingFormat("%04d", arc4random()%10000)
  320. return result
  321. }
  322. }