KMBackgroundManager.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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. if (model.type == .image) {
  119. let filePath: String = model.imagePath ?? ""
  120. try?FileManager.default.removeItem(atPath: filePath)
  121. }
  122. if (self.datas.contains(model)) {
  123. self.datas.removeObject(model)
  124. }
  125. }
  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. return result
  146. }
  147. func deleteAllColorTemplates() -> Bool {
  148. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  149. return false
  150. }
  151. let dictionary = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  152. var newDictionary: NSMutableDictionary!
  153. if (dictionary != nil) {
  154. newDictionary = NSMutableDictionary(dictionary: dictionary!)
  155. } else {
  156. newDictionary = NSMutableDictionary()
  157. }
  158. let count = self.datas.count-1
  159. var deleteArray: Array<KMBackgroundModel> = []
  160. for i in 0 ... count {
  161. let model = self.datas[i]
  162. if (model.type == .color) {
  163. newDictionary.removeObject(forKey: model.backgroundID as Any)
  164. deleteArray.append(model)
  165. }
  166. }
  167. let result = newDictionary.write(toFile: kBackgroundPlistPath!, atomically: true)
  168. if (result) {
  169. for model in deleteArray {
  170. self.datas.removeObject(model)
  171. }
  172. }
  173. return result
  174. }
  175. func deleteAllFileTemplates() -> Bool {
  176. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  177. return false
  178. }
  179. let dictionary = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  180. var newDictionary: NSMutableDictionary!
  181. if (dictionary != nil) {
  182. newDictionary = NSMutableDictionary(dictionary: dictionary!)
  183. } else {
  184. newDictionary = NSMutableDictionary()
  185. }
  186. let count = self.datas.count-1
  187. var deleteArray: Array<KMBackgroundModel> = []
  188. for i in 0 ... count {
  189. let model = self.datas[i]
  190. if (model.type == .image) {
  191. newDictionary.removeObject(forKey: model.backgroundID as Any)
  192. deleteArray.append(model)
  193. }
  194. }
  195. let result = newDictionary.write(toFile: kBackgroundPlistPath!, atomically: true)
  196. if (result) {
  197. for model in deleteArray {
  198. self.datas.removeObject(model)
  199. }
  200. }
  201. return result
  202. }
  203. func updateTemplate(model: KMBackgroundModel) -> Bool {
  204. if (!FileManager.default.fileExists(atPath: kBackgroundFolderPath!)) {
  205. let create = try?FileManager.default.createDirectory(atPath: kBackgroundFolderPath!, withIntermediateDirectories: false)
  206. if (create == nil) {
  207. return false
  208. }
  209. }
  210. if (!FileManager.default.fileExists(atPath: kBackgroundPlistPath!)) {
  211. let create = try?FileManager.default.createFile(atPath: kBackgroundPlistPath!, contents: nil)
  212. if (create == nil) {
  213. return false
  214. }
  215. }
  216. var flagModel: KMBackgroundModel!
  217. for model_ in self.datas {
  218. if (model_.backgroundID == model.backgroundID) {
  219. flagModel = model_
  220. break
  221. }
  222. }
  223. if (flagModel == nil) {
  224. return false
  225. }
  226. let dict = NSDictionary(contentsOfFile: kBackgroundPlistPath!)
  227. var newDict:NSMutableDictionary!
  228. if (dict != nil) {
  229. newDict = NSMutableDictionary(dictionary: dict!)
  230. } else {
  231. newDict = NSMutableDictionary()
  232. }
  233. let modelDict = self.parseModelToDict(model: model)
  234. if (modelDict.isEmpty) {
  235. let alert = NSAlert()
  236. alert.alertStyle = .critical
  237. // alert.messageText = NSLocalizedString("文件\(model.imagePath?.lastPathComponent)已损坏", comment: "")
  238. alert.runModal()
  239. return false
  240. }
  241. newDict.setObject(modelDict, forKey: flagModel.backgroundID as NSCopying)
  242. let result = newDict.write(toFile: kBackgroundPlistPath!, atomically: true)
  243. if (result) {
  244. if let index = self.datas.firstIndex(of: flagModel) {
  245. self.datas[index] = model
  246. }
  247. model.updatePreviewImage()
  248. }
  249. return result
  250. }
  251. func updateModel(_ model: KMBackgroundModel, withDict dict: NSDictionary) {
  252. model.type = CPDFBackgroundType(rawValue: dict.object(forKey: "type") as! Int)!
  253. if (model.type == .image) {
  254. model.imagePath = (dict.object(forKey: "imagePath") as! String)
  255. } else {
  256. if let value = dict.object(forKey: "color") {
  257. model.color = NSColor.km_init(hex: value as! String)
  258. }
  259. }
  260. model.scale = dict.object(forKey: "scale") as! CGFloat
  261. model.rotation = CGFloat(Int(dict.object(forKey: "rotation") as! CGFloat))
  262. model.opacity = (dict.object(forKey: "opacity") as! CGFloat)
  263. model.verticalMode = (dict.object(forKey: "verticalMode") as! Int)
  264. model.verticalSpace = (dict.object(forKey: "verticalSpace") as! CGFloat)
  265. model.horizontalMode = (dict.object(forKey: "horizontalMode") as! Int)
  266. model.horizontalSpace = (dict.object(forKey: "horizontalSpace") as! CGFloat)
  267. model.backgroundID = dict.object(forKey: "backgroundID") as! String
  268. if let value = dict.object(forKey: "name") {
  269. model.name = value as! String
  270. }
  271. }
  272. func updateBackground(_ background: CPDFBackground, withModel model: KMBackgroundModel) {
  273. background.type = model.type
  274. background.color = model.color
  275. background.setImage(model.image())
  276. background.rotation = model.rotation
  277. background.opacity = model.opacity
  278. background.scale = model.scale
  279. background.verticalAlignment = UInt(model.verticalMode)
  280. background.yOffset = model.verticalSpace
  281. background.horizontalAlignment = UInt(model.horizontalMode)
  282. background.xOffset = model.horizontalSpace
  283. }
  284. //MARK: - parse
  285. func parseModelToDict(model: KMBackgroundModel) -> Dictionary<String, Any> {
  286. var dict: [String : Any] = [:]
  287. if (model.type == .color) {
  288. dict["color"] = model.color?.colorToHexString()
  289. } else {
  290. dict["imagePath"] = model.imagePath
  291. }
  292. dict["type"] = model.type.rawValue
  293. dict["scale"] = model.scale
  294. dict["opacity"] = model.opacity
  295. dict["rotation"] = model.rotation
  296. dict["horizontalMode"] = model.horizontalMode
  297. dict["horizontalSpace"] = model.horizontalSpace
  298. dict["verticalMode"] = model.verticalMode
  299. dict["verticalSpace"] = model.verticalSpace
  300. dict["backgroundID"] = model.backgroundID
  301. dict["name"] = model.name
  302. return dict
  303. }
  304. private func parseDictionaryToModel(dict: NSDictionary) -> KMBackgroundModel {
  305. let model = KMBackgroundModel()
  306. model.type = CPDFBackgroundType(rawValue: dict.object(forKey: "type") as! Int)!
  307. if (model.type == .image) {
  308. if let value = dict.object(forKey: "imagePath") {
  309. model.imagePath = value as? String
  310. }
  311. } else {
  312. if let value = dict.object(forKey: "color") {
  313. model.color = NSColor.km_init(hex: value as! String)
  314. }
  315. }
  316. model.scale = dict.object(forKey: "scale") as! CGFloat
  317. model.rotation = CGFloat(Int(dict.object(forKey: "rotation") as! CGFloat))
  318. model.opacity = (dict.object(forKey: "opacity") as! CGFloat)
  319. model.verticalMode = (dict.object(forKey: "verticalMode") as! Int)
  320. model.verticalSpace = (dict.object(forKey: "verticalSpace") as! CGFloat)
  321. model.horizontalMode = (dict.object(forKey: "horizontalMode") as! Int)
  322. model.horizontalSpace = (dict.object(forKey: "horizontalSpace") as! CGFloat)
  323. if let value = dict.object(forKey: "backgroundID") {
  324. model.backgroundID = value as! String
  325. }
  326. if let value = dict.object(forKey: "name") {
  327. model.name = value as! String
  328. }
  329. return model
  330. }
  331. //MARK: - Compare
  332. class func compareIsChangedModel(_ model: KMBackgroundModel, withDict dict: NSDictionary) -> Bool {
  333. if let value = dict["type"] {
  334. if model.type != CPDFBackgroundType(rawValue: value as! Int)! {
  335. return true
  336. }
  337. }
  338. if let value = dict["color"] {
  339. if model.color?.colorToHexString() != (value as! String) {
  340. return true
  341. }
  342. }
  343. if let value = dict["rotation"] {
  344. if model.rotation != (value as! CGFloat) {
  345. return true
  346. }
  347. }
  348. if let value = dict["opacity"] {
  349. if model.opacity != (value as! CGFloat) {
  350. return true
  351. }
  352. }
  353. if let value = dict["scale"] {
  354. if model.scale != (value as! CGFloat) {
  355. return true
  356. }
  357. }
  358. if let value = dict["verticalMode"] {
  359. if model.verticalMode != (value as! Int) {
  360. return true
  361. }
  362. }
  363. if let value = dict["verticalSpace"] {
  364. if model.verticalSpace != (value as! CGFloat) {
  365. return true
  366. }
  367. }
  368. if let value = dict["horizontalMode"] {
  369. if model.horizontalMode != (value as! Int) {
  370. return true
  371. }
  372. }
  373. if let value = dict["horizontalSpace"] {
  374. if model.horizontalSpace != (value as! CGFloat) {
  375. return true
  376. }
  377. }
  378. return false
  379. }
  380. //MARK: - Get
  381. func fetchAvailableBackgroundName() -> String {
  382. var availableIndex = 0
  383. for item in datas {
  384. if item.name.hasPrefix("Background") {
  385. if let index = Int(item.name.dropFirst("Background".count)), index >= availableIndex {
  386. availableIndex = index + 1
  387. }
  388. }
  389. }
  390. return "Background\(availableIndex)"
  391. }
  392. }