Formatting fixes.

This commit is contained in:
Nick Blakely 2020-08-12 21:58:53 -07:00
parent c6c9b6f4f9
commit 582fe3e693
10 changed files with 359 additions and 365 deletions

View File

@ -1,11 +1,5 @@
namespace Giants.Launcher
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class ApplicationNames
{
public const string Giants = nameof(Giants);

View File

@ -4,18 +4,18 @@ using Microsoft.Win32;
namespace Giants.Launcher
{
public static class RegistryExtensions
{
// Extension to Registry.GetValue() that returns the default value if the returned object does not
// match the type specified.
public static object GetValue(string keyName, string valueName, object defaultValue, Type type)
{
object retVal = Registry.GetValue(keyName, valueName, defaultValue);
{
// Extension to Registry.GetValue() that returns the default value if the returned object does not
// match the type specified.
public static object GetValue(string keyName, string valueName, object defaultValue, Type type)
{
object retVal = Registry.GetValue(keyName, valueName, defaultValue);
if (retVal.GetType() != type)
return defaultValue;
else
return retVal;
}
}
if (retVal.GetType() != type)
return defaultValue;
else
return retVal;
}
}
}

View File

@ -8,114 +8,115 @@ using Microsoft.Win32;
namespace Giants.Launcher
{
static class GameSettings
{
// Constants
private const string REGISTRY_KEY = @"HKEY_CURRENT_USER\Software\PlanetMoon\Giants";
private const int OPTIONS_VERSION = 3;
{
// Constants
private const string REGISTRY_KEY = @"HKEY_CURRENT_USER\Software\PlanetMoon\Giants";
private const int OPTIONS_VERSION = 3;
private static readonly Dictionary<string, object> Settings = new Dictionary<string, object>();
private static readonly Dictionary<string, object> Settings = new Dictionary<string, object>();
// List of renderers compatible with the user's system.
static public List<RendererInterop.Capabilities> CompatibleRenderers;
// List of renderers compatible with the user's system.
static public List<RendererInterop.Capabilities> CompatibleRenderers;
public static object Get(string settingName)
{
if (Settings.ContainsKey(settingName))
return Settings[settingName];
else
return 0;
public static object Get(string settingName)
{
if (Settings.ContainsKey(settingName))
return Settings[settingName];
else
return 0;
}
}
public static void Modify(string settingName, object settingValue)
{
Settings[settingName] = settingValue;
}
public static void Modify(string settingName, object settingValue)
{
Settings[settingName] = settingValue;
}
public static void SetDefaults(string gamePath)
{
// Set default settings:
Settings["Renderer"] = "gg_dx7r.dll";
Settings["Antialiasing"] = 0;
Settings["AnisotropicFiltering"] = 0;
Settings["VideoWidth"] = 640;
Settings["VideoHeight"] = 480;
Settings["VideoDepth"] = 32;
Settings["Windowed"] = 0;
Settings["BorderlessWindow"] = 0;
Settings["VerticalSync"] = 1;
Settings["TripleBuffering"] = 1;
Settings["NoAutoUpdate"] = 0;
public static void SetDefaults(string gamePath)
{
// Set default settings:
Settings["Renderer"] = "gg_dx7r.dll";
Settings["Antialiasing"] = 0;
Settings["AnisotropicFiltering"] = 0;
Settings["VideoWidth"] = 640;
Settings["VideoHeight"] = 480;
Settings["VideoDepth"] = 32;
Settings["Windowed"] = 0;
Settings["BorderlessWindow"] = 0;
Settings["VerticalSync"] = 1;
Settings["TripleBuffering"] = 1;
Settings["NoAutoUpdate"] = 0;
// Get a list of renderers compatible with the user's system
if (CompatibleRenderers == null)
{
CompatibleRenderers = RendererInterop.GetCompatibleRenderers(gamePath);
if (CompatibleRenderers.Count == 0)
{
MessageBox.Show("Could not locate any renderers compatible with your system. The most compatible renderer has been selected, but you may experience difficulty running the game.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Get a list of renderers compatible with the user's system
if (CompatibleRenderers == null)
{
CompatibleRenderers = RendererInterop.GetCompatibleRenderers(gamePath);
if (CompatibleRenderers.Count == 0)
{
MessageBox.Show(
"Could not locate any renderers compatible with your system. " +
"The most compatible renderer has been selected, but you may experience difficulty running the game.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Select the highest priority renderer
if (CompatibleRenderers.Count > 0)
Settings["Renderer"] = Path.GetFileName(CompatibleRenderers.Max().FilePath);
// Select the highest priority renderer
if (CompatibleRenderers.Count > 0)
Settings["Renderer"] = Path.GetFileName(CompatibleRenderers.Max().FilePath);
// Set the current desktop resolution, leaving bit depth at the default 32:
Settings["VideoWidth"] = Screen.PrimaryScreen.Bounds.Width;
Settings["VideoHeight"] = Screen.PrimaryScreen.Bounds.Height;
}
// Set the current desktop resolution, leaving bit depth at the default 32:
Settings["VideoWidth"] = Screen.PrimaryScreen.Bounds.Width;
Settings["VideoHeight"] = Screen.PrimaryScreen.Bounds.Height;
}
public static void Load(string gamePath)
{
SetDefaults(gamePath);
public static void Load(string gamePath)
{
SetDefaults(gamePath);
if ((int)Registry.GetValue(REGISTRY_KEY, "GameOptionsVersion", 0) == OPTIONS_VERSION)
{
try
{
Settings["Renderer"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Renderer", Settings["Renderer"], typeof(string));
//System.Diagnostics.Debug.Assert(_Settings["Renderer"] is string);
Settings["Antialiasing"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Antialiasing", Settings["Antialiasing"], typeof(int));
Settings["AnisotropicFiltering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], typeof(int));
Settings["VideoWidth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoWidth", Settings["VideoWidth"], typeof(int));
Settings["VideoHeight"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], typeof(int));
Settings["VideoDepth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoDepth", Settings["VideoDepth"], typeof(int));
Settings["Windowed"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], typeof(int));
Settings["BorderlessWindow"] = RegistryExtensions.GetValue(REGISTRY_KEY, "BorderlessWindow", Settings["BorderlessWindow"], typeof(int));
Settings["VerticalSync"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], typeof(int));
Settings["TripleBuffering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "TripleBuffering", Settings["TripleBuffering"], typeof(int));
Settings["NoAutoUpdate"] = RegistryExtensions.GetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], typeof(int));
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Could not read game settings from registry!\n\nReason: {0}", ex.Message));
}
}
}
if ((int)Registry.GetValue(REGISTRY_KEY, "GameOptionsVersion", 0) == OPTIONS_VERSION)
{
try
{
Settings["Renderer"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Renderer", Settings["Renderer"], typeof(string));
Settings["Antialiasing"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Antialiasing", Settings["Antialiasing"], typeof(int));
Settings["AnisotropicFiltering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], typeof(int));
Settings["VideoWidth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoWidth", Settings["VideoWidth"], typeof(int));
Settings["VideoHeight"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], typeof(int));
Settings["VideoDepth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoDepth", Settings["VideoDepth"], typeof(int));
Settings["Windowed"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], typeof(int));
Settings["BorderlessWindow"] = RegistryExtensions.GetValue(REGISTRY_KEY, "BorderlessWindow", Settings["BorderlessWindow"], typeof(int));
Settings["VerticalSync"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], typeof(int));
Settings["TripleBuffering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "TripleBuffering", Settings["TripleBuffering"], typeof(int));
Settings["NoAutoUpdate"] = RegistryExtensions.GetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], typeof(int));
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Could not read game settings from registry!\n\nReason: {0}", ex.Message));
}
}
}
public static void Save()
{
try
{
Registry.SetValue(REGISTRY_KEY, "GameOptionsVersion", 3, RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "Renderer", Settings["Renderer"], RegistryValueKind.String);
Registry.SetValue(REGISTRY_KEY, "Antialiasing", Settings["Antialiasing"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoWidth", Settings["VideoWidth"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoDepth", Settings["VideoDepth"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "BorderlessWindow", Settings["BorderlessWindow"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "TripleBuffering", Settings["TripleBuffering"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], RegistryValueKind.DWord);
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Could not save game settings to registry!\n\nReason: {0}", ex.Message));
}
}
}
public static void Save()
{
try
{
Registry.SetValue(REGISTRY_KEY, "GameOptionsVersion", 3, RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "Renderer", Settings["Renderer"], RegistryValueKind.String);
Registry.SetValue(REGISTRY_KEY, "Antialiasing", Settings["Antialiasing"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoWidth", Settings["VideoWidth"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoDepth", Settings["VideoDepth"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "BorderlessWindow", Settings["BorderlessWindow"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "TripleBuffering", Settings["TripleBuffering"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], RegistryValueKind.DWord);
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Could not save game settings to registry!\n\nReason: {0}", ex.Message));
}
}
}
}

View File

@ -18,60 +18,60 @@ namespace Giants.Launcher
[DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
[DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture();
[DllImport("user32.dll")]
public static extern bool EnumDisplaySettings(
string deviceName, int modeNum, ref DEVMODE devMode);
const int ENUM_CURRENT_SETTINGS = -1;
[DllImport("user32.dll")]
public static extern bool EnumDisplaySettings(
string deviceName, int modeNum, ref DEVMODE devMode);
const int ENUM_CURRENT_SETTINGS = -1;
const int ENUM_REGISTRY_SETTINGS = -2;
const int ENUM_REGISTRY_SETTINGS = -2;
[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
[StructLayout(LayoutKind.Sequential)]
public struct DEVMODE
{
private const int CCHDEVICENAME = 0x20;
private const int CCHFORMNAME = 0x20;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public ScreenOrientation dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmFormName;
public short dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
private const int CCHDEVICENAME = 0x20;
private const int CCHFORMNAME = 0x20;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmDeviceName;
public short dmSpecVersion;
public short dmDriverVersion;
public short dmSize;
public short dmDriverExtra;
public int dmFields;
public int dmPositionX;
public int dmPositionY;
public ScreenOrientation dmDisplayOrientation;
public int dmDisplayFixedOutput;
public short dmColor;
public short dmDuplex;
public short dmYResolution;
public short dmTTOption;
public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmFormName;
public short dmLogPixels;
public int dmBitsPerPel;
public int dmPelsWidth;
public int dmPelsHeight;
public int dmDisplayFlags;
public int dmDisplayFrequency;
public int dmICMMethod;
public int dmICMIntent;
public int dmMediaType;
public int dmDitherType;
public int dmReserved1;
public int dmReserved2;
public int dmPanningWidth;
public int dmPanningHeight;
}
}
}
}

View File

@ -12,7 +12,7 @@ namespace Giants.Launcher
public struct GFXCapabilityInfo
{
public int maxAnisotropy;
public uint flags;
public uint flags;
public int priority;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string rendererName;
@ -22,118 +22,118 @@ namespace Giants.Launcher
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool GFXGetCapabilities(ref GFXCapabilityInfo outCapabilities);
/// <summary>
/// Makes interop call to native renderer DLL to obtain capability information.
/// </summary>
/// <returns>True if the given renderer is supported by the system.</returns>
public static bool GetRendererCapabilities(string dllPath, ref GFXCapabilityInfo capabilities)
{
bool rendererSupported = false;
IntPtr pDll = NativeMethods.LoadLibrary(dllPath);
if (pDll == IntPtr.Zero)
throw new System.Exception(string.Format("LoadLibrary() for {0} failed", dllPath));
/// <summary>
/// Makes interop call to native renderer DLL to obtain capability information.
/// </summary>
/// <returns>True if the given renderer is supported by the system.</returns>
public static bool GetRendererCapabilities(string dllPath, ref GFXCapabilityInfo capabilities)
{
bool rendererSupported = false;
IntPtr pDll = NativeMethods.LoadLibrary(dllPath);
if (pDll == IntPtr.Zero)
throw new System.Exception(string.Format("LoadLibrary() for {0} failed", dllPath));
IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "GFXGetCapabilities");
if (pAddressOfFunctionToCall == IntPtr.Zero)
return false;
IntPtr pAddressOfFunctionToCall = NativeMethods.GetProcAddress(pDll, "GFXGetCapabilities");
if (pAddressOfFunctionToCall == IntPtr.Zero)
return false;
var prcGetCapabilities = (GFXGetCapabilities)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(GFXGetCapabilities));
rendererSupported = prcGetCapabilities(ref capabilities);
var prcGetCapabilities = (GFXGetCapabilities)Marshal.GetDelegateForFunctionPointer(pAddressOfFunctionToCall, typeof(GFXGetCapabilities));
rendererSupported = prcGetCapabilities(ref capabilities);
NativeMethods.FreeLibrary(pDll);
NativeMethods.FreeLibrary(pDll);
return rendererSupported;
}
return rendererSupported;
}
public static List<Capabilities> GetCompatibleRenderers(string gamePath)
{
DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(gamePath));
public static List<Capabilities> GetCompatibleRenderers(string gamePath)
{
DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(gamePath));
List<Capabilities> Capabilities = new List<Capabilities>();
List<Capabilities> Capabilities = new List<Capabilities>();
// Search current directory for compatible renderers:
foreach (FileInfo file in dir.GetFiles("gg_*.dll"))
{
try
{
// Make interop call to native renderer DLLs to get capability info
RendererInterop.GFXCapabilityInfo interopCaps = new RendererInterop.GFXCapabilityInfo();
string path = Path.Combine(file.DirectoryName, file.Name);
if (RendererInterop.GetRendererCapabilities(path, ref interopCaps))
{
// Search current directory for compatible renderers:
foreach (FileInfo file in dir.GetFiles("gg_*.dll"))
{
try
{
// Make interop call to native renderer DLLs to get capability info
RendererInterop.GFXCapabilityInfo interopCaps = new RendererInterop.GFXCapabilityInfo();
string path = Path.Combine(file.DirectoryName, file.Name);
if (RendererInterop.GetRendererCapabilities(path, ref interopCaps))
{
Capabilities caps = new Capabilities(path, ref interopCaps);
Capabilities.Add(caps);
//cmbRenderer.Items.Add(caps);
}
Capabilities caps = new Capabilities(path, ref interopCaps);
Capabilities.Add(caps);
//cmbRenderer.Items.Add(caps);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
return Capabilities;
return Capabilities;
// Select highest priority renderer
//cmbRenderer.SelectedItem = _RendererCaps.Max();
}
// Select highest priority renderer
//cmbRenderer.SelectedItem = _RendererCaps.Max();
}
public class Capabilities : IComparable
{
[Flags]
public enum RendererFlag
{
LowBitDepthAllowed = 0x1,
public class Capabilities : IComparable
{
[Flags]
public enum RendererFlag
{
LowBitDepthAllowed = 0x1,
// Multisampling support flags:
MSAA2x = 0x2,
MSAA4x = 0x4,
MSAA8x = 0x8,
MSAA16x = 0x10,
// Multisampling support flags:
MSAA2x = 0x2,
MSAA4x = 0x4,
MSAA8x = 0x8,
MSAA16x = 0x10,
// Other options:
VSync = 0x20,
TripleBuffer = 0x40,
// Other options:
VSync = 0x20,
TripleBuffer = 0x40,
};
};
public Capabilities(string filePath, ref RendererInterop.GFXCapabilityInfo gfxCaps)
{
public Capabilities(string filePath, ref RendererInterop.GFXCapabilityInfo gfxCaps)
{
this.FilePath = filePath;
this.FileName = Path.GetFileName(filePath);
this.MaxAnisotropy = gfxCaps.maxAnisotropy;
this.Flags = (RendererFlag)gfxCaps.flags;
this.Priority = gfxCaps.priority;
this.Name = gfxCaps.rendererName;
}
}
public override string ToString()
{
return string.Format("{0} ({1})", this.Name, Path.GetFileName(this.FilePath));
}
public override string ToString()
{
return string.Format("{0} ({1})", this.Name, Path.GetFileName(this.FilePath));
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
public int CompareTo(object obj)
{
if (obj == null) return 1;
Capabilities other = obj as Capabilities;
if (other != null)
return this.Priority.CompareTo(other.Priority);
else
throw new ArgumentException();
}
Capabilities other = obj as Capabilities;
if (other != null)
return this.Priority.CompareTo(other.Priority);
else
throw new ArgumentException();
}
public string FilePath { get; private set; }
public string FileName { get; private set; }
public int MaxAnisotropy { get; private set; }
public RendererFlag Flags { get; private set; }
public int Priority { get; private set; }
public string Name { get; private set; }
}
public string FilePath { get; private set; }
public string FileName { get; private set; }
public int MaxAnisotropy { get; private set; }
public RendererFlag Flags { get; private set; }
public int Priority { get; private set; }
public string Name { get; private set; }
}
}
}

View File

@ -3,36 +3,35 @@
namespace Giants.Launcher
{
class ScreenResolution : IComparable
{
public int Width { get; set; }
public int Height { get; set; }
{
public int Width { get; set; }
public int Height { get; set; }
public ScreenResolution(int width, int height)
{
public ScreenResolution(int width, int height)
{
this.Width = width;
this.Height = height;
}
}
public int CompareTo(object obj)
{
if (obj == null) return 1;
public int CompareTo(object obj)
{
if (obj == null) return 1;
ScreenResolution other = obj as ScreenResolution;
if (other == null)
throw new ArgumentException();
ScreenResolution other = obj as ScreenResolution;
if (other == null)
throw new ArgumentException();
if (this.Width > other.Width)
return 1;
else if (this.Width == other.Width && this.Height == other.Height)
return 0;
else
return -1;
}
if (this.Width > other.Width)
return 1;
else if (this.Width == other.Width && this.Height == other.Height)
return 0;
else
return -1;
}
public override string ToString()
{
return string.Format("{0}x{1}", this.Width, this.Height);
}
}
public override string ToString()
{
return string.Format("{0}x{1}", this.Width, this.Height);
}
}
}

View File

@ -1,8 +1,8 @@
namespace Giants.Launcher
{
public enum ApplicationType
{
Launcher,
Game,
}
{
Launcher,
Game,
}
}

View File

@ -5,8 +5,8 @@ namespace Giants.Launcher
{
public class UpdateInfo
{
public int FileSize { get; set; }
public string FilePath { get; set; }
public ApplicationType ApplicationType { get; set; }
public int FileSize { get; set; }
public string FilePath { get; set; }
public ApplicationType ApplicationType { get; set; }
}
}

View File

@ -13,99 +13,99 @@ namespace Giants.Launcher
{
private readonly IDictionary<ApplicationType, Version> appVersions;
private readonly AsyncCompletedEventHandler updateCompletedCallback;
private readonly DownloadProgressChangedEventHandler updateProgressCallback;
public Updater(
IDictionary<ApplicationType, Version> appVersions,
AsyncCompletedEventHandler updateCompletedCallback,
DownloadProgressChangedEventHandler updateProgressCallback)
{
private readonly DownloadProgressChangedEventHandler updateProgressCallback;
public Updater(
IDictionary<ApplicationType, Version> appVersions,
AsyncCompletedEventHandler updateCompletedCallback,
DownloadProgressChangedEventHandler updateProgressCallback)
{
this.appVersions = appVersions;
this.updateCompletedCallback = updateCompletedCallback;
this.updateProgressCallback = updateProgressCallback;
}
public Task UpdateApplication(ApplicationType applicationType, VersionInfo versionInfo)
public Task UpdateApplication(ApplicationType applicationType, VersionInfo versionInfo)
{
try
{
if (this.ToVersion(versionInfo.Version) > this.appVersions[applicationType])
{
this.StartApplicationUpdate(applicationType, versionInfo);
}
}
catch (Exception)
try
{
if (this.ToVersion(versionInfo.Version) > this.appVersions[applicationType])
{
this.StartApplicationUpdate(applicationType, versionInfo);
}
}
catch (Exception)
{
}
return Task.CompletedTask;
return Task.CompletedTask;
}
private int GetHttpFileSize(Uri uri)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Proxy = null;
req.Method = "HEAD";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
private int GetHttpFileSize(Uri uri)
{
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Proxy = null;
req.Method = "HEAD";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
if (resp.StatusCode == HttpStatusCode.OK && int.TryParse(resp.Headers.Get("Content-Length"), out int contentLength))
{
resp.Close();
return contentLength;
}
resp.Close();
return -1;
}
private void StartApplicationUpdate(ApplicationType applicationType, VersionInfo versionInfo)
{
// Display update prompt
string updateMsg = applicationType == ApplicationType.Game ?
string.Format(Resources.UpdateAvailableText, this.ToVersion(versionInfo.Version).ToString()) :
string.Format(Resources.LauncherUpdateAvailableText, this.ToVersion(versionInfo.Version).ToString());
if (MessageBox.Show(updateMsg, Resources.UpdateAvailableTitle, MessageBoxButtons.YesNo) == DialogResult.No)
{
return; // User declined update
}
string patchFileName = Path.GetFileName(versionInfo.InstallerUri.AbsoluteUri);
string localPath = Path.Combine(Path.GetTempPath(), patchFileName);
// Delete the file locally if it already exists, just to be safe
if (File.Exists(localPath))
{
File.Delete(localPath);
}
int fileSize = this.GetHttpFileSize(versionInfo.InstallerUri);
if (fileSize == -1)
{
string errorMsg = string.Format(Resources.UpdateDownloadFailedText, "File not found on server.");
MessageBox.Show(errorMsg, Resources.UpdateDownloadFailedTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var updateInfo = new UpdateInfo()
if (resp.StatusCode == HttpStatusCode.OK && int.TryParse(resp.Headers.Get("Content-Length"), out int contentLength))
{
FilePath = localPath,
FileSize = fileSize,
ApplicationType = applicationType
resp.Close();
return contentLength;
}
resp.Close();
return -1;
}
private void StartApplicationUpdate(ApplicationType applicationType, VersionInfo versionInfo)
{
// Display update prompt
string updateMsg = applicationType == ApplicationType.Game ?
string.Format(Resources.UpdateAvailableText, this.ToVersion(versionInfo.Version).ToString()) :
string.Format(Resources.LauncherUpdateAvailableText, this.ToVersion(versionInfo.Version).ToString());
if (MessageBox.Show(updateMsg, Resources.UpdateAvailableTitle, MessageBoxButtons.YesNo) == DialogResult.No)
{
return; // User declined update
}
string patchFileName = Path.GetFileName(versionInfo.InstallerUri.AbsoluteUri);
string localPath = Path.Combine(Path.GetTempPath(), patchFileName);
// Delete the file locally if it already exists, just to be safe
if (File.Exists(localPath))
{
File.Delete(localPath);
}
int fileSize = this.GetHttpFileSize(versionInfo.InstallerUri);
if (fileSize == -1)
{
string errorMsg = string.Format(Resources.UpdateDownloadFailedText, "File not found on server.");
MessageBox.Show(errorMsg, Resources.UpdateDownloadFailedTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var updateInfo = new UpdateInfo()
{
FilePath = localPath,
FileSize = fileSize,
ApplicationType = applicationType
};
// Download the update
// TODO: Super old code, replace this with async HttpClient
WebClient client = new WebClient();
// Download the update
// TODO: Super old code, replace this with async HttpClient
WebClient client = new WebClient();
client.DownloadFileAsync(versionInfo.InstallerUri, localPath, updateInfo);
client.DownloadFileCompleted += this.updateCompletedCallback;
client.DownloadProgressChanged += this.updateProgressCallback;
}
client.DownloadFileCompleted += this.updateCompletedCallback;
client.DownloadProgressChanged += this.updateProgressCallback;
}
private Version ToVersion(AppVersion version)
{
return new Version(version.Major, version.Minor, version.Build, version.Revision);
}
}
{
return new Version(version.Major, version.Minor, version.Build, version.Revision);
}
}
}

View File

@ -5,9 +5,9 @@ using System.Text;
namespace Giants.Launcher
{
public enum WindowType
{
Fullscreen = 0,
Windowed = 1,
Borderless = 2,
}
{
Fullscreen = 0,
Windowed = 1,
Borderless = 2,
}
}