KMBackgroundManager.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. //
  2. // KMBackgroundManager.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by tangchao on 2022/12/23.
  6. //
  7. import Cocoa
  8. /*
  9. Pro Mac -> New
  10. New !-> Pro Mac
  11. 1.Pro Mac New 更新 Pro Mac 的模板,会新建新的 New 模板(原数据保存不变) 会出现两个
  12. 2.Pro Mac 删除
  13. */
  14. class KMBackgroundManager: NSObject {
  15. let kBackgroundFolderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("background")
  16. let kBackgroundPlistPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("background").stringByAppendingPathComponent("background.plist")
  17. let kBackgroundImageFolder = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.applicationSupportDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last?.stringByAppendingPathComponent(Bundle.main.bundleIdentifier!).stringByAppendingPathComponent("background").stringByAppendingPathComponent("image")
  18. static let defaultManager = KMBackgroundManager()
  19. static let kRemovedKey = "KMBackgroundRemovedKey"
  20. var datas: Array<KMBackgroundModel> = []
  21. var defaultModel: KMBackgroundModel = KMBackgroundModel() //新增模板时的数据。
  22. override init() {
  23. super.init()
  24. print("kBackgroundFolderPath = \(kBackgroundFolderPath ?? "")")
  25. if (!FileManager.default.fileExists(atPath: kBackgroundFolderPath!)) {
  26. let create: ()? = try?FileManager.default.createDirectory(atPath: kBackgroundFolderPath!, withIntermediateDirectories: false)
  27. }
  28. if (!FileManager.default.fileExists(atPath: kBackgroundImageFolder!)) {
  29. let create: ()? = try?FileManager.default.createDirectory(atPath: kBackgroundImageFolder!, withIntermediateDirectories: false)
  30. }
  31. if (FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  32. let dataDict = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  33. if (dataDict == nil) {
  34. return
  35. }
  36. let deleteKeys: Array<String> = []
  37. for keyIndex in 0 ..< (dataDict?.allKeys.count)! {
  38. let key: String = dataDict?.allKeys[keyIndex] as! String
  39. let backgroundDict: NSDictionary = dataDict?.object(forKey: key) as! NSDictionary
  40. let model = parseDictionaryToModel(dict: backgroundDict)
  41. model.backgroundID = key
  42. if (model.type == .image) {
  43. self.datas.append(model)
  44. } else {
  45. self.datas.append(model)
  46. }
  47. }
  48. if (deleteKeys.count > 0) {
  49. let newDict: NSMutableDictionary = NSMutableDictionary(dictionary: dataDict!)
  50. for key in deleteKeys {
  51. newDict.removeObject(forKey: key)
  52. }
  53. newDict.write(toFile: kBackgroundPlistPath!, atomically: true)
  54. }
  55. }
  56. defaultModel.name = fetchAvailableBackgroundName()
  57. }
  58. //MARK: - 增删改查
  59. func addTemplate(model: KMBackgroundModel) -> Bool {
  60. if (!FileManager.default.fileExists(atPath: kBackgroundFolderPath!)) {
  61. let create: ()? = try?FileManager.default.createDirectory(atPath: kBackgroundFolderPath!, withIntermediateDirectories: false)
  62. if (create == nil) {
  63. return false
  64. }
  65. }
  66. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  67. let create = try?FileManager.default.createFile(atPath: kBackgroundPlistPath!, contents: nil)
  68. if (create == nil) {
  69. return false
  70. }
  71. }
  72. let dict = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  73. var newDict:NSMutableDictionary!
  74. if (dict != nil) {
  75. newDict = NSMutableDictionary(dictionary: dict!)
  76. } else {
  77. newDict = NSMutableDictionary()
  78. }
  79. let backgroundDict = self.parseModelToDict(model: model)
  80. if (backgroundDict.isEmpty) {
  81. let alert = NSAlert()
  82. alert.alertStyle = .critical
  83. alert.messageText = NSLocalizedString("文件\(model.imagePath?.lastPathComponent)已损坏", comment: "")
  84. alert.runModal()
  85. return false
  86. }
  87. let tag = model.backgroundID
  88. newDict.addEntries(from: [tag : backgroundDict])
  89. let result = newDict.write(toFile: kBackgroundPlistPath!, atomically: true)
  90. if (result) {
  91. if (self.datas.count < 1) {
  92. self.datas.append(model)
  93. } else {
  94. self.datas.insert(model, at: 0)
  95. }
  96. model.updatePreviewImage()
  97. }
  98. return result
  99. }
  100. func deleteTemplate(model: KMBackgroundModel) -> Bool {
  101. if (model.backgroundID.isEmpty) {
  102. return false
  103. }
  104. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  105. return false
  106. }
  107. let key: String = model.backgroundID
  108. let dictionary = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  109. var newDictionary: NSMutableDictionary!
  110. if (dictionary != nil) {
  111. newDictionary = NSMutableDictionary(dictionary: dictionary!)
  112. } else {
  113. newDictionary = NSMutableDictionary()
  114. }
  115. newDictionary.removeObject(forKey: key)
  116. let result = newDictionary.write(toFile: kBackgroundPlistPath!, atomically: true)
  117. if (result) {
  118. model.removeModelCacheInfo()
  119. if (self.datas.contains(model)) {
  120. self.datas.removeObject(model)
  121. }
  122. }
  123. return result
  124. }
  125. func deleteAllTemplates() -> Bool {
  126. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  127. return false
  128. }
  129. let dictionary = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  130. var newDictionary: NSMutableDictionary!
  131. if (dictionary != nil) {
  132. newDictionary = NSMutableDictionary(dictionary: dictionary!)
  133. } else {
  134. newDictionary = NSMutableDictionary()
  135. }
  136. newDictionary.removeAllObjects()
  137. let result = newDictionary.write(toFile: kBackgroundPlistPath!, atomically: true)
  138. if (result) {
  139. self.datas.removeAll()
  140. }
  141. KMDataManager.ud_set(nil, forKey: Self.kRemovedKey)
  142. return result
  143. }
  144. func deleteAllColorTemplates() -> Bool {
  145. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  146. return false
  147. }
  148. let dictionary = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  149. var newDictionary: NSMutableDictionary!
  150. if (dictionary != nil) {
  151. newDictionary = NSMutableDictionary(dictionary: dictionary!)
  152. } else {
  153. newDictionary = NSMutableDictionary()
  154. }
  155. let count = self.datas.count-1
  156. var deleteArray: Array<KMBackgroundModel> = []
  157. for i in 0 ... count {
  158. let model = self.datas[i]
  159. if (model.type == .color) {
  160. newDictionary.removeObject(forKey: model.backgroundID as Any)
  161. deleteArray.append(model)
  162. }
  163. }
  164. let result = newDictionary.write(toFile: kBackgroundPlistPath!, atomically: true)
  165. if (result) {
  166. for model in deleteArray {
  167. self.datas.removeObject(model)
  168. }
  169. }
  170. return result
  171. }
  172. func deleteAllFileTemplates() -> Bool {
  173. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  174. return false
  175. }
  176. let dictionary = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  177. var newDictionary: NSMutableDictionary!
  178. if (dictionary != nil) {
  179. newDictionary = NSMutableDictionary(dictionary: dictionary!)
  180. } else {
  181. newDictionary = NSMutableDictionary()
  182. }
  183. let count = self.datas.count-1
  184. var deleteArray: Array<KMBackgroundModel> = []
  185. for i in 0 ... count {
  186. let model = self.datas[i]
  187. if (model.type == .image) {
  188. newDictionary.removeObject(forKey: model.backgroundID as Any)
  189. deleteArray.append(model)
  190. }
  191. }
  192. let result = newDictionary.write(toFile: kBackgroundPlistPath!, atomically: true)
  193. if (result) {
  194. for model in deleteArray {
  195. self.datas.removeObject(model)
  196. }
  197. }
  198. return result
  199. }
  200. func updateTemplate(model: KMBackgroundModel) -> Bool {
  201. if (!FileManager.default.fileExists(atPath: kBackgroundFolderPath!)) {
  202. let create = try?FileManager.default.createDirectory(atPath: kBackgroundFolderPath!, withIntermediateDirectories: false)
  203. if (create == nil) {
  204. return false
  205. }
  206. }
  207. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  208. let create = try?FileManager.default.createFile(atPath: kBackgroundPlistPath!, contents: nil)
  209. if (create == nil) {
  210. return false
  211. }
  212. }
  213. var flagModel: KMBackgroundModel!
  214. for model_ in self.datas {
  215. if (model_.backgroundID == model.backgroundID) {
  216. flagModel = model_
  217. break
  218. }
  219. }
  220. if (flagModel == nil) {
  221. return false
  222. }
  223. let dict = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  224. var newDict:NSMutableDictionary!
  225. if (dict != nil) {
  226. newDict = NSMutableDictionary(dictionary: dict!)
  227. } else {
  228. newDict = NSMutableDictionary()
  229. }
  230. let modelDict = self.parseModelToDict(model: model)
  231. if (modelDict.isEmpty) {
  232. let alert = NSAlert()
  233. alert.alertStyle = .critical
  234. // alert.messageText = NSLocalizedString("文件\(model.imagePath?.lastPathComponent)已损坏", comment: "")
  235. alert.runModal()
  236. return false
  237. }
  238. newDict.setObject(modelDict, forKey: flagModel.backgroundID as NSCopying)
  239. let result = newDict.write(toFile: kBackgroundPlistPath!, atomically: true)
  240. if (result) {
  241. if let index = self.datas.firstIndex(of: flagModel) {
  242. self.datas[index] = model
  243. }
  244. model.updatePreviewImage()
  245. }
  246. return result
  247. }
  248. func updateModel(_ model: KMBackgroundModel, withDict dict: NSDictionary) {
  249. model.type = CPDFBackgroundType(rawValue: dict.object(forKey: "type") as! Int)!
  250. if (model.type == .image) {
  251. model.imagePath = (dict.object(forKey: "imagePath") as! String)
  252. } else {
  253. if let value = dict.object(forKey: "color") {
  254. model.color = NSColor.km_init(hex: value as! String)
  255. }
  256. }
  257. model.scale = dict.object(forKey: "scale") as! CGFloat
  258. model.rotation = CGFloat(Int(dict.object(forKey: "rotation") as! CGFloat))
  259. model.opacity = (dict.object(forKey: "opacity") as! CGFloat)
  260. model.verticalMode = (dict.object(forKey: "verticalMode") as! Int)
  261. model.verticalSpace = (dict.object(forKey: "verticalSpace") as! CGFloat)
  262. model.horizontalMode = (dict.object(forKey: "horizontalMode") as! Int)
  263. model.horizontalSpace = (dict.object(forKey: "horizontalSpace") as! CGFloat)
  264. model.backgroundID = dict.object(forKey: "backgroundID") as! String
  265. if let value = dict.object(forKey: "name") {
  266. model.name = value as! String
  267. }
  268. }
  269. func updateBackground(_ background: CPDFBackground, withModel model: KMBackgroundModel) {
  270. background.type = model.type
  271. background.color = model.color
  272. background.setImage(model.image())
  273. background.rotation = model.rotation
  274. background.opacity = model.opacity
  275. background.scale = model.scale
  276. background.verticalAlignment = UInt(model.verticalMode)
  277. background.yOffset = model.verticalSpace
  278. background.horizontalAlignment = UInt(model.horizontalMode)
  279. background.xOffset = model.horizontalSpace
  280. }
  281. //MARK: - parse
  282. func parseModelToDict(model: KMBackgroundModel) -> Dictionary<String, Any> {
  283. var dict: [String : Any] = [:]
  284. if (model.type == .color) {
  285. dict["color"] = model.color?.colorToHexString()
  286. } else {
  287. dict["imagePath"] = model.imagePath
  288. }
  289. dict["type"] = model.type.rawValue
  290. dict["scale"] = model.scale
  291. dict["opacity"] = model.opacity
  292. dict["rotation"] = model.rotation
  293. dict["horizontalMode"] = model.horizontalMode
  294. dict["horizontalSpace"] = model.horizontalSpace
  295. dict["verticalMode"] = model.verticalMode
  296. dict["verticalSpace"] = model.verticalSpace
  297. dict["backgroundID"] = model.backgroundID
  298. dict["name"] = model.name
  299. return dict
  300. }
  301. private func parseDictionaryToModel(dict: NSDictionary) -> KMBackgroundModel {
  302. let model = KMBackgroundModel()
  303. model.type = CPDFBackgroundType(rawValue: dict.object(forKey: "type") as! Int)!
  304. if (model.type == .image) {
  305. if let value = dict.object(forKey: "imagePath") {
  306. model.imagePath = value as? String
  307. }
  308. } else {
  309. if let value = dict.object(forKey: "color") {
  310. model.color = NSColor.km_init(hex: value as! String)
  311. }
  312. }
  313. model.scale = dict.object(forKey: "scale") as! CGFloat
  314. model.rotation = CGFloat(Int(dict.object(forKey: "rotation") as! CGFloat))
  315. model.opacity = (dict.object(forKey: "opacity") as! CGFloat)
  316. model.verticalMode = (dict.object(forKey: "verticalMode") as! Int)
  317. model.verticalSpace = (dict.object(forKey: "verticalSpace") as! CGFloat)
  318. model.horizontalMode = (dict.object(forKey: "horizontalMode") as! Int)
  319. model.horizontalSpace = (dict.object(forKey: "horizontalSpace") as! CGFloat)
  320. if let value = dict.object(forKey: "backgroundID") {
  321. model.backgroundID = value as! String
  322. }
  323. if let value = dict.object(forKey: "name") {
  324. model.name = value as! String
  325. }
  326. return model
  327. }
  328. //MARK: - Compare
  329. class func compareIsChangedModel(_ model: KMBackgroundModel, withDict dict: NSDictionary) -> Bool {
  330. if let value = dict["type"] {
  331. if model.type != CPDFBackgroundType(rawValue: value as! Int)! {
  332. return true
  333. }
  334. }
  335. if let value = dict["color"] {
  336. if model.color?.colorToHexString() != (value as! String) {
  337. return true
  338. }
  339. }
  340. if let value = dict["rotation"] {
  341. if model.rotation != (value as! CGFloat) {
  342. return true
  343. }
  344. }
  345. if let value = dict["opacity"] {
  346. if model.opacity != (value as! CGFloat) {
  347. return true
  348. }
  349. }
  350. if let value = dict["scale"] {
  351. if model.scale != (value as! CGFloat) {
  352. return true
  353. }
  354. }
  355. if let value = dict["verticalMode"] {
  356. if model.verticalMode != (value as! Int) {
  357. return true
  358. }
  359. }
  360. if let value = dict["verticalSpace"] {
  361. if model.verticalSpace != (value as! CGFloat) {
  362. return true
  363. }
  364. }
  365. if let value = dict["horizontalMode"] {
  366. if model.horizontalMode != (value as! Int) {
  367. return true
  368. }
  369. }
  370. if let value = dict["horizontalSpace"] {
  371. if model.horizontalSpace != (value as! CGFloat) {
  372. return true
  373. }
  374. }
  375. return false
  376. }
  377. //MARK: - Get
  378. func fetchAvailableBackgroundName() -> String {
  379. var availableIndex = 1
  380. for item in datas {
  381. if item.name.hasPrefix("Background-") {
  382. if let index = Int(item.name.dropFirst("Background-".count)), index >= availableIndex {
  383. availableIndex = index + 1
  384. }
  385. }
  386. }
  387. return "Background-\(availableIndex)"
  388. }
  389. }