public static void Main(string[] args) { try { //Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Trace.Listeners.Add(new ConsoleTraceListener()); if (Environment.OSVersion.Platform != PlatformID.Unix) { var ver = GetNetVersionFromRegistry(); if (ver < 378675) { MessageBox.Show(new Form { TopMost = true }, "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); // extract fonts EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.SM.ttf", "SM.ttf"); EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.OpenSans-Regular.ttf", "OpenSans-Regular.ttf"); Conf = new Config(); IsSteamFolder = File.Exists(Path.Combine(StartupPath, "steamfolder.txt")); SelfUpdater = new SelfUpdater("Zero-K"); StartupArgs = args; try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); } catch (Exception ex) { Trace.TraceWarning("Failed to set rendering compatibility: {0}", ex); } if (!Debugger.IsAttached) { try { AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Thread.GetDomain().UnhandledException += UnhandledException; Application.ThreadException += Application_ThreadException; Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); } catch (Exception ex) { Trace.TraceWarning("Failed to set exception handling :{0}", ex); } } //HttpWebRequest.DefaultCachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore); Trace.TraceInformation("Starting with version {0}", SelfUpdater.CurrentVersion); WebRequest.DefaultWebProxy = null; ThreadPool.SetMaxThreads(500, 2000); ServicePointManager.Expect100Continue = false; LoadConfig(); Trace.Listeners.Add(new LogTraceListener()); if (Environment.OSVersion.Platform != PlatformID.Unix && !Conf.UseExternalBrowser) { Utils.SetIeCompatibility(); //set to current IE version } var contentDir = !string.IsNullOrEmpty(Conf.DataFolder) ? Conf.DataFolder : StartupPath; if (!Directory.Exists(contentDir) || !SpringPaths.IsDirectoryWritable(contentDir)) { 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)) { 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(new Form { TopMost = true }, "Move failed, please copy Zero-K.exe to a writable folder"); return; } SpringPaths = new SpringPaths(contentDir, true, true); if ( MessageBox.Show(new Form() { TopMost = true }, "WARNING: Zero-K lobby is now obsolete. Starting Chobby instead, ok? ", "WARNING: launcher obsolete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { var targetPath = Path.Combine(SpringPaths.WritableDirectory, "Chobby.exe"); if (!File.Exists(targetPath)) { var wc = new WebClient(); wc.DownloadFile(GlobalConst.BaseSiteUrl + "/lobby/Chobby.exe", targetPath); } Process.Start(targetPath); Environment.Exit(0); } // speed up spring start SpringPaths.SpringVersionChanged += (sender, engine) => { ZkData.Utils.StartAsync( () => { UnitSync unitSync = null; try { unitSync = new UnitSync(SpringPaths, engine); // initialize unitsync to avoid slowdowns when starting if (unitSync.UnitsyncWritableFolder != SpringPaths.WritableDirectory) { // unitsync created its cache in different folder than is used to start spring -> move it var fi = ArchiveCache.GetCacheFile(unitSync.UnitsyncWritableFolder); if (fi != null) { File.Copy(fi.FullName, Path.Combine(SpringPaths.WritableDirectory, "cache", fi.Name), true); } } } finally { unitSync?.Dispose(); } }); }; SaveConfig(); // write license files try { var path = SpringPaths.WritableDirectory; var pathGPL = Utils.MakePath(path, "license_GPLv3"); var gpl = Encoding.UTF8.GetString(License.GPLv3); if (!File.Exists(pathGPL)) { File.WriteAllText(pathGPL, gpl); } var pathMIT = Utils.MakePath(path, "license_MIT"); var mit = Encoding.UTF8.GetString(License.MITlicense); if (!File.Exists(pathMIT)) { File.WriteAllText(pathMIT, mit); } } catch (Exception ex) { Trace.TraceError(ex.ToString()); } if (Conf.IsFirstRun) { if (!IsSteamFolder) { Utils.CreateDesktopShortcut(); } if (Environment.OSVersion.Platform != PlatformID.Unix) { Utils.RegisterProtocol(); } } MetaData = new MetaDataCache(SpringPaths); AutoJoinManager = new AutoJoinManager(); EngineConfigurator = new EngineConfigurator(SpringPaths.WritableDirectory); SpringScanner = new PlasmaResourceChecker(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); Downloader = new PlasmaDownloader.PlasmaDownloader(SpringScanner, SpringPaths); //rapid Downloader.DownloadAdded += (s, e) => Trace.TraceInformation("Download started: {0}", e.Data.Name); //Downloader.GetResource(DownloadType.ENGINE, GlobalConst.DefaultEngineOverride); 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) { if (MainWindow != null) { MainWindow.navigationControl.Path = "battles"; } } }; TasClient.LoginDenied += (s, e) => Trace.TraceInformation("TASC login denied"); TasClient.ChannelJoined += (s, e) => { Trace.TraceInformation("TASC channel joined: " + e.Name); }; TasClient.ConnectionLost += (s, e) => Trace.TraceInformation("Connection lost"); TasClient.WelcomeReceived += (s, e) => { Downloader.GetResource(DownloadType.ENGINE, e.Engine); Downloader.GetResource(DownloadType.RAPID, e.Game); }; Program.AreYouReadyDialog = new AreYouReadyDialog(TasClient); // 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) || TasClient.Ignores.Contains(e.Data.UserName)) { e.Cancel = true; } } }; TasClient.SiteToLobbyCommandReceived += (eventArgs, o) => { if (MainWindow != null) { MainWindow.navigationControl.Path = o.Command; MainWindow.PopupSelf(); } }; ModStore = new ModStore(); ConnectBar = new ConnectBar(TasClient); ToolTip = new ToolTipHandler(); BrowserInterop = new BrowserInterop(TasClient, Conf); BattleIconManager = new BattleIconManager(); Application.AddMessageFilter(ToolTip); SteamHandler = new ZklSteamHandler(TasClient); MainWindow = new MainWindow(); Application.AddMessageFilter(new ScrollMessageFilter()); 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(); VoteBar = new VoteBar(); PwBar = new PwBar(); MatchMakerBar = new MatchMakerBar(TasClient); SelfUpdater.ProgramUpdated += s => { Program.MainWindow.InvokeFunc( () => WarningBar.DisplayWarning($"New version of Zero-K launcher downloaded, restart it to apply changes", "Restart", Restart)); }; if (!Debugger.IsAttached && !Conf.DisableAutoUpdate && !IsSteamFolder) { SelfUpdater.StartChecking(); } if (GlobalConst.Mode != ModeType.Local) { SteamHandler.Connect(); } Application.Run(MainWindow); ShutDown(); } catch (Exception ex) { ErrorHandling.HandleException(ex, true); if (Debugger.IsAttached) { Debugger.Break(); } } finally { ShutDown(); } if (ErrorHandling.HasFatalException && !CloseOnNext) { if (Debugger.IsAttached) { Debugger.Break(); } Application.Restart(); } }
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 static void Main(string[] args) { try { //Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); Trace.Listeners.Add(new ConsoleTraceListener()); try { Application.SetCompatibleTextRenderingDefault(false); } catch (Exception ex) { Trace.TraceWarning("Failed to set rendering compatibility: {0}",ex); } if (Environment.OSVersion.Platform != PlatformID.Unix) { var ver = GetNetVersionFromRegistry(); if (ver < 378675) { MessageBox.Show(new Form { TopMost = true }, "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); // extract fonts EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.SM.ttf", "SM.ttf"); EmbeddedResourceExtractor.ExtractFile("ZeroKLobby.NativeLibs.OpenSans-Regular.ttf", "OpenSans-Regular.ttf"); Conf = new Config(); IsSteamFolder = File.Exists(Path.Combine(StartupPath, "steamfolder.txt")); SelfUpdater = new SelfUpdater("Zero-K"); StartupArgs = args; Application.EnableVisualStyles(); 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; LoadConfig(); Trace.Listeners.Add(new LogTraceListener()); if (Environment.OSVersion.Platform != PlatformID.Unix && !Conf.UseExternalBrowser) Utils.SetIeCompatibility(); //set to current IE version var contentDir = !string.IsNullOrEmpty(Conf.DataFolder) ? Conf.DataFolder : StartupPath; if (!Directory.Exists(contentDir) || !SpringPaths.IsDirectoryWritable(contentDir)) { 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)) { 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(new Form { TopMost = true }, "Move failed, please copy Zero-K.exe to a writable folder"); return; } SpringPaths = new SpringPaths(null, contentDir); SpringPaths.MakeFolders(); // speed up spring start SpringPaths.SpringVersionChanged += (sender, eventArgs) => { ZkData.Utils.StartAsync( () => { UnitSync unitSync = null; try { unitSync = new UnitSync(SpringPaths); // initialize unitsync to avoid slowdowns when starting if (unitSync.UnitsyncWritableFolder != SpringPaths.WritableDirectory) { // unitsync created its cache in different folder than is used to start spring -> move it var fi = ArchiveCache.GetCacheFile(unitSync.UnitsyncWritableFolder); if (fi != null) File.Copy(fi.FullName, Path.Combine(SpringPaths.WritableDirectory, "cache", fi.Name), true); } } finally { unitSync?.Dispose(); } }); }; SaveConfig(); // write license files try { var path = SpringPaths.WritableDirectory; var pathGPL = Utils.MakePath(path, "license_GPLv3"); var gpl = Encoding.UTF8.GetString(License.GPLv3); if (!File.Exists(pathGPL)) File.WriteAllText(pathGPL, gpl); var pathMIT = Utils.MakePath(path, "license_MIT"); var mit = Encoding.UTF8.GetString(License.MITlicense); if (!File.Exists(pathMIT)) File.WriteAllText(pathMIT, mit); } catch (Exception ex) { Trace.TraceError(ex.ToString()); } if (Conf.IsFirstRun) { if (!IsSteamFolder) { 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 (Conf.EnableUnitSyncPrompt && Environment.OSVersion.Platform != PlatformID.Unix) { SpringScanner.UploadUnitsyncData += UnitSyncUploadPrompt.SpringScanner_UploadUnitsyncData; SpringScanner.RetryResourceCheck += 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(SpringScanner, SpringPaths); //rapid Downloader.DownloadAdded += (s, e) => Trace.TraceInformation("Download started: {0}", e.Data.Name); Downloader.GetAndSwitchEngine(GlobalConst.DefaultEngineOverride ?? TasClient.ServerSpringVersion); 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) if (MainWindow != null) MainWindow.navigationControl.Path = "battles"; }; TasClient.LoginDenied += (s, e) => Trace.TraceInformation("TASC login denied"); TasClient.ChannelJoined += (s, e) => { Trace.TraceInformation("TASC channel joined: " + e.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.SiteToLobbyCommandReceived += (eventArgs, o) => { if (MainWindow != null) { MainWindow.navigationControl.Path = o.Command; MainWindow.PopupSelf(); } }; ModStore = new ModStore(); ConnectBar = new ConnectBar(TasClient); ToolTip = new ToolTipHandler(); BrowserInterop = new BrowserInterop(TasClient, Conf); BattleIconManager = new BattleIconManager(); Application.AddMessageFilter(ToolTip); SteamHandler = new ZklSteamHandler(TasClient); MainWindow = new MainWindow(); Application.AddMessageFilter(new ScrollMessageFilter()); 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(); VoteBar = new VoteBar(); PwBar = new PwBar(); if (!Debugger.IsAttached && !Conf.DisableAutoUpdate && !IsSteamFolder) SelfUpdater.StartChecking(); SteamHandler.Connect(); Application.Run(MainWindow); ShutDown(); } catch (Exception ex) { ErrorHandling.HandleException(ex, true); if (Debugger.IsAttached) Debugger.Break(); } finally { ShutDown(); } if (ErrorHandling.HasFatalException && !CloseOnNext) { if (Debugger.IsAttached) Debugger.Break(); Application.Restart(); } }
public static void Main(string[] args) { try { GlobalConst.Mode =ModeType.Live; //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"); // 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; 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(); if (Conf.CleanCache) { try { var path = Program.SpringPaths.WritableDirectory; bool backupChatlogs = false; string sdPath = Utils.MakePath(path, "cache", "SD"); string chatHistoryPath = Utils.MakePath(sdPath, "ChatHistory"); string backupPath = Utils.MakePath(path, "_chatlogBackup"); // save chatlogs and such if (Directory.Exists(chatHistoryPath)) { if (Directory.Exists(backupPath)) Directory.Delete(backupPath, true); Directory.Move(chatHistoryPath, backupPath); backupChatlogs = true; } Directory.Delete(Utils.MakePath(path, "cache"), true); if (backupChatlogs) { if (!Directory.Exists(sdPath)) Directory.CreateDirectory(sdPath); Directory.Move(backupPath, chatHistoryPath); } } catch (Exception ex) { Trace.TraceError(ex.ToString()); } finally { Conf.CleanCache = false; 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 launcher is still running" + "\nMake sure the other launcher is closed (check task manager) before starting new one", "There can be only one launcher 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(); } } 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); }; TasClient.LoginDenied += (s, e) => Trace.TraceInformation("TASC login denied"); TasClient.ChannelJoined += (s, e) => { Trace.TraceInformation("TASC channel joined: " + e.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(); } }; ModStore = new ModStore(); ToolTip = new ToolTipHandler(); BrowserInterop = new BrowserInterop(); BattleIconManager = new BattleIconManager(); Application.AddMessageFilter(ToolTip); SteamHandler = new ZklSteamHandler(TasClient); SteamHandler.Connect(); MainWindow = new MainWindow(); Application.AddMessageFilter(new ScrollMessageFilter()); BattleBar = new BattleBar(); NewVersionBar = new NewVersionBar(SelfUpdater); VoteBar = new VoteBar(); PwBar = new PwBar(); if (!Debugger.IsAttached && !Conf.DisableAutoUpdate) Program.SelfUpdater.StartChecking(); Application.Run(MainWindow); ShutDown(); } catch (Exception ex) { ErrorHandling.HandleException(ex, true); } finally { ShutDown(); } if (ErrorHandling.HasFatalException && !Program.CloseOnNext) Application.Restart(); }
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) { 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"); } if (Conf.IsFirstRun) { Utils.CreateDesktopShortcut(); if (Environment.OSVersion.Platform != PlatformID.Unix) { Utils.RegisterProtocol(); } } 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) { } 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 void Draw(Graphics g, Font font, Color foreColor) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; var fbrush = new SolidBrush(foreColor); User user; if (!Program.TasClient.ExistingUsers.TryGetValue(userName, out user)) { return; } var x = (int)1; var y = 3; Action newLine = () => { x = (int)1; y += (int)16; }; Action <string> drawString = (text) => { //y -= 3; x += ToolTipHandler.TEXT_X_OFFSET; TextRenderer.DrawText(g, text, font, new Point(x, y + ToolTipHandler.TEXT_Y_OFFSET), Config.TextColor, TextFormatFlags.LeftAndRightPadding); x += TextRenderer.MeasureText(g, text, font).Width; //y += 3; }; Action <string, Color> drawString2 = (text, color) => { //y -= 3; x += ToolTipHandler.TEXT_X_OFFSET; TextRenderer.DrawText(g, text, font, new Point(x, y + ToolTipHandler.TEXT_Y_OFFSET), color, TextFormatFlags.LeftAndRightPadding); x += TextRenderer.MeasureText(g, text, font).Width; //y += 3; }; Action <Image, int, int> drawImage = (image, w, h) => { g.DrawImage(image, x, y, (int)w, (int)h); x += (int)(w + 3); }; using (var boldFont = new Font(font, FontStyle.Bold)) TextRenderer.DrawText(g, user.Name, boldFont, new Point(x, y), Config.TextColor, TextFormatFlags.LeftAndRightPadding); y += 3; newLine(); if (!user.IsBot) { var clan = ServerImagesHandler.GetClanOrFactionImage(user); if (clan.Item1 != null) { drawImage(clan.Item1, 16, 16); drawString2(clan.Item2, Utils.GetFactionColor(user.Faction)); newLine(); } } Image flag; if (Images.CountryFlags.TryGetValue(user.Country, out flag) && flag != null) { //drawString("Country: "); y += 2; drawImage(flag, flag.Width, flag.Height); y -= 2; drawString(CountryNames.GetName(user.Country)); newLine(); } if (user.IsBot) { drawImage(ZklResources.robot, 16, 16); drawString("Bot"); newLine(); } if (user.Name == Program.TasClient.MyBattle?.FounderName) { drawImage(ZklResources.self_police, 16, 16); drawString("Battle founder"); newLine(); } if (user.IsAdmin) { drawImage(ZklResources.police, 16, 16); drawString("Administrator"); newLine(); } if (Program.TasClient.Friends.Contains(user.Name)) { drawImage(ZklResources.friend, 16, 16); drawString("Friend"); newLine(); } if (user.SteamID != null) { drawImage(ZklResources.steam, 16, 16); drawString(string.Format("Steam name: {0}", user.DisplayName ?? user.Name)); newLine(); } if (!user.IsBot) { drawImage(Images.GetRank(user.Level, user.EffectiveMmElo), 16, 16); drawString(string.Format("Level: {0}", user.Level)); newLine(); if (user.AwaySince.HasValue) { drawImage(ZklResources.away, 16, 16); drawString("User idle for " + DateTime.UtcNow.Subtract(user.AwaySince.Value).PrintTimeRemaining() + "."); newLine(); } if (user.IsInGame) { drawImage(Buttons.fight, 16, 16); if (user.InGameSince != null) { var time = DateTime.UtcNow.Subtract(user.InGameSince.Value).PrintTimeRemaining(); drawString("Playing since " + time + " ago."); } newLine(); } if (!string.IsNullOrEmpty(user.Avatar)) { var image = Program.ServerImages.GetAvatarImage(user); if (image != null) { g.DrawImage(image, (int)(302 - 65), 0, (int)64, (int)64); } } } if (user.IsInBattleRoom) { if (y < 70) { y = 70; } if (user.IsInBattleRoom) { var battleIcon = Program.BattleIconManager.GetBattleIcon(user.BattleID ?? 0); if (battleIcon != null) { g.DrawImageUnscaled(battleIcon.Image, x, y); } } } fbrush.Dispose(); }
public void Draw(Graphics g, Font font, Color foreColor) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; User user; if (!Program.TasClient.ExistingUsers.TryGetValue(userName, out user)) { return; } DpiMeasurement.DpiXYMeasurement(); var x = DpiMeasurement.ScaleValueX(1); var y = 0; Action newLine = () => { x = DpiMeasurement.ScaleValueX(1); y += DpiMeasurement.ScaleValueY(16); }; Action <string> drawString = (text) => { TextRenderer.DrawText(g, text, font, new Point(x, y), foreColor); x += (int)Math.Ceiling((double)TextRenderer.MeasureText(g, text, font).Width); //Note: TextRenderer measurement already DPI aware }; Action <string, Color> drawString2 = (text, color) => { TextRenderer.DrawText(g, text, font, new Point(x, y), color); x += (int)Math.Ceiling((double)TextRenderer.MeasureText(g, text, font).Width); //Note: TextRenderer measurement already DPI aware }; Action <Image, int, int> drawImage = (image, w, h) => { g.DrawImage(image, x, y, DpiMeasurement.ScaleValueX(w), DpiMeasurement.ScaleValueY(h)); x += DpiMeasurement.ScaleValueX(w + 3); }; using (var boldFont = new Font(font, FontStyle.Bold)) TextRenderer.DrawText(g, user.Name, boldFont, new Point(x, y), foreColor); newLine(); if (!user.IsBot) { var clan = ServerImagesHandler.GetClanOrFactionImage(user); if (clan.Item1 != null) { drawImage(clan.Item1, 16, 16); drawString2(clan.Item2, Utils.GetFactionColor(user.Faction)); newLine(); } } Image flag; if (Images.CountryFlags.TryGetValue(user.Country, out flag) && flag != null) { drawString("Country: "); drawImage(flag, flag.Width, flag.Height); drawString(user.CountryName); newLine(); } if (user.IsBot) { drawImage(ZklResources.robot, 16, 16); drawString("Bot"); newLine(); } if (user.IsAdmin || user.IsZeroKAdmin) { drawImage(ZklResources.police, 16, 16); drawString("Administrator"); newLine(); } if (Program.FriendManager.Friends.Contains(user.Name)) { drawImage(ZklResources.friend, 16, 16); drawString("Friend"); newLine(); } if (user.IsZkLobbyUser) { drawImage(ZklResources.ZK_logo_square, 16, 16); drawString(string.Format("ZK lobby user ({0})", user.IsZkLinuxUser ? "Linux" : "Windows")); newLine(); } if (!user.IsBot) { drawImage(Images.GetRank(user.Level), 16, 16); drawString(string.Format("Level: {0}", user.Level)); newLine(); if (user.IsAway) { drawImage(ZklResources.away, 16, 16); drawString("User has been idle for " + DateTime.Now.Subtract(user.AwaySince.Value).PrintTimeRemaining() + "."); newLine(); } if (user.IsInGame) { drawImage(ZklResources.ingame, 16, 16); var time = DateTime.Now.Subtract(user.InGameSince.Value).PrintTimeRemaining(); drawString("Playing since " + time + " ago."); newLine(); } var top10 = Program.SpringieServer.GetTop10Rank(user.Name); if (top10 > 0) { drawImage(ZklResources.cup, 16, 16); drawString(string.Format("Top 10 Rank: {0}.", top10)); newLine(); } if (!string.IsNullOrEmpty(user.Avatar)) { var image = Program.ServerImages.GetAvatarImage(user); if (image != null) { g.DrawImage(image, DpiMeasurement.ScaleValueX(302 - 65), 0, DpiMeasurement.ScaleValueX(64), DpiMeasurement.ScaleValueY(64)); } } } if (user.IsInBattleRoom) { var battle = Program.TasClient.ExistingBattles.Values.SingleOrDefault(b => b.Users.Any(ub => ub.Name == user.Name)); var battleIcon = Program.BattleIconManager.GetBattleIcon(battle.BattleID); if (battleIcon != null) { g.DrawImageUnscaled(battleIcon.Image, x, y); } } }
public void Draw(Graphics g, Font font, Color foreColor) { Battle battle; User founder; if (!GetBattle(out battle)) { return; } var fbrush = new SolidBrush(foreColor); var x = 1; // margin var y = 3; g.InterpolationMode = InterpolationMode.HighQualityBicubic; Action newLine = () => { x = 1; y += 16; }; Action <string> drawString = text => { //y -= 3; x += ToolTipHandler.TEXT_X_OFFSET; TextRenderer.DrawText(g, text, font, new Point(x, y + ToolTipHandler.TEXT_Y_OFFSET), Config.TextColor, TextFormatFlags.LeftAndRightPadding); x += TextRenderer.MeasureText(g, text, font).Width; //y += 3; }; Action <Image, int, int> drawImage = (image, w, h) => { g.DrawImage(image, x, y, w, h); x += w + 3; }; drawString("Founder: " + battle.FounderName); newLine(); drawString("Map: " + battle.MapName); newLine(); drawString("Players: " + battle.NonSpectatorCount); drawString("Spectators: " + battle.SpectatorCount); drawString("Friends: " + battle.Users.Count(u => Program.TasClient.Friends.Contains(u.Key))); newLine(); if (battle.IsInGame) { drawImage(Buttons.fight, 16, 16); if (battle.RunningSince != null) { var timeString = DateTime.UtcNow.Subtract(battle.RunningSince.Value).PrintTimeRemaining(); drawString("Battle running for " + timeString + "."); } newLine(); } if (battle.IsPassworded) { drawImage(ZklResources._lock, 16, 16); drawString("Joining requires a password."); newLine(); } newLine(); foreach (var player in battle.Users.Values.Select(u => u.LobbyUser)) { var user = player; var icon = TextImage.GetUserImage(user.Name); drawImage(icon, 16, 16); Image flag; y += 3; if (Images.CountryFlags.TryGetValue(user.Country, out flag) && flag != null) { drawImage(flag, flag.Width, flag.Height); } else { x += 19; } y -= 3; if (!user.IsBot) { drawImage(Images.GetRank(user.Level, user.EffectiveMmElo), 16, 16); var clan = ServerImagesHandler.GetClanOrFactionImage(user); if (clan.Item1 != null) { drawImage(clan.Item1, 16, 16); } } /* * if (user.IsZkLobbyUser) * { * drawImage(Resources.ZK_logo_square, 16, 16); * }*/ drawString(player.Name); if (!user.IsBot) { if (user.IsAway) { drawImage(ZklResources.away, 16, 16); } if (user.IsInGame) { drawImage(Buttons.fight, 16, 16); } } newLine(); } if (Program.TasClient.MyBattle != null && battle.BattleID == Program.TasClient.MyBattle.BattleID && !String.IsNullOrEmpty(Program.ModStore.ChangedOptions)) { newLine(); drawString("Game Options:"); newLine(); foreach (var line in Program.ModStore.ChangedOptions.Lines().Where(z => !string.IsNullOrEmpty(z))) { drawString(" " + line); newLine(); } } fbrush.Dispose(); }
public void Draw(Graphics g, Font font, Color foreColor) { Battle battle; User founder; if (!GetBattleAndFounder(out battle, out founder)) { return; } var x = 1; // margin var y = 3; g.InterpolationMode = InterpolationMode.HighQualityBicubic; Action newLine = () => { x = 1; y += 16; }; Action <string> drawString = text => { TextRenderer.DrawText(g, text, font, new Point(x, y), foreColor); x += (int)Math.Ceiling((double)TextRenderer.MeasureText(g, text, font).Width); }; Action <Image, int, int> drawImage = (image, w, h) => { g.DrawImage(image, x, y, w, h); x += w + 3; }; founder = battle.Founder; drawString("Founder: " + battle.Founder); newLine(); drawString("Map: " + battle.MapName); newLine(); drawString("Players: " + battle.NonSpectatorCount); drawString("Spectators: " + battle.SpectatorCount); drawString("Friends: " + battle.Users.Values.Count(u => Program.FriendManager.Friends.Contains(u.Name))); newLine(); if (founder.IsInGame) { drawImage(ZklResources.boom, 16, 16); if (founder.InGameSince != null) { var timeString = DateTime.UtcNow.Subtract(founder.InGameSince.Value).PrintTimeRemaining(); drawString("The battle has been going on for at least " + timeString + "."); } newLine(); } if (battle.IsPassworded) { drawImage(ZklResources._lock, 16, 16); drawString("Joining requires a password."); newLine(); } newLine(); foreach (var player in battle.Users.Values) { var user = player.LobbyUser; var icon = TextImage.GetUserImage(user.Name); drawImage(icon, 16, 16); Image flag; y += 3; if (Images.CountryFlags.TryGetValue(user.Country, out flag) && flag != null) { drawImage(flag, flag.Width, flag.Height); } else { x += 19; } y -= 3; if (!user.IsBot) { drawImage(Images.GetRank(user.Level), 16, 16); var clan = ServerImagesHandler.GetClanOrFactionImage(user); if (clan.Item1 != null) { drawImage(clan.Item1, 16, 16); } } /* * if (user.IsZkLobbyUser) * { * drawImage(Resources.ZK_logo_square, 16, 16); * }*/ drawString(player.Name); var top10 = Program.SpringieServer.GetTop10Rank(user.Name); if (top10 > 0) { var oldx = x; drawImage(ZklResources.cup, 16, 16); x -= 17; drawString(top10.ToString()); x = oldx + 16; } if (!user.IsBot) { if (user.IsAway) { drawImage(ZklResources.away, 16, 16); } if (user.IsInGame) { drawImage(ZklResources.ingame, 16, 16); } } newLine(); } if (Program.TasClient.MyBattle != null && battle.BattleID == Program.TasClient.MyBattle.BattleID && !String.IsNullOrEmpty(Program.ModStore.ChangedOptions)) { newLine(); drawString("Game Options:"); newLine(); foreach (var line in Program.ModStore.ChangedOptions.Lines().Where(z => !string.IsNullOrEmpty(z))) { drawString(" " + line); newLine(); } } }