You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 line
1.9KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading;
  4. namespace NScript.Install
  5. {
  6. public class Installer
  7. {
  8. private List<IInstallable> _toInstall;
  9. private bool _isRunning = false;
  10. private bool _isCompleted = false;
  11. public bool Completed => _isCompleted;
  12. private string _currentItemName = null;
  13. public string CurrentlyInstalling => _currentItemName;
  14. private Thread _worker = null;
  15. public Installer()
  16. {
  17. _toInstall = new List<IInstallable>();
  18. }
  19. public Installer(IEnumerable<IInstallable> toInstall)
  20. {
  21. _toInstall = new List<IInstallable>(toInstall);
  22. }
  23. public void AddInstallable(IInstallable i)
  24. {
  25. if (_isRunning) throw new Exception("Cannot add IInstallable when already installing");
  26. _toInstall.Add(i);
  27. }
  28. public void InstallEverything()
  29. {
  30. if (_worker != null) _worker.Join();
  31. _worker = new Thread(InstallWorker);
  32. _worker.Start();
  33. }
  34. public void WaitForCompletion()
  35. {
  36. if (_worker != null) _worker.Join();
  37. _worker = null;
  38. }
  39. private void InstallWorker()
  40. {
  41. _isRunning = true;
  42. foreach (var i in _toInstall)
  43. {
  44. _currentItemName = i.Name;
  45. if (!i.IsInstalled())
  46. {
  47. try
  48. {
  49. i.Install();
  50. }
  51. catch (Exception e)
  52. {
  53. GamecraftModdingAPI.Utility.Logging.LogWarning(
  54. $"Failed to install {_currentItemName}: {e.Message}");
  55. }
  56. }
  57. }
  58. _isRunning = false;
  59. _isCompleted = true;
  60. _currentItemName = null;
  61. }
  62. }
  63. }