Extract parent class from `{FFmpeg,RAIntegration}DownloaderForm`

This commit is contained in:
YoshiRulz 2025-04-10 21:08:33 +10:00
parent b52bce6fe0
commit 15cdf2d49d
No known key found for this signature in database
GPG Key ID: C4DE31C245353FB7
7 changed files with 226 additions and 612 deletions

View File

@ -1,164 +1,34 @@
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using BizHawk.Common;
namespace BizHawk.Client.EmuHawk
{
/// <summary>
/// Downloads FFmpeg
/// </summary>
public partial class FFmpegDownloaderForm : Form
public sealed class FFmpegDownloaderForm : DownloaderForm
{
protected override string ComponentName
=> "FFmpeg";
protected override string DownloadTemp { get; }
= TempFileManager.GetTempFilename("ffmpeg_download", ".7z", delete: false);
public FFmpegDownloaderForm()
{
_path = FFmpegService.FFmpegPath;
_url = FFmpegService.Url;
InitializeComponent();
txtLocation.Text = _path;
txtUrl.Text = _url;
if (OSTailoredCode.IsUnixHost) textBox1.Text = string.Join("\n", textBox1.Text.Split('\n').Take(3)) + "\n\n(Linux user: If installing manually, you can use a symlink.)";
Description = "BizHawk relies on a specific version of FFmpeg. No other version will do. The wrong version will be ignored. There is no way to override this behavior."
+ "\n\nThe required version could not be found."
+ (OSTailoredCode.IsUnixHost
? "\n\n(Linux user: If installing manually, you can use a symlink.)"
: "\n\nUse this dialog to download it automatically, or download it yourself from the URL below and place it in the specified location.");
DownloadFrom = FFmpegService.Url;
DownloadTo = FFmpegService.FFmpegPath;
}
private readonly string _path;
private readonly string _url;
protected override Stream GetExtractionStream(HawkFile downloaded)
=> (OSTailoredCode.IsUnixHost
? downloaded.BindArchiveMember("ffmpeg")!
: downloaded.BindFirstOf(".exe")).GetStream();
private int _pct = 0;
private bool _exiting = false;
private bool _succeeded = false;
private bool _failed = false;
private void ThreadProc()
{
Download();
}
private void Download()
{
//the temp file is owned by this thread
var fn = TempFileManager.GetTempFilename("ffmpeg_download", ".7z", false);
try
{
DirectoryInfo parentDir = new(Path.GetDirectoryName(_path)!);
if (!parentDir.Exists) parentDir.Create();
// check writable before bothering with the download
if (File.Exists(_path)) File.Delete(_path);
using var fs = File.Create(_path);
using (var evt = new ManualResetEvent(false))
{
using var client = new WebClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
client.DownloadFileAsync(new Uri(_url), fn);
client.DownloadProgressChanged += (_, progressArgs) => _pct = progressArgs.ProgressPercentage;
client.DownloadFileCompleted += (_, _) => evt.Set(); // we don't really need a status, we'll just try to unzip it when it's done
while (true)
{
if (evt.WaitOne(10)) break;
//if the gui thread ordered an exit, cancel the download and wait for it to acknowledge
if (_exiting)
{
client.CancelAsync();
evt.WaitOne();
break;
}
}
}
// throw new Exception("test of download failure");
//if we were ordered to exit, bail without wasting any more time
if (_exiting) return;
//try acquiring file
using (var hf = new HawkFile(fn))
{
using (var exe = OSTailoredCode.IsUnixHost ? hf.BindArchiveMember("ffmpeg") : hf.BindFirstOf(".exe"))
{
//last chance. exiting, don't dump the new ffmpeg file
if (_exiting) return;
exe!.GetStream().CopyTo(fs);
fs.Dispose();
if (OSTailoredCode.IsUnixHost)
{
OSTailoredCode.ConstructSubshell("chmod", $"+x {_path}", checkStdout: false).Start();
Thread.Sleep(50); // Linux I/O flush idk
}
}
}
//make sure it worked
if (!FFmpegService.QueryServiceAvailable()) throw new Exception("download failed");
_succeeded = true;
}
catch (Exception e)
{
_failed = true;
Util.DebugWriteLine($"FFmpeg download failed with:\n{e}");
}
finally
{
try
{
File.Delete(fn);
}
catch
{
// ignore
}
}
}
private void btnDownload_Click(object sender, EventArgs e)
{
btnDownload.Text = "Downloading...";
btnDownload.Enabled = false;
_failed = false;
_succeeded = false;
_pct = 0;
var t = new Thread(ThreadProc);
t.Start();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
protected override void OnClosed(EventArgs e)
{
//inform the worker thread that it needs to try terminating without doing anything else
//(it will linger on in background for a bit til it can service this)
_exiting = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
//if it's done, close the window. the user will be smart enough to reopen it
if (_succeeded) Close();
if (_failed)
{
_failed = false;
_pct = 0;
btnDownload.Text = "FAILED - Download Again";
btnDownload.Enabled = true;
}
progressBar1.Value = _pct;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(_url);
}
protected override bool PostChmodCheck()
=> FFmpegService.QueryServiceAvailable();
}
}

View File

@ -1,132 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="textBox1.Text" xml:space="preserve">
<value>BizHawk relies on a specific version of FFmpeg. No other version will do. The wrong version will be ignored. There is no way to override this behavior.
The required version could not be found.
Use this dialog to download it automatically, or download it yourself from the URL below and place it in the specified location
</value>
</data>
<metadata name="timer1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -1,6 +1,6 @@
namespace BizHawk.Client.EmuHawk
{
partial class FFmpegDownloaderForm
partial class DownloaderForm
{
/// <summary>
/// Required designer variable.
@ -29,7 +29,6 @@
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FFmpegDownloaderForm));
this.btnCancel = new System.Windows.Forms.Button();
this.btnDownload = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
@ -73,7 +72,7 @@
this.textBox1.ReadOnly = true;
this.textBox1.Size = new System.Drawing.Size(699, 95);
this.textBox1.TabIndex = 10;
this.textBox1.Text = resources.GetString("textBox1.Text");
this.textBox1.Text = "%description%";
//
// label3
//
@ -112,6 +111,7 @@
this.txtLocation.ReadOnly = true;
this.txtLocation.Size = new System.Drawing.Size(613, 20);
this.txtLocation.TabIndex = 15;
this.txtLocation.Text = "%downloadTo%";
//
// label1
//
@ -138,8 +138,9 @@
this.txtUrl.ReadOnly = true;
this.txtUrl.Size = new System.Drawing.Size(613, 20);
this.txtUrl.TabIndex = 18;
this.txtUrl.Text = "%downloadFrom%";
//
// FFmpegDownloaderForm
// DownloaderForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
@ -159,10 +160,10 @@
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(300, 160);
this.Name = "FFmpegDownloaderForm";
this.Name = "DownloaderForm";
this.ShowIcon = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Download FFmpeg";
this.Text = "%windowTitle%";
this.ResumeLayout(false);
this.PerformLayout();

View File

@ -0,0 +1,186 @@
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using BizHawk.Common;
namespace BizHawk.Client.EmuHawk
{
public partial class DownloaderForm : Form
{
protected virtual string ComponentName { get; } = null!;
public string Description
{
get => textBox1.Text;
init => textBox1.Text = value;
}
public string DownloadFrom
{
get => txtUrl.Text;
init => txtUrl.Text = value;
}
protected virtual string DownloadTemp { get; } = null!;
public string DownloadTo
{
get => txtLocation.Text;
init => txtLocation.Text = value;
}
public DownloaderForm()
{
InitializeComponent();
Load += (_, _) => Text = $"Download {ComponentName ?? "COMPONENT UNSET"}";
}
private int _pct = 0;
private bool _exiting = false;
private bool _succeeded = false;
private bool _failed = false;
private Thread/*?*/ _thread = null;
public bool DownloadSucceeded()
{
// block until the thread dies
while (_thread is { IsAlive: true })
{
Thread.Sleep(1);
}
return _succeeded;
}
private void ThreadProc()
{
Download();
}
private void Download()
{
try
{
DirectoryInfo parentDir = new(Path.GetDirectoryName(DownloadTo)!);
if (!parentDir.Exists) parentDir.Create();
// check writable before bothering with the download
if (File.Exists(DownloadTo)) File.Delete(DownloadTo);
using var fs = File.Create(DownloadTo);
using (var evt = new ManualResetEvent(false))
{
using var client = new WebClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
client.DownloadFileAsync(new Uri(DownloadFrom), DownloadTemp);
client.DownloadProgressChanged += (_, progressArgs) => _pct = progressArgs.ProgressPercentage;
client.DownloadFileCompleted += (_, _) => evt.Set(); // we don't really need a status, we'll just try to unzip it when it's done
while (true)
{
if (evt.WaitOne(10)) break;
//if the gui thread ordered an exit, cancel the download and wait for it to acknowledge
if (_exiting)
{
client.CancelAsync();
evt.WaitOne();
break;
}
}
}
// throw new Exception("test of download failure");
//if we were ordered to exit, bail without wasting any more time
if (_exiting) return;
//try acquiring file
using (HawkFile hf = new(DownloadTemp))
{
using var exStream = GetExtractionStream(hf);
//last chance. exiting, don't dump the new file
if (_exiting) return;
exStream.CopyTo(fs);
fs.Dispose();
if (OSTailoredCode.IsUnixHost)
{
OSTailoredCode.ConstructSubshell("chmod", $"+x {DownloadTo}", checkStdout: false).Start();
Thread.Sleep(50); // Linux I/O flush idk
}
}
//make sure it worked
if (!PostChmodCheck()) throw new Exception("download failed");
_succeeded = true;
}
catch (Exception e)
{
_failed = true;
Util.DebugWriteLine($"{ComponentName} download failed with:\n{e}");
}
finally
{
try
{
File.Delete(DownloadTemp);
}
catch
{
// ignore
}
}
}
protected virtual Stream GetExtractionStream(HawkFile downloaded)
=> throw new NotImplementedException();
protected virtual bool PostChmodCheck()
=> true;
private void btnDownload_Click(object sender, EventArgs e)
{
btnDownload.Text = "Downloading...";
btnDownload.Enabled = false;
_failed = false;
_succeeded = false;
_pct = 0;
_thread = new(ThreadProc);
_thread.Start();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
protected override void OnClosed(EventArgs e)
{
//inform the worker thread that it needs to try terminating without doing anything else
//(it will linger on in background for a bit til it can service this)
_exiting = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
//if it's done, close the window. the user will be smart enough to reopen it
if (_succeeded) Close();
if (_failed)
{
_failed = false;
_pct = 0;
btnDownload.Text = "FAILED - Download Again";
btnDownload.Enabled = true;
}
progressBar1.Value = _pct;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(DownloadFrom);
}
}
}

View File

@ -117,7 +117,4 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="timer1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
</root>

View File

@ -1,170 +0,0 @@
namespace BizHawk.Client.EmuHawk
{
partial class RAIntegrationDownloaderForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.btnCancel = new System.Windows.Forms.Button();
this.btnDownload = new System.Windows.Forms.Button();
this.label3 = new BizHawk.WinForms.Controls.LocLabelEx();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.timer1 = new System.Windows.Forms.Timer(this.components);
this.txtLocation = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtUrl = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// btnCancel
//
this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.btnCancel.Location = new System.Drawing.Point(667, 86);
this.btnCancel.Name = "btnCancel";
this.btnCancel.Size = new System.Drawing.Size(75, 23);
this.btnCancel.TabIndex = 7;
this.btnCancel.Text = "Cancel";
this.btnCancel.UseVisualStyleBackColor = true;
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// btnDownload
//
this.btnDownload.Location = new System.Drawing.Point(9, 86);
this.btnDownload.Name = "btnDownload";
this.btnDownload.Size = new System.Drawing.Size(186, 23);
this.btnDownload.TabIndex = 6;
this.btnDownload.Text = "Download";
this.btnDownload.UseVisualStyleBackColor = true;
this.btnDownload.Click += new System.EventHandler(this.btnDownload_Click);
//
// label3
//
this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.label3.Location = new System.Drawing.Point(6, -35);
this.label3.MaximumSize = new System.Drawing.Size(260, 0);
this.label3.Name = "label3";
//
// linkLabel1
//
this.linkLabel1.AutoSize = true;
this.linkLabel1.Location = new System.Drawing.Point(715, 61);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(27, 13);
this.linkLabel1.TabIndex = 12;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "Link";
this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked);
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(201, 86);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(186, 23);
this.progressBar1.TabIndex = 13;
//
// timer1
//
this.timer1.Enabled = true;
this.timer1.Tick += new System.EventHandler(this.timer1_Tick);
//
// txtLocation
//
this.txtLocation.Location = new System.Drawing.Point(95, 12);
this.txtLocation.Name = "txtLocation";
this.txtLocation.ReadOnly = true;
this.txtLocation.Size = new System.Drawing.Size(613, 20);
this.txtLocation.TabIndex = 15;
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(9, 15);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 13);
this.label1.TabIndex = 16;
this.label1.Text = "Local Location:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(57, 41);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(32, 13);
this.label2.TabIndex = 17;
this.label2.Text = "URL:";
//
// txtUrl
//
this.txtUrl.Location = new System.Drawing.Point(96, 38);
this.txtUrl.Name = "txtUrl";
this.txtUrl.ReadOnly = true;
this.txtUrl.Size = new System.Drawing.Size(613, 20);
this.txtUrl.TabIndex = 18;
//
// RAIntegrationDownloaderForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.CancelButton = this.btnCancel;
this.ClientSize = new System.Drawing.Size(754, 121);
this.Controls.Add(this.progressBar1);
this.Controls.Add(this.txtUrl);
this.Controls.Add(this.btnDownload);
this.Controls.Add(this.label2);
this.Controls.Add(this.linkLabel1);
this.Controls.Add(this.label1);
this.Controls.Add(this.txtLocation);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.label3);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(300, 160);
this.Name = "RAIntegrationDownloaderForm";
this.ShowIcon = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "Download RAIntegration";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private BizHawk.WinForms.Controls.LocLabelEx label3;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.Button btnDownload;
private System.Windows.Forms.LinkLabel linkLabel1;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Timer timer1;
private System.Windows.Forms.TextBox txtLocation;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox txtUrl;
}
}

View File

@ -1,164 +1,26 @@
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using BizHawk.Common;
using BizHawk.Common.PathExtensions;
namespace BizHawk.Client.EmuHawk
{
/// <summary>
/// Downloads RAIntegration (largely a copy paste of ffmpeg's downloader)
/// </summary>
public partial class RAIntegrationDownloaderForm : Form
public sealed class RAIntegrationDownloaderForm : DownloaderForm
{
public RAIntegrationDownloaderForm(string url)
protected override string ComponentName
=> "RAIntegration";
protected override string DownloadTemp { get; }
= TempFileManager.GetTempFilename("RAIntegration_download", ".dll", delete: false);
public RAIntegrationDownloaderForm(string downloadFrom)
{
_path = Path.Combine(PathUtils.DataDirectoryPath, "dll", "RA_Integration-x64.dll");
_url = url;
InitializeComponent();
txtLocation.Text = _path;
txtUrl.Text = _url;
Description = string.Empty;
DownloadFrom = downloadFrom;
DownloadTo = Path.Combine(PathUtils.DataDirectoryPath, "dll", "RA_Integration-x64.dll");
}
private readonly string _path;
private readonly string _url;
private int _pct = 0;
private bool _exiting = false;
private bool _succeeded = false;
private bool _failed = false;
private Thread/*?*/ _thread = null;
public bool DownloadSucceeded()
{
// block until the thread dies
while (_thread is { IsAlive: true })
{
Thread.Sleep(1);
}
return _succeeded;
}
private void ThreadProc()
{
Download();
}
private void Download()
{
//the temp file is owned by this thread
var fn = TempFileManager.GetTempFilename("RAIntegration_download", ".dll", false);
try
{
DirectoryInfo parentDir = new(Path.GetDirectoryName(_path)!);
if (!parentDir.Exists) parentDir.Create();
// check writable before bothering with the download
if (File.Exists(_path)) File.Delete(_path);
using var fs = File.Create(_path);
using (var evt = new ManualResetEvent(false))
{
using var client = new WebClient();
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
client.DownloadFileAsync(new Uri(_url), fn);
client.DownloadProgressChanged += (_, progressArgs) => _pct = progressArgs.ProgressPercentage;
client.DownloadFileCompleted += (_, _) => evt.Set(); // we don't really need a status, we'll just try to unzip it when it's done
while (true)
{
if (evt.WaitOne(10)) break;
//if the gui thread ordered an exit, cancel the download and wait for it to acknowledge
if (_exiting)
{
client.CancelAsync();
evt.WaitOne();
break;
}
}
}
// throw new Exception("test of download failure");
//if we were ordered to exit, bail without wasting any more time
if (_exiting) return;
//try acquiring file
using (var dll = new HawkFile(fn))
{
//last chance. exiting, don't dump the new RAIntegration file
if (_exiting) return;
dll.GetStream().CopyTo(fs);
}
_succeeded = true;
}
catch (Exception e)
{
_failed = true;
Util.DebugWriteLine($"RAIntegration download failed with:\n{e}");
}
finally
{
try
{
File.Delete(fn);
}
catch
{
// ignore
}
}
}
private void btnDownload_Click(object sender, EventArgs e)
{
btnDownload.Text = "Downloading...";
btnDownload.Enabled = false;
_failed = false;
_succeeded = false;
_pct = 0;
_thread = new Thread(ThreadProc);
_thread.Start();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
protected override void OnClosed(EventArgs e)
{
//inform the worker thread that it needs to try terminating without doing anything else
//(it will linger on in background for a bit til it can service this)
_exiting = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
//if it's done, close the window. the user will be smart enough to reopen it
if (_succeeded) Close();
if (_failed)
{
_failed = false;
_pct = 0;
btnDownload.Text = "FAILED - Download Again";
btnDownload.Enabled = true;
}
progressBar1.Value = _pct;
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Process.Start(_url);
}
protected override Stream GetExtractionStream(HawkFile downloaded)
=> downloaded.GetStream();
}
}