MenuFileCache.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. public class MenuFileCache
  11. {
  12. private const int cacheVersion = 765;
  13. public static readonly string cachePath = Path.Combine(Constants.configPath, "cache.dat");
  14. private readonly Dictionary<string, ModItem> modItems;
  15. private bool rebuild;
  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) => modItems.ContainsKey(menuFileName);
  34. private void Deserialize()
  35. {
  36. using (BinaryReader binaryReader = new BinaryReader(File.OpenRead(cachePath)))
  37. {
  38. if (binaryReader.ReadInt32() != cacheVersion)
  39. {
  40. Utility.LogInfo("Cache version out of date. Rebuilding");
  41. return;
  42. }
  43. while (binaryReader.BaseStream.Position < binaryReader.BaseStream.Length)
  44. {
  45. ModItem item = ModItem.Deserialize(binaryReader);
  46. modItems[item.MenuFile] = item;
  47. }
  48. }
  49. }
  50. public void Serialize()
  51. {
  52. if (!rebuild) return;
  53. using (BinaryWriter binaryWriter = new BinaryWriter(File.OpenWrite(cachePath)))
  54. {
  55. binaryWriter.Write(cacheVersion);
  56. foreach (ModItem item in modItems.Values) item.Serialize(binaryWriter);
  57. }
  58. }
  59. }
  60. }