public MainForm(SpringPaths paths = null, SpringScanner scanner = null, PlasmaDownloader.PlasmaDownloader downloader = null) { InitializeComponent(); if (paths != null) springPaths = paths; else springPaths = new SpringPaths(null, writableFolderOverride: null); if (scanner != null) springScanner = scanner; else { springScanner = new SpringScanner(springPaths); springScanner.Start(); } if (downloader != null) springDownloader = downloader; else springDownloader = new PlasmaDownloader.PlasmaDownloader(new PlasmaConfig(), springScanner, springPaths); timer = new Timer(); timer.Tick += (sender, args) => { tbDownloads.Clear(); foreach (var d in springDownloader.Downloads.Where(x => x.IsComplete == null)) tbDownloads.AppendText(string.Format("{1:F0}% {0} ETA: {2} {3}\n", d.Name, d.TotalProgress, d.TimeRemaining, d.IsComplete)); }; timer.Interval = 1000; timer.Enabled = true; tbEngine.Text = springPaths.SpringVersion; }
public MainForm(SpringPaths paths, IResourcePresenceChecker scanner = null, PlasmaDownloader.PlasmaDownloader downloader = null) { InitializeComponent(); springPaths = paths; if (scanner != null) springScanner = scanner; else { var pl = new PlasmaResourceChecker(springPaths); springScanner = pl; pl.Start(); } if (downloader != null) springDownloader = downloader; else springDownloader = new PlasmaDownloader.PlasmaDownloader(springScanner, springPaths); timer = new Timer(); timer.Tick += (sender, args) => { tbDownloads.Clear(); foreach (var d in springDownloader.Downloads.Where(x => x.IsComplete == null)) tbDownloads.AppendText(string.Format("{1:F0}% {0} ETA: {2} {3}\n", d.Name, d.TotalProgress, d.TimeRemaining, d.IsComplete)); }; timer.Interval = 1000; timer.Enabled = true; tbEngine.Text = GlobalConst.DefaultEngineOverride; }
public static IEnumerable<Config> GetConfigs(SpringPaths paths, bool refresh = false) { if (refresh) allConfigs = null; if (allConfigs != null) return allConfigs; allConfigs = new List<Config>(); allConfigs = Batch.GetBenchmarkFolders(paths, "Configs").SelectMany(x => x.GetDirectories().Select(y => new Config(y.FullName))).ToList(); return allConfigs; }
public PlasmaDownloader(IResourcePresenceChecker checker, SpringPaths paths) { SpringPaths = paths; this.scanner = checker; //torrentDownloader = new TorrentDownloader(this); packageDownloader = new PackageDownloader(this); }
public void RunTests(SpringPaths paths) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; isAborted = false; var result = new BatchRunResult(); bool usingOptirun = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("OPTIRUN")); foreach (var tr in TestCases) { foreach (var b in Benchmarks) { if (isAborted) return; b.ModifyModInfo(tr); string log = null; try { run = new SpringRun(); log = run.Start(paths, tr, b); } catch (Exception ex) { Trace.TraceError(ex.ToString()); } finally { b.RestoreModInfo(); } try { if(usingOptirun) { // leave some time for optimus/primus to rest Thread.Sleep(5000); } result.AddRun(tr, b, log); RunCompleted(tr, b, log); } catch (Exception ex) { Trace.TraceError(ex.ToString()); } } } if (isAborted) return; AllCompleted(result); }
public Dictionary<string, EngineConfigEntry> GetEngineConfigOptions(SpringPaths paths, string engine) { Trace.TraceInformation("Extracting configuration from Spring located in {0}", paths.GetEngineFolderByVersion(engine)); var sb = new StringBuilder(); var p = new Process(); p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.Arguments += string.Format("--list-config-vars"); p.StartInfo.EnvironmentVariables["SPRING_DATADIR"] = paths.WritableDirectory; p.StartInfo.EnvironmentVariables.Remove("SPRING_ISOLATED"); p.StartInfo.FileName = paths.GetSpringExecutablePath(engine); p.StartInfo.WorkingDirectory = Path.GetDirectoryName(paths.GetSpringExecutablePath(engine)); p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data); p.Start(); p.BeginOutputReadLine(); p.WaitForExit(3000); sb.AppendLine(); //append terminator var text = sb.ToString(); int whereIsTable = text.IndexOf('{'); text = text.Substring(whereIsTable); // skip empty line or other info (if exist). Compatibility with Spring 94+ var data = JsonConvert.DeserializeObject<Dictionary<string, EngineConfigEntry>>(text); return data; }
/// <summary> /// The main entry point for the application. /// </summary> public void Main() { Paths = new SpringPaths(Path.Combine(sitePath, "autoregistrator"), false); Scanner = new SpringScanner(Paths) { UseUnitSync = true, WatchingEnabled = false}; Scanner.LocalResourceAdded += (s, e) => Trace.TraceInformation("Autoregistrator new resource found: {0}", e.Item.InternalName); Scanner.LocalResourceRemoved += (s, e) => Trace.TraceInformation("Autoregistrator Resource removed: {0}", e.Item.InternalName); SpringScanner.MapRegistered += (s, e) => Trace.TraceInformation("Autoregistrator Map registered: {0}", e.MapName); SpringScanner.ModRegistered += (s, e) => Trace.TraceInformation("Autoregistrator Mod registered: {0}", e.Data.Name); Downloader = new PlasmaDownloader.PlasmaDownloader(Scanner, Paths); Downloader.DownloadAdded += (s, e) => Trace.TraceInformation("Autoregistrator Download started: {0}", e.Data.Name); Downloader.GetResource(DownloadType.ENGINE, MiscVar.DefaultEngine)?.WaitHandle.WaitOne(); //for ZKL equivalent, see PlasmaShared/GlobalConst.cs Scanner.InitialScan(); Downloader.PackageDownloader.SetMasterRefreshTimer(20); Downloader.PackagesChanged += Downloader_PackagesChanged; Downloader.PackageDownloader.LoadMasterAndVersions()?.Wait(); Downloader.GetResource(DownloadType.MOD, "zk:stable")?.WaitHandle.WaitOne(); Downloader.GetResource(DownloadType.MOD, "zk:test")?.WaitHandle.WaitOne(); lastStableVersion = Downloader.PackageDownloader.GetByTag("zk:stable").InternalName; foreach (var ver in Downloader.PackageDownloader.Repositories.SelectMany(x => x.VersionsByTag).Where(x => x.Key.StartsWith("spring-features"))) { Downloader.GetResource(DownloadType.UNKNOWN, ver.Value.InternalName)?.WaitHandle.WaitOne(); } Scanner.Start(false); while (Scanner.GetWorkCost() > 0) Thread.Sleep(1000); }
/// <summary> /// Gets all benchamrks and caches them. Looks for folder Benchmarks and traverses paths up until found /// </summary> public static List<Benchmark> GetBenchmarks(SpringPaths paths, bool refresh = false) { if (refresh) allBenchmarks = null; if (allBenchmarks != null) return allBenchmarks; allBenchmarks = new List<Benchmark>(); allBenchmarks = Batch.GetBenchmarkFolders(paths, "games").SelectMany(x => x.GetDirectories("*.sdd").Select(y=> new Benchmark(y.FullName))).ToList(); return allBenchmarks; }
public static void ResetConfigs(SpringPaths paths, PackageDownloader.Version ver) { if (ver != null) { var oldVers = LoadFromDisk(paths); var newVers = LoadFromChobby(ver, paths); if (oldVers != null && newVers != null) { foreach (var kvp in newVers.Versions) { int oldVerNumber; if (oldVers.Versions.TryGetValue(kvp.Key, out oldVerNumber) && oldVerNumber < kvp.Value) { try { File.Delete(Path.Combine(paths.WritableDirectory, kvp.Key)); } catch (Exception ex) { Trace.TraceWarning("Error deleting config file {0} : {1}", kvp.Key, ex); } } } } (newVers ?? new ConfigVersions()).SaveToDisk(paths); } }
public Chobbyla(string rootPath, string chobbyTagOverride, string engineOverride) { paths = new SpringPaths(rootPath, false); chobbyTag = chobbyTagOverride ?? (GlobalConst.Mode == ModeType.Live ? "chobby:stable" : "chobby:test"); isDev = chobbyTag == "dev" || chobbyTag == "chobby:dev"; engine = engineOverride; }
public event EventHandler <CancelEventArgs <CacheItem> > RetryResourceCheck = delegate { }; // raised before attempting to reconnect to server to check for resource info public SpringScanner(SpringPaths springPaths) { this.springPaths = springPaths; MetaData = new MetaDataCache(springPaths, this); foreach (var folder in springPaths.DataDirectories) { var modsPath = Utils.MakePath(folder, "games"); if (Directory.Exists(modsPath)) { modsWatchers.Add(new FileSystemWatcher(modsPath)); } var mapsPath = Utils.MakePath(folder, "maps"); if (Directory.Exists(mapsPath)) { mapsWatchers.Add(new FileSystemWatcher(mapsPath)); } var packagesPath = Utils.MakePath(folder, "packages"); if (Directory.Exists(packagesPath)) { packagesWatchers.Add(new FileSystemWatcher(packagesPath)); } } SetupWatcherEvents(mapsWatchers); SetupWatcherEvents(modsWatchers); SetupWatcherEvents(packagesWatchers); Directory.CreateDirectory(springPaths.Cache); cachePath = Utils.MakePath(springPaths.Cache, "ScannerCache.json"); Directory.CreateDirectory(Utils.MakePath(springPaths.Cache, "Resources")); }
public PlasmaDownloader(IPlasmaDownloaderConfig config, SpringScanner scanner, SpringPaths springPaths) { SpringPaths = springPaths; Config = config; this.scanner = scanner; //torrentDownloader = new TorrentDownloader(this); packageDownloader = new PackageDownloader(this); }
public Chobbyla(string rootPath, string chobbyTagOverride, string engineOverride) { paths = new SpringPaths(rootPath, false); chobbyTag = chobbyTagOverride ?? (GlobalConst.Mode == ModeType.Live ? "zkmenu:stable" : "zkmenu:test"); isDev = chobbyTag == "dev" || chobbyTag == "chobby:dev" || chobbyTag =="zkmenu:dev"; engine = engineOverride; downloader = new PlasmaDownloader.PlasmaDownloader(null, paths); }
public static IEnumerable<StartScript> GetStartScripts(SpringPaths paths, bool refresh = false) { if (refresh) allStartScripts = null; if (allStartScripts != null) return allStartScripts; allStartScripts = new List<StartScript>(); allStartScripts = Batch.GetBenchmarkFolders(paths, "Scripts").SelectMany(x => x.GetFiles("*.txt").Select(y => new StartScript(y.FullName))).ToList(); return allStartScripts; }
public static ConfigVersions LoadFromDisk(SpringPaths paths) { var filePath = Path.Combine(paths.WritableDirectory, FilePathOnDisk); if (File.Exists(filePath)) { TryDeserialize(File.ReadAllText(filePath)); } return null; }
public UnitsyncResourcePresenceChecker(SpringPaths paths, string engine) { if (string.IsNullOrEmpty(engine) || !paths.HasEngineVersion(engine)) { Trace.TraceWarning("Engine {0} not found, trying backup", engine); engine = paths.GetEngineList().FirstOrDefault(); if (engine == null) throw new Exception("No engine found for unitsync"); } unitsync = new UnitSync(paths, engine); }
public PackageDownload(string urlRoot, string displayName, Hash hash, SpringPaths paths) { this.paths = paths; this.urlRoot = urlRoot; pool = new Pool(paths); PackageHash = hash; Name = displayName; fileListWebGet = new WebDownload(); }
public UnitSyncer(SpringPaths npaths, string nengine) { Paths = npaths; Engine = nengine; if (string.IsNullOrEmpty(Engine) || !Paths.HasEngineVersion(Engine)) { Trace.TraceWarning("UnitSyncer: Engine {0} not found, trying backup", Engine); Engine = Paths.GetEngineList().FirstOrDefault(); if (Engine == null) throw new Exception("UnitSyncer: No engine found for unitsync"); } }
public ServerImagesHandler(SpringPaths springPaths, TasClient tas) { basePath = Utils.MakePath(springPaths.WritableDirectory, "LuaUI", "Configs"); tas.BattleUserJoined += (sender, args) => { // preload avatar images on user join battle so that they are available ingame User us; if (tas.ExistingUsers.TryGetValue(args.UserName, out us)) { GetAvatarImage(us); GetClanOrFactionImage(us); } }; }
public UnitsyncResourcePresenceChecker(SpringPaths paths, string engine) { if (string.IsNullOrEmpty(engine) || !paths.HasEngineVersion(engine)) { Trace.TraceWarning("Engine {0} not found, trying backup", engine); engine = paths.GetEngineList().FirstOrDefault(); if (engine == null) { throw new Exception("No engine found for unitsync"); } } unitsync = new UnitSync(paths, engine); }
/// <summary> /// Returns folders of interest - for example if you set "games" it will look in all datadirs and current dir for "Games" and "Benchmarks/Games" /// </summary> public static List<DirectoryInfo> GetBenchmarkFolders(SpringPaths paths, string folderName) { var dirsToCheck = new List<string>(paths.DataDirectories); dirsToCheck.Add(Directory.GetCurrentDirectory()); var ret = new List<DirectoryInfo>(); foreach (var dir in dirsToCheck) { var sub = Path.Combine(dir, folderName); if (Directory.Exists(sub)) ret.Add(new DirectoryInfo(sub)); var bsub = Path.Combine(dir, "Benchmarks", folderName); if (Directory.Exists(bsub)) ret.Add(new DirectoryInfo(bsub)); } return ret; }
public void UpdateMission(ZkDataContext db, Mission mission, SpringPaths paths, string engine) { var file = mission.Mutator.ToArray(); var targetPath = Path.Combine(paths.WritableDirectory, "games", mission.SanitizedFileName); File.WriteAllBytes(targetPath, file); Mod modInfo; using (var unitsync = new UnitSync(paths, engine)) { modInfo = unitsync.GetResourceFromFileName(targetPath) as Mod; } File.Delete(targetPath); UpdateMission(db, mission, modInfo); }
public Pool(SpringPaths paths) { foreach (var p in paths.DataDirectories) { var readPath = Utils.MakePath(p, "pool"); Utils.CheckPath(readPath); readPaths.Add(readPath); } writePath = Utils.MakePath(paths.WritableDirectory, "pool"); Utils.CheckPath(writePath); tempPath = Utils.MakePath(paths.WritableDirectory, "temp"); Utils.CheckPath(tempPath); }
public UnitSync(SpringPaths springPaths) { paths = springPaths; //originalDirectory = Directory.GetCurrentDirectory(); //Getting the directory of this application instead of the non-constant currentDirectory. Reference: http://stackoverflow.com/questions/52797/how-do-i-get-the-path-of-the-assembly-the-code-is-in originalDirectory = AppDomain.CurrentDomain.BaseDirectory; System.Diagnostics.Trace.TraceInformation("UnitSync: Directory: {0}", paths.UnitSyncDirectory); System.Diagnostics.Trace.TraceInformation("UnitSync: ZKL: {0}", originalDirectory); Directory.SetCurrentDirectory(paths.UnitSyncDirectory); //originalEnvironmentVariable = Environment.GetEnvironmentVariable("SPRING_DATADIR", EnvironmentVariableTarget.Process); //Environment.SetEnvironmentVariable("SPRING_DATADIR", paths.WritableDirectory, EnvironmentVariableTarget.Process);//no longer needed since SpringPath already set SPRING_DATADIR if (!NativeMethods.Init(false, 666)) throw new UnitSyncException("Unitsync initialization failed."); Version = NativeMethods.GetSpringVersion(); var writ = NativeMethods.GetWritableDataDirectory(); System.Diagnostics.Trace.TraceInformation("UnitSync Version: {0}", Version); //System.Diagnostics.Trace.TraceInformation("UnitSync new SPRING_DATADIR: {0}", paths.WritableDirectory); //System.Diagnostics.Trace.TraceInformation("UnitSync original SPRING_DATADIR: {0}", originalEnvironmentVariable); TraceErrors(); System.Diagnostics.Trace.TraceInformation("UnitSync Initialized"); }
public Main(string path) { RootWorkPath = path; LoadConfig(); Config.RestartCounter++; if (Config.RestartCounter > 3) Config.RestartCounter = 0; SaveConfig(); paths = new SpringPaths(Path.GetDirectoryName(Config.ExecutableName), writableFolderOverride: Config.DataDir); if (!string.IsNullOrEmpty(Config.ExecutableName)) paths.OverrideDedicatedServer(Config.ExecutableName); paths.MakeFolders(); MetaCache = new MetaDataCache(paths); timer = new Timer(30000); timer.Elapsed += timer_Elapsed; timer.AutoReset = true; timer.Start(); Downloader = new PlasmaDownloader.PlasmaDownloader(Config, null, paths); }
/// <summary> /// The main entry point for the application. /// </summary> public void Main() { Paths = new SpringPaths(Path.Combine(sitePath, "autoregistrator"), false); Downloader = new PlasmaDownloader.PlasmaDownloader(null, Paths); Downloader.DownloadAdded += (s, e) => Trace.TraceInformation("Autoregistrator Download started: {0}", e.Data.Name); Downloader.GetResource(DownloadType.ENGINE, MiscVar.DefaultEngine)?.WaitHandle.WaitOne(); //for ZKL equivalent, see PlasmaShared/GlobalConst.cs UnitSyncer = new UnitSyncer(Paths, MiscVar.DefaultEngine); Downloader.PackageDownloader.DoMasterRefresh(); Downloader.GetResource(DownloadType.RAPID, "zk:stable")?.WaitHandle.WaitOne(); Downloader.GetResource(DownloadType.RAPID, "zk:test")?.WaitHandle.WaitOne(); foreach ( var ver in Downloader.PackageDownloader.Repositories.SelectMany(x => x.VersionsByTag).Where(x => x.Key.StartsWith("spring-features"))) Downloader.GetResource(DownloadType.RAPID, ver.Value.InternalName)?.WaitHandle.WaitOne(); OnRapidChanged(); }
/// <summary> /// Download requested Spring version, then call SetEnginePath() after finishes. /// Parameter "forSpringPaths" allow you to set a custom SpringPath for which to call SetEnginePath() /// on behalf off (is useful for Autohost which run multiple Spring version but is sharing single downloader) /// </summary> public Download GetAndSwitchEngine(string version, SpringPaths forSpringPaths=null ) { if (forSpringPaths == null) forSpringPaths = SpringPaths; lock (downloads) { downloads.RemoveAll(x => x.IsAborted || x.IsComplete != null); // remove already completed downloads from list} var existing = downloads.SingleOrDefault(x => x.Name == version); if (existing != null) return existing; if (SpringPaths.HasEngineVersion(version)) { forSpringPaths.SetEnginePath(SpringPaths.GetEngineFolderByVersion(version)); return null; } else { var down = new EngineDownload(version, forSpringPaths); downloads.Add(down); DownloadAdded.RaiseAsyncEvent(this, new EventArgs<Download>(down)); down.Start(); return down; } } }
public void Generate() { Utils.CheckPath(targetFolder); var paths = new SpringPaths(targetFolder, false); try { //Directory.Delete(Path.Combine(paths.WritableDirectory, "pool"), true); Directory.Delete(Path.Combine(paths.WritableDirectory, "packages"), true); Directory.CreateDirectory(Path.Combine(paths.WritableDirectory, "packages")); } catch { } var downloader = new PlasmaDownloader.PlasmaDownloader(null, paths); downloader.GetResource(DownloadType.ENGINE, MiscVar.DefaultEngine)?.WaitHandle.WaitOne(); //for ZKL equivalent, see PlasmaShared/GlobalConst.cs downloader.GetResource(DownloadType.RAPID, "zk:stable")?.WaitHandle.WaitOne(); downloader.GetResource(DownloadType.RAPID, "zk:test")?.WaitHandle.WaitOne(); CopyResources(siteBase, paths, GetResourceList(downloader.PackageDownloader.GetByTag("zk:stable").InternalName, downloader.PackageDownloader.GetByTag("zk:test").InternalName), downloader); CopyLobbyProgram(); CopyExtraImages(); }
static void Main() { Trace.Listeners.Add(new ConsoleTraceListener()); Paths = new SpringPaths(null); Scanner = new SpringScanner(Paths); Scanner.LocalResourceAdded += (s, e) => Trace.TraceInformation("New resource found: {0}", e.Item.InternalName); Scanner.LocalResourceRemoved += (s, e) => Trace.TraceInformation("Resource removed: {0}", e.Item.InternalName); SpringScanner.MapRegistered += (s, e) => Trace.TraceInformation("Map registered: {0}", e.MapName); SpringScanner.ModRegistered += (s, e) => Trace.TraceInformation("Mod registered: {0}", e.Data.Name); Scanner.Start(); Downloader = new PlasmaDownloader.PlasmaDownloader(new Config(), Scanner, Paths); Downloader.DownloadAdded += (s, e) => Trace.TraceInformation("Download started: {0}", e.Data.Name); Downloader.GetAndSwitchEngine(GlobalConst.DefaultEngineOverride); //for ZKL equivalent, see PlasmaShared/GlobalConst.cs Downloader.PackagesChanged += Downloader_PackagesChanged; while (true) {Thread.Sleep(10000);} /*Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1());*/ }
public void Generate() { Utils.CheckPath(targetFolder); var paths = new SpringPaths(null, targetFolder, false); try { //Directory.Delete(Path.Combine(paths.WritableDirectory, "pool"), true); Directory.Delete(Path.Combine(paths.WritableDirectory, "packages"), true); } catch { } paths.MakeFolders(); var downloader = new PlasmaDownloader.PlasmaDownloader(null, paths); downloader.GetAndSwitchEngine(GlobalConst.DefaultEngineOverride)?.WaitHandle.WaitOne(); //for ZKL equivalent, see PlasmaShared/GlobalConst.cs downloader.PackageDownloader.LoadMasterAndVersions(false).Wait(); downloader.GetResource(DownloadType.MOD, "zk:stable")?.WaitHandle.WaitOne(); downloader.GetResource(DownloadType.MOD, "zk:test")?.WaitHandle.WaitOne(); CopyResources(siteBase, paths, GetResourceList(downloader.PackageDownloader.GetByTag("zk:stable").InternalName, downloader.PackageDownloader.GetByTag("zk:test").InternalName), downloader); CopyLobbyProgram(); CopyExtraImages(); ScanArchives(paths); }
public MetaDataCache(SpringPaths springPaths) { resourceFolder = Utils.MakePath(springPaths.Cache, "Resources"); Utils.CheckPath(resourceFolder); }
public static void Main(string[] args) { try { //Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Trace.Listeners.Add(new ConsoleTraceListener()); Trace.Listeners.Add(new LogTraceListener()); /* if (Environment.OSVersion.Platform != PlatformID.Unix) { var ver = GetNetVersionFromRegistry(); if (ver < 378675) { MessageBox.Show("Zero-K launcher needs Microsoft .NET framework 4.5.1\nPlease download and install it first", "Program is unable to run", MessageBoxButtons.OK, MessageBoxIcon.Error); } } */ Directory.SetCurrentDirectory(StartupPath); SelfUpdater = new SelfUpdater("Zero-K_NET4.0"); // if (Process.GetProcesses().Any(x => x.ProcessName.StartsWith("spring_"))) return; // dont start if started from installer StartupArgs = args; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); if (!Debugger.IsAttached) { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Thread.GetDomain().UnhandledException += UnhandledException; Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); } //HttpWebRequest.DefaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); Trace.TraceInformation("Starting with version {0}", SelfUpdater.CurrentVersion); WebRequest.DefaultWebProxy = null; ThreadPool.SetMaxThreads(500, 2000); ServicePointManager.Expect100Continue = false; if (Environment.OSVersion.Platform != PlatformID.Unix && !Conf.UseExternalBrowser) { Utils.SetIeCompatibility(); } //set to current IE version LoadConfig(); var contentDir = !string.IsNullOrEmpty(Conf.DataFolder) ? Conf.DataFolder : StartupPath; if (!Directory.Exists(contentDir) || !SpringPaths.IsDirectoryWritable(contentDir) || pickInitFolder || contentDir.Contains("Local\\Apps")) { var dc = new SelectWritableFolder() { SelectedPath = SpringPaths.GetMySpringDocPath() }; if (dc.ShowDialog() != DialogResult.OK) return; contentDir = dc.SelectedPath; } if (Conf.DataFolder != StartupPath) Conf.DataFolder = contentDir; else Conf.DataFolder = null; if (!SpringPaths.IsDirectoryWritable(StartupPath) || StartupPath.Contains("Local\\Apps")) { MessageBox.Show( string.Format( "Please use the newly created desktop icon to start Zero-K not this one.\r\nZero-K.exe will be moved to {0}", contentDir), "Startup directory is not writable!"); var newTarget = Path.Combine(contentDir, "Zero-K.exe"); if (SelfUpdater.CheckForUpdate(newTarget, true)) { Conf.Save(Path.Combine(contentDir, Config.ConfigFileName)); Process.Start(newTarget); return; } MessageBox.Show("Move failed, please copy Zero-K.exe to a writable folder"); } SpringPaths = new SpringPaths(null, writableFolderOverride: contentDir); SpringPaths.MakeFolders(); SpringPaths.SetEnginePath(Utils.MakePath(SpringPaths.WritableDirectory, "engine", ZkData.GlobalConst.DefaultEngineOverride ?? TasClient.ServerSpringVersion)); // run unitsync as soon as possible so we don't have to spend several minutes doing it on game start // two problems: // 1) unitsync can only be loaded once, even if in a different directory http://msdn.microsoft.com/en-us/library/ms682586.aspx#factors_that_affect_searching // so if we do it in SpringVersionChanged it'll be done at startup for GlobalConst.DefaultEngineOverride, then for no other engine version // 2) unitsync can't be unloaded http://stackoverflow.com/questions/1371877/how-to-unload-the-dll-using-c // also see EngineDownload.cs //SpringPaths.SpringVersionChanged += (s, e) => //{ // //System.Diagnostics.Trace.TraceInformation("SpringPaths version: {0}", SpringPaths.SpringVersion); // //new PlasmaShared.UnitSyncLib.UnitSync(SpringPaths); // //SpringScanner.VerifyUnitSync(); // //if (SpringScanner != null) SpringScanner.Dispose(); // //SpringScanner = new SpringScanner(SpringPaths); // //SpringScanner.Start(); //}; SaveConfig(); try { if (!Debugger.IsAttached) { var wp = ""; foreach (var c in SpringPaths.WritableDirectory.Where(x => (x >= 'a' && x <= 'z') || (x >= 'A' && x <= 'Z'))) wp += c; mutex = new Mutex(false, "ZeroKLobby" + wp); if (!mutex.WaitOne(10000, false)) { MessageBox.Show( "Another copy of Zero-K lobby is still running" + "\nMake sure the other lobby is closed (check task manager) before starting new one", "There can be only one lobby running", MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } } } catch (AbandonedMutexException) { } if (Conf.IsFirstRun) { DialogResult result = MessageBox.Show("Create a desktop icon for Zero-K?", "Zero-K", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { Utils.CreateDesktopShortcut(); } if (Environment.OSVersion.Platform != PlatformID.Unix) Utils.RegisterProtocol(); } FriendManager = new FriendManager(); AutoJoinManager = new AutoJoinManager(); EngineConfigurator = new EngineConfigurator(SpringPaths.WritableDirectory); SpringScanner = new SpringScanner(SpringPaths); SpringScanner.LocalResourceAdded += (s, e) => Trace.TraceInformation("New resource found: {0}", e.Item.InternalName); SpringScanner.LocalResourceRemoved += (s, e) => Trace.TraceInformation("Resource removed: {0}", e.Item.InternalName); if (Program.Conf.EnableUnitSyncPrompt && Environment.OSVersion.Platform != PlatformID.Unix) { SpringScanner.UploadUnitsyncData += MicroForms.UnitSyncUploadPrompt.SpringScanner_UploadUnitsyncData; SpringScanner.RetryResourceCheck += MicroForms.UnitSyncRetryPrompt.SpringScanner_RetryGetResourceInfo; } SpringScanner.MapRegistered += (s, e) => Trace.TraceInformation("Map registered: {0}", e.MapName); SpringScanner.ModRegistered += (s, e) => Trace.TraceInformation("Mod registered: {0}", e.Data.Name); Downloader = new PlasmaDownloader.PlasmaDownloader(Conf, SpringScanner, SpringPaths); //rapid Downloader.DownloadAdded += (s, e) => Trace.TraceInformation("Download started: {0}", e.Data.Name); var isLinux = Environment.OSVersion.Platform == PlatformID.Unix; TasClient = new TasClient(string.Format("ZK {0}{1}", SelfUpdater.CurrentVersion, isLinux ? " linux" : "")); SayCommandHandler = new SayCommandHandler(TasClient); ServerImages = new ServerImagesHandler(SpringPaths, TasClient); // log, for debugging TasClient.Connected += (s, e) => Trace.TraceInformation("TASC connected"); TasClient.LoginAccepted += (s, e) => { Trace.TraceInformation("TASC login accepted"); Trace.TraceInformation("Server is using Spring version {0}", TasClient.ServerSpringVersion); if (Environment.OSVersion.Platform == PlatformID.Unix || Conf.UseExternalBrowser) MainWindow.navigationControl.Path = "battles"; }; TasClient.LoginDenied += (s, e) => Trace.TraceInformation("TASC login denied"); TasClient.ChannelJoined += (s, e) => { Trace.TraceInformation("TASC channel joined: " + e.Data.Name); }; TasClient.ConnectionLost += (s, e) => Trace.TraceInformation("Connection lost"); // special handling TasClient.PreviewSaid += (s, e) => { var tas = (TasClient)s; User user = null; if (e.Data.UserName != null) { tas.ExistingUsers.TryGetValue(e.Data.UserName, out user); if ((user != null && user.BanMute) || Conf.IgnoredUsers.Contains(e.Data.UserName)) e.Cancel = true; } }; TasClient.Extensions.JsonDataReceived += (eventArgs, o) => { var command = o as ProtocolExtension.SiteToLobbyCommand; if (command != null) { MainWindow.navigationControl.Path = command.SpringLink; MainWindow.PopupSelf(); } }; ConnectBar = new ConnectBar(TasClient); ModStore = new ModStore(); ToolTip = new ToolTipHandler(); BrowserInterop = new BrowserInterop(TasClient, Conf); BattleIconManager = new BattleIconManager(); Application.AddMessageFilter(ToolTip); SteamHandler = new ZklSteamHandler(TasClient); SteamHandler.Connect(); MainWindow = new MainWindow(); Application.AddMessageFilter(new ScrollMessageFilter()); if (Conf.StartMinimized) MainWindow.WindowState = FormWindowState.Minimized; else MainWindow.WindowState = FormWindowState.Normal; MainWindow.Size = new Size(Math.Min(SystemInformation.VirtualScreen.Width - 30, MainWindow.Width), Math.Min(SystemInformation.VirtualScreen.Height - 30, MainWindow.Height)); //in case user have less space than 1024x768 BattleBar = new BattleBar(); NewVersionBar = new NewVersionBar(SelfUpdater); VoteBar = new VoteBar(); PwBar = new PwBar(); //This make the size of every bar constant (only for height). //We wanted to make them constant because the bar get DPI-scaled twice/thrice/multiple-time (especially for reusable bar). //Setting maximum height upon creation will hopefully make sure it is not DPI-scaled multiple time. var votebarSize = new Size(0, VoteBar.Height); // Reference: http://stackoverflow.com/questions/5314041/set-minimum-window-size-in-c-sharp-net var newversionbarSize = new Size(0, NewVersionBar.Height); var battlebarSize = new Size(0, BattleBar.Height); var connectbarSize = new Size(0, ConnectBar.Height); VoteBar.MinimumSize = votebarSize; //fix minimum size forever VoteBar.MaximumSize = votebarSize; //fix maximum size forever NewVersionBar.MinimumSize = newversionbarSize; NewVersionBar.MaximumSize = newversionbarSize; BattleBar.MinimumSize = battlebarSize; BattleBar.MaximumSize = battlebarSize; ConnectBar.MinimumSize = connectbarSize; ConnectBar.MaximumSize = connectbarSize; //End battlebar size hax if (!Debugger.IsAttached && !Conf.DisableAutoUpdate) Program.SelfUpdater.StartChecking(); //if (Conf.IsFirstRun) Utils.OpenWeb(GlobalConst.BaseSiteUrl + "/Wiki/LobbyStart", false); // download primary engine & game MainWindow.Paint += GetSpringZK; Downloader.PackageDownloader.MasterManifestDownloaded += GetSpringZK; // Format and display the TimeSpan value. //stopWatch.Stop(); TimeSpan ts = stopWatch.Elapsed; string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10); //Trace.TraceInformation("1 Runtime {0}", elapsedTime); Application.Run(MainWindow); ShutDown(); } catch (Exception ex) { ErrorHandling.HandleException(ex, true); } finally { ShutDown(); } if (ErrorHandling.HasFatalException && !Program.CloseOnNext) Application.Restart(); }
public Spring(SpringPaths springPaths) { paths = springPaths; timer.Elapsed += timer_Elapsed; }
public MetaDataCache(SpringPaths springPaths, SpringScanner scanner) { this.scanner = scanner; resourceFolder = Utils.MakePath(springPaths.Cache, "Resources"); Utils.CheckPath(resourceFolder); }