MenuFileCache.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System.IO;
  2. using System.Collections.Generic;
  3. /*
  4. All of this is pretty much stolen from COM3D2.CacheEditMenu. Thanks Mr. Horsington.
  5. https://git.coder.horse/ghorsington/COM3D2.CacheEditMenu
  6. */
  7. namespace COM3D2.MeidoPhotoStudio.Plugin
  8. {
  9. using static MenuFileUtility;
  10. internal class MenuFileCache
  11. {
  12. private const int cacheVersion = 765;
  13. public static readonly string cachePath = Path.Combine(Constants.configPath, "cache.dat");
  14. private Dictionary<string, ModItem> modItems;
  15. private bool rebuild = false;
  16. public ModItem this[string menu]
  17. {
  18. get => modItems[menu];
  19. set
  20. {
  21. if (!modItems.ContainsKey(menu))
  22. {
  23. rebuild = true;
  24. modItems[menu] = value;
  25. }
  26. }
  27. }
  28. public MenuFileCache()
  29. {
  30. modItems = new Dictionary<string, ModItem>();
  31. if (File.Exists(cachePath)) Deserialize();
  32. }
  33. public bool Has(string menuFileName)
  34. {
  35. return modItems.ContainsKey(menuFileName);
  36. }
  37. private void Deserialize()
  38. {
  39. using (BinaryReader binaryReader = new BinaryReader(File.OpenRead(cachePath)))
  40. {
  41. if (binaryReader.ReadInt32() != cacheVersion)
  42. {
  43. Utility.LogInfo($"Cache version out of date. Rebuilding");
  44. return;
  45. }
  46. while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
  47. {
  48. ModItem item = ModItem.Deserialize(binaryReader);
  49. modItems[item.MenuFile] = item;
  50. }
  51. }
  52. }
  53. public void Serialize()
  54. {
  55. if (!rebuild) return;
  56. using (BinaryWriter binaryWriter = new BinaryWriter(File.OpenWrite(cachePath)))
  57. {
  58. binaryWriter.Write(cacheVersion);
  59. foreach (ModItem item in modItems.Values)
  60. {
  61. item.Serialize(binaryWriter);
  62. }
  63. }
  64. }
  65. }
  66. }