1
0
mirror of https://github.com/ncblakely/GiantsTools synced 2024-11-22 06:05:38 +01:00

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 namespace Giants.Launcher
{ {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class ApplicationNames public class ApplicationNames
{ {
public const string Giants = nameof(Giants); public const string Giants = nameof(Giants);

View File

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

View File

@ -8,114 +8,115 @@ using Microsoft.Win32;
namespace Giants.Launcher namespace Giants.Launcher
{ {
static class GameSettings static class GameSettings
{ {
// Constants // Constants
private const string REGISTRY_KEY = @"HKEY_CURRENT_USER\Software\PlanetMoon\Giants"; private const string REGISTRY_KEY = @"HKEY_CURRENT_USER\Software\PlanetMoon\Giants";
private const int OPTIONS_VERSION = 3; 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. // List of renderers compatible with the user's system.
static public List<RendererInterop.Capabilities> CompatibleRenderers; static public List<RendererInterop.Capabilities> CompatibleRenderers;
public static object Get(string settingName) public static object Get(string settingName)
{ {
if (Settings.ContainsKey(settingName)) if (Settings.ContainsKey(settingName))
return Settings[settingName]; return Settings[settingName];
else else
return 0; return 0;
} }
public static void Modify(string settingName, object settingValue) public static void Modify(string settingName, object settingValue)
{ {
Settings[settingName] = settingValue; Settings[settingName] = settingValue;
} }
public static void SetDefaults(string gamePath) public static void SetDefaults(string gamePath)
{ {
// Set default settings: // Set default settings:
Settings["Renderer"] = "gg_dx7r.dll"; Settings["Renderer"] = "gg_dx7r.dll";
Settings["Antialiasing"] = 0; Settings["Antialiasing"] = 0;
Settings["AnisotropicFiltering"] = 0; Settings["AnisotropicFiltering"] = 0;
Settings["VideoWidth"] = 640; Settings["VideoWidth"] = 640;
Settings["VideoHeight"] = 480; Settings["VideoHeight"] = 480;
Settings["VideoDepth"] = 32; Settings["VideoDepth"] = 32;
Settings["Windowed"] = 0; Settings["Windowed"] = 0;
Settings["BorderlessWindow"] = 0; Settings["BorderlessWindow"] = 0;
Settings["VerticalSync"] = 1; Settings["VerticalSync"] = 1;
Settings["TripleBuffering"] = 1; Settings["TripleBuffering"] = 1;
Settings["NoAutoUpdate"] = 0; Settings["NoAutoUpdate"] = 0;
// Get a list of renderers compatible with the user's system // Get a list of renderers compatible with the user's system
if (CompatibleRenderers == null) if (CompatibleRenderers == null)
{ {
CompatibleRenderers = RendererInterop.GetCompatibleRenderers(gamePath); CompatibleRenderers = RendererInterop.GetCompatibleRenderers(gamePath);
if (CompatibleRenderers.Count == 0) 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.", MessageBox.Show(
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error); "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 // Select the highest priority renderer
if (CompatibleRenderers.Count > 0) if (CompatibleRenderers.Count > 0)
Settings["Renderer"] = Path.GetFileName(CompatibleRenderers.Max().FilePath); Settings["Renderer"] = Path.GetFileName(CompatibleRenderers.Max().FilePath);
// Set the current desktop resolution, leaving bit depth at the default 32: // Set the current desktop resolution, leaving bit depth at the default 32:
Settings["VideoWidth"] = Screen.PrimaryScreen.Bounds.Width; Settings["VideoWidth"] = Screen.PrimaryScreen.Bounds.Width;
Settings["VideoHeight"] = Screen.PrimaryScreen.Bounds.Height; Settings["VideoHeight"] = Screen.PrimaryScreen.Bounds.Height;
} }
public static void Load(string gamePath) public static void Load(string gamePath)
{ {
SetDefaults(gamePath); SetDefaults(gamePath);
if ((int)Registry.GetValue(REGISTRY_KEY, "GameOptionsVersion", 0) == OPTIONS_VERSION) if ((int)Registry.GetValue(REGISTRY_KEY, "GameOptionsVersion", 0) == OPTIONS_VERSION)
{ {
try try
{ {
Settings["Renderer"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Renderer", Settings["Renderer"], typeof(string)); 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["Antialiasing"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Antialiasing", Settings["Antialiasing"], typeof(int)); Settings["AnisotropicFiltering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], 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["VideoWidth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoWidth", Settings["VideoWidth"], typeof(int)); Settings["VideoHeight"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], 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["VideoDepth"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VideoDepth", Settings["VideoDepth"], typeof(int)); Settings["Windowed"] = RegistryExtensions.GetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], 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["BorderlessWindow"] = RegistryExtensions.GetValue(REGISTRY_KEY, "BorderlessWindow", Settings["BorderlessWindow"], typeof(int)); Settings["VerticalSync"] = RegistryExtensions.GetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], 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["TripleBuffering"] = RegistryExtensions.GetValue(REGISTRY_KEY, "TripleBuffering", Settings["TripleBuffering"], typeof(int)); Settings["NoAutoUpdate"] = RegistryExtensions.GetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], typeof(int));
Settings["NoAutoUpdate"] = RegistryExtensions.GetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], typeof(int)); }
} catch (Exception ex)
catch (Exception ex) {
{ MessageBox.Show(string.Format("Could not read game settings from registry!\n\nReason: {0}", ex.Message));
MessageBox.Show(string.Format("Could not read game settings from registry!\n\nReason: {0}", ex.Message)); }
} }
} }
}
public static void Save() public static void Save()
{ {
try try
{ {
Registry.SetValue(REGISTRY_KEY, "GameOptionsVersion", 3, RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "GameOptionsVersion", 3, RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "Renderer", Settings["Renderer"], RegistryValueKind.String); Registry.SetValue(REGISTRY_KEY, "Renderer", Settings["Renderer"], RegistryValueKind.String);
Registry.SetValue(REGISTRY_KEY, "Antialiasing", Settings["Antialiasing"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "Antialiasing", Settings["Antialiasing"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "AnisotropicFiltering", Settings["AnisotropicFiltering"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoWidth", Settings["VideoWidth"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "VideoWidth", Settings["VideoWidth"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "VideoHeight", Settings["VideoHeight"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VideoDepth", Settings["VideoDepth"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "VideoDepth", Settings["VideoDepth"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "Windowed", Settings["Windowed"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "BorderlessWindow", Settings["BorderlessWindow"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "BorderlessWindow", Settings["BorderlessWindow"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "VerticalSync", Settings["VerticalSync"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "TripleBuffering", Settings["TripleBuffering"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "TripleBuffering", Settings["TripleBuffering"], RegistryValueKind.DWord);
Registry.SetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], RegistryValueKind.DWord); Registry.SetValue(REGISTRY_KEY, "NoAutoUpdate", Settings["NoAutoUpdate"], RegistryValueKind.DWord);
} }
catch (Exception ex) catch (Exception ex)
{ {
MessageBox.Show(string.Format("Could not save game settings to registry!\n\nReason: {0}", ex.Message)); 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")] [DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd); public static extern bool SetForegroundWindow(IntPtr hWnd);
public const int WM_NCLBUTTONDOWN = 0xA1; public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2; public const int HT_CAPTION = 0x2;
[DllImportAttribute("user32.dll")] [DllImportAttribute("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImportAttribute("user32.dll")] [DllImportAttribute("user32.dll")]
public static extern bool ReleaseCapture(); public static extern bool ReleaseCapture();
[DllImport("user32.dll")] [DllImport("user32.dll")]
public static extern bool EnumDisplaySettings( public static extern bool EnumDisplaySettings(
string deviceName, int modeNum, ref DEVMODE devMode); string deviceName, int modeNum, ref DEVMODE devMode);
const int ENUM_CURRENT_SETTINGS = -1; const int ENUM_CURRENT_SETTINGS = -1;
const int ENUM_REGISTRY_SETTINGS = -2; const int ENUM_REGISTRY_SETTINGS = -2;
[StructLayout(LayoutKind.Sequential)] [StructLayout(LayoutKind.Sequential)]
public struct DEVMODE public struct DEVMODE
{ {
private const int CCHDEVICENAME = 0x20; private const int CCHDEVICENAME = 0x20;
private const int CCHFORMNAME = 0x20; private const int CCHFORMNAME = 0x20;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmDeviceName; public string dmDeviceName;
public short dmSpecVersion; public short dmSpecVersion;
public short dmDriverVersion; public short dmDriverVersion;
public short dmSize; public short dmSize;
public short dmDriverExtra; public short dmDriverExtra;
public int dmFields; public int dmFields;
public int dmPositionX; public int dmPositionX;
public int dmPositionY; public int dmPositionY;
public ScreenOrientation dmDisplayOrientation; public ScreenOrientation dmDisplayOrientation;
public int dmDisplayFixedOutput; public int dmDisplayFixedOutput;
public short dmColor; public short dmColor;
public short dmDuplex; public short dmDuplex;
public short dmYResolution; public short dmYResolution;
public short dmTTOption; public short dmTTOption;
public short dmCollate; public short dmCollate;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)] [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x20)]
public string dmFormName; public string dmFormName;
public short dmLogPixels; public short dmLogPixels;
public int dmBitsPerPel; public int dmBitsPerPel;
public int dmPelsWidth; public int dmPelsWidth;
public int dmPelsHeight; public int dmPelsHeight;
public int dmDisplayFlags; public int dmDisplayFlags;
public int dmDisplayFrequency; public int dmDisplayFrequency;
public int dmICMMethod; public int dmICMMethod;
public int dmICMIntent; public int dmICMIntent;
public int dmMediaType; public int dmMediaType;
public int dmDitherType; public int dmDitherType;
public int dmReserved1; public int dmReserved1;
public int dmReserved2; public int dmReserved2;
public int dmPanningWidth; public int dmPanningWidth;
public int dmPanningHeight; public int dmPanningHeight;
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

@ -13,99 +13,99 @@ namespace Giants.Launcher
{ {
private readonly IDictionary<ApplicationType, Version> appVersions; private readonly IDictionary<ApplicationType, Version> appVersions;
private readonly AsyncCompletedEventHandler updateCompletedCallback; private readonly AsyncCompletedEventHandler updateCompletedCallback;
private readonly DownloadProgressChangedEventHandler updateProgressCallback; private readonly DownloadProgressChangedEventHandler updateProgressCallback;
public Updater( public Updater(
IDictionary<ApplicationType, Version> appVersions, IDictionary<ApplicationType, Version> appVersions,
AsyncCompletedEventHandler updateCompletedCallback, AsyncCompletedEventHandler updateCompletedCallback,
DownloadProgressChangedEventHandler updateProgressCallback) DownloadProgressChangedEventHandler updateProgressCallback)
{ {
this.appVersions = appVersions; this.appVersions = appVersions;
this.updateCompletedCallback = updateCompletedCallback; this.updateCompletedCallback = updateCompletedCallback;
this.updateProgressCallback = updateProgressCallback; this.updateProgressCallback = updateProgressCallback;
} }
public Task UpdateApplication(ApplicationType applicationType, VersionInfo versionInfo) public Task UpdateApplication(ApplicationType applicationType, VersionInfo versionInfo)
{ {
try try
{ {
if (this.ToVersion(versionInfo.Version) > this.appVersions[applicationType]) if (this.ToVersion(versionInfo.Version) > this.appVersions[applicationType])
{ {
this.StartApplicationUpdate(applicationType, versionInfo); this.StartApplicationUpdate(applicationType, versionInfo);
} }
} }
catch (Exception) catch (Exception)
{ {
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
private int GetHttpFileSize(Uri uri) private int GetHttpFileSize(Uri uri)
{ {
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.Proxy = null; req.Proxy = null;
req.Method = "HEAD"; req.Method = "HEAD";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
if (resp.StatusCode == HttpStatusCode.OK && int.TryParse(resp.Headers.Get("Content-Length"), out int contentLength)) 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()
{ {
FilePath = localPath, resp.Close();
FileSize = fileSize, return contentLength;
ApplicationType = applicationType }
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 // Download the update
// TODO: Super old code, replace this with async HttpClient // TODO: Super old code, replace this with async HttpClient
WebClient client = new WebClient(); WebClient client = new WebClient();
client.DownloadFileAsync(versionInfo.InstallerUri, localPath, updateInfo); client.DownloadFileAsync(versionInfo.InstallerUri, localPath, updateInfo);
client.DownloadFileCompleted += this.updateCompletedCallback; client.DownloadFileCompleted += this.updateCompletedCallback;
client.DownloadProgressChanged += this.updateProgressCallback; client.DownloadProgressChanged += this.updateProgressCallback;
} }
private Version ToVersion(AppVersion version) 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 namespace Giants.Launcher
{ {
public enum WindowType public enum WindowType
{ {
Fullscreen = 0, Fullscreen = 0,
Windowed = 1, Windowed = 1,
Borderless = 2, Borderless = 2,
} }
} }