KMBackgroundManager.swift 18 KB

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