random-file-runner/MainForm.cs

672 lines
20 KiB
C#
Raw Permalink Normal View History

using RandomFileRunner.IO;
using RyzStudio.Windows.Forms;
2021-10-24 15:49:48 +00:00
using System;
using System.Collections.Generic;
2021-10-30 02:21:45 +00:00
using System.ComponentModel;
2021-10-24 16:16:37 +00:00
using System.Diagnostics;
2021-10-24 15:49:48 +00:00
using System.Drawing;
using System.IO;
2021-10-30 02:21:45 +00:00
using System.Runtime.InteropServices;
2021-10-30 23:40:58 +00:00
using System.Text.Json;
using System.Threading.Tasks;
2021-10-24 15:49:48 +00:00
using System.Windows.Forms;
namespace RandomFileRunner
{
public partial class MainForm : Form
{
2021-10-30 02:21:45 +00:00
[DllImport("user32.dll")]
protected static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
[DllImport("user32.dll")]
protected static extern bool UnregisterHotKey(IntPtr hWnd, int id);
//protected const int MOD_NONE = 0x0000;
//protected const int MOD_ALT = 0x1;
//protected const int MOD_CONTROL = 0x2;
//protected const int MOD_SHIFT = 0x4;
//protected const int MOD_WIN = 0x8;
protected const int WM_HOTKEY = 0x312;
protected const int WM_QUERYENDSESSION = 0x0011;
2021-10-24 15:49:48 +00:00
protected readonly Random randy;
protected OptionsForm optionsForm = null;
protected bool isBusy = false;
protected bool requestCancel = false;
2021-10-24 15:49:48 +00:00
protected List<string> foundFiles = null;
2021-10-24 16:16:37 +00:00
protected Process currentProcess = null;
2021-10-24 15:49:48 +00:00
public MainForm()
{
InitializeComponent();
2021-10-24 16:16:37 +00:00
textBox1.Text = "*.*";
memoBox1.InnerTextBox.WordWrap = false;
2021-10-24 15:49:48 +00:00
2021-10-24 16:16:37 +00:00
randy = new Random();
2021-10-24 15:49:48 +00:00
}
2021-10-31 03:23:25 +00:00
protected async override void OnShown(EventArgs e)
{
base.OnShown(e);
string[] commandLineArgs = Environment.GetCommandLineArgs();
string jsonfigFilename = null;
if (string.IsNullOrWhiteSpace(jsonfigFilename)) jsonfigFilename = ParseOpenFile_FromCMD(commandLineArgs);
if (string.IsNullOrWhiteSpace(jsonfigFilename)) jsonfigFilename = Path.ChangeExtension(Application.ExecutablePath, "jsonfig");
if (!string.IsNullOrWhiteSpace(jsonfigFilename) && File.Exists(jsonfigFilename))
{
await LoadSessionFile(jsonfigFilename);
}
}
2021-10-30 02:21:45 +00:00
protected override void OnClosing(CancelEventArgs e)
2021-10-24 15:49:48 +00:00
{
2021-10-30 02:21:45 +00:00
base.OnClosing(e);
2021-10-24 15:49:48 +00:00
if (this.IsBusy)
{
e.Cancel = true;
return;
}
2021-10-30 02:21:45 +00:00
if (this.CurrentSession.ClosePrevOnNext) CloseCurrentProcess(currentProcess);
if (this.CurrentSession.NextHotKey != null)
{
if (this.CurrentSession.NextHotKey.KeyCode != Keys.None)
{
//#if !DEBUG
UnregisterHotKey((IntPtr)Handle, 1);
//#endif
}
}
}
protected override void WndProc(ref Message m)
{
switch (m.Msg)
{
case WM_HOTKEY:
if (m.WParam.ToInt32() == 1) button5_MouseClick(null, null);
break;
//case WM_QUERYENDSESSION:
// requestExit = true;
// //this.Close();
// Application.Exit();
// break;
default: break;
}
base.WndProc(ref m);
2021-10-24 15:49:48 +00:00
}
public bool IsBusy
{
get => isBusy;
set
{
isBusy = value;
ThreadControl.SetValue(pictureBox1, (isBusy ? AppResource.loading_block : null));
2021-10-25 14:20:23 +00:00
ThreadControl.SetEnable(textBox1, !isBusy);
//ThreadControl.SetEnable(button2, !isBusy);
button2.LabelText = (isBusy? "&Cancel" : "&Search");
2021-10-25 14:20:23 +00:00
ThreadControl.SetEnable(button3, !isBusy);
ThreadControl.SetEnable(button4, !isBusy);
ThreadControl.SetEnable(memoBox1, !isBusy);
ThreadControl.SetEnable(button5, !isBusy);
//ThreadControl.SetEnable(button1, !isBusy);
2021-10-24 15:49:48 +00:00
}
}
public AppSession CurrentSession { get; set; } = new AppSession();
protected bool SearchDirecory_OnFound(string file, ulong searchCount, int searchQueue)
{
if (!string.IsNullOrWhiteSpace(file))
{
foundFiles.Add(file);
}
//ThreadControl.SetText(label2, foundFiles.Count.ToString());
ThreadControl.SetText(label2, foundFiles.Count.ToString("#,#", System.Globalization.CultureInfo.CurrentCulture) + Environment.NewLine + searchQueue.ToString("#,#", System.Globalization.CultureInfo.CurrentCulture));
return true;
}
2021-10-30 22:44:44 +00:00
/// <summary>
/// New
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void newToolStripMenuItem_Click(object sender, EventArgs e)
{
await Task.Run(() =>
{
if (this.IsBusy) return;
if (this.CurrentSession.ClosePrevOnNext) CloseCurrentProcess(currentProcess);
2021-10-30 23:40:58 +00:00
ClearSession();
2021-10-30 22:44:44 +00:00
});
}
/// <summary>
/// Open
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
2021-10-30 23:40:58 +00:00
private async void openToolStripMenuItem_Click(object sender, EventArgs e)
2021-10-30 22:44:44 +00:00
{
2021-10-30 23:40:58 +00:00
if (this.IsBusy) return;
2021-10-30 22:44:44 +00:00
2021-10-30 23:40:58 +00:00
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
await LoadSessionFile(openFileDialog2.FileName);
}
2021-10-30 22:44:44 +00:00
}
/// <summary>
/// Save as
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
2021-10-30 23:40:58 +00:00
private async void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
2021-10-30 22:44:44 +00:00
{
2021-10-30 23:40:58 +00:00
if (this.IsBusy) return;
2021-10-30 22:44:44 +00:00
2021-10-30 23:40:58 +00:00
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
await SaveSessionFile(saveFileDialog1.FileName);
}
2021-10-30 22:44:44 +00:00
}
/// <summary>
/// Close
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void exitToolStripMenuItem2_Click(object sender, EventArgs e)
{
this.Close();
}
2021-10-30 02:21:45 +00:00
/// <summary>
/// Options
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
2021-10-30 22:44:44 +00:00
if (this.IsBusy) return;
2021-10-30 02:21:45 +00:00
if (optionsForm == null) optionsForm = new OptionsForm(this.CurrentSession);
if (optionsForm.ShowDialog() == DialogResult.OK)
{
this.CurrentSession = optionsForm.Session;
InvalidateHotKey();
}
}
2021-10-30 22:44:44 +00:00
/// <summary>
/// Help
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void viewHelpToolStripMenuItem1_Click(object sender, EventArgs e)
{
try
{
System.Diagnostics.Process.Start(new ProcessStartInfo()
{
2021-10-31 03:23:25 +00:00
FileName = "https://www.hiimray.co.uk/software-random-file-runner",
2021-10-30 22:44:44 +00:00
UseShellExecute = true
});
}
catch
{
// do nothing
}
}
/// <summary>
/// About
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void aboutToolStripMenuItem1_Click(object sender, EventArgs e)
{
MessageBox.Show(Application.ProductName + " v" + Application.ProductVersion, "About", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
2021-10-30 02:21:45 +00:00
2021-10-24 15:49:48 +00:00
/// <summary>
/// Search
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private async void button2_MouseClick(object sender, MouseEventArgs e)
2021-10-24 15:49:48 +00:00
{
await Task.Run(() =>
{
if (this.IsBusy)
{
requestCancel = true;
button2.LabelText = "&Cancelling...";
return;
}
this.IsBusy = true;
requestCancel = false;
foundFiles = new List<string>();
currentProcess = null;
2021-10-24 15:49:48 +00:00
2021-10-30 22:44:44 +00:00
if (!string.IsNullOrWhiteSpace(memoBox1.Text))
{
2021-10-30 22:44:44 +00:00
string[] itemList = memoBox1.Text?.Trim().Split('\n');
for (int i = 0; i < itemList.Length; i++)
{
if (string.IsNullOrWhiteSpace(itemList[i])) continue;
if (requestCancel) break;
2021-10-30 22:44:44 +00:00
string item = itemList[i]?.Trim();
2021-10-30 22:44:44 +00:00
if (File.Exists(item))
{
2021-10-30 22:44:44 +00:00
if (SmartDirectory.IsFileAccessible(item))
{
foundFiles.Add(item);
ThreadControl.SetText(label2, foundFiles.Count.ToString());
2021-10-30 22:44:44 +00:00
continue;
}
}
2021-10-30 22:44:44 +00:00
if (Directory.Exists(item))
{
SmartDirectory.GetFiles(item, textBox1.Text, this.CurrentSession.SearchTopDirectoryOnly, SearchDirecory_OnFound);
2021-10-30 22:44:44 +00:00
ThreadControl.SetText(label2, foundFiles.Count.ToString());
2021-10-30 22:44:44 +00:00
continue;
}
}
}
2021-10-30 22:44:44 +00:00
ThreadControl.SetText(label2, ((foundFiles.Count <= 0) ? "0" :foundFiles.Count.ToString("#,#", System.Globalization.CultureInfo.CurrentCulture)) + " File" + ((foundFiles.Count == 1) ? "" : "s") + " Found");
this.IsBusy = false;
requestCancel = false;
});
2021-10-24 15:49:48 +00:00
}
/// <summary>
/// Add directory
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void addDirectoryToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.IsBusy) return;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
AddSearchItem(folderBrowserDialog1.SelectedPath);
}
}
/// <summary>
/// Add file
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void addFileToolStripMenuItem_Click(object sender, EventArgs e)
{
if (this.IsBusy) return;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
AddSearchItem(openFileDialog1.FileName);
}
}
/// <summary>
/// Clear
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button4_MouseClick(object sender, MouseEventArgs e)
{
if (this.IsBusy) return;
memoBox1.Text = string.Empty;
}
2021-10-24 16:16:37 +00:00
private void memoBox1_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
if (this.IsBusy)
{
e.Effect = DragDropEffects.None;
}
else
{
e.Effect = DragDropEffects.Copy;
}
}
else
{
e.Effect = DragDropEffects.None;
}
}
2021-10-24 15:49:48 +00:00
2021-10-24 16:16:37 +00:00
private void memoBox1_DragDrop(object sender, DragEventArgs e)
{
if (this.IsBusy) return;
2021-10-24 15:49:48 +00:00
2021-10-24 16:16:37 +00:00
string[] fileList = e.Data.GetData(DataFormats.FileDrop) as string[];
if (fileList == null)
{
return;
}
foreach (string item in fileList)
{
AddSearchItem(item);
}
}
/// <summary>
/// Run next
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
2021-10-30 02:21:45 +00:00
private async void button5_MouseClick(object sender, MouseEventArgs e)
2021-10-24 16:16:37 +00:00
{
2021-10-30 02:21:45 +00:00
await Task.Run(() =>
{
if (this.IsBusy) return;
2021-10-24 16:16:37 +00:00
2021-10-30 02:21:45 +00:00
//this.IsBusy = true;
if (this.CurrentSession == null) this.CurrentSession = new AppSession();
if (this.CurrentSession.ClosePrevOnNext) CloseCurrentProcess(currentProcess);
string filename = null;
// retry 8 times
for (int i = 0; i < this.CurrentSession.RetryOnError; i++)
{
filename = foundFiles[randy.Next(0, (foundFiles.Count - 1))];
if (File.Exists(filename))
{
continue;
}
filename = null;
}
if (!string.IsNullOrWhiteSpace(filename))
{
ProcessStartInfo psi = new ProcessStartInfo(filename);
psi.UseShellExecute = true;
try
{
currentProcess = Process.Start(psi);
}
catch (Exception)
{
// do nothing
}
}
//this.IsBusy = false;
});
2021-10-24 16:16:37 +00:00
}
/// <summary>
/// Close
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
2021-10-24 16:16:37 +00:00
private void button1_MouseClick(object sender, MouseEventArgs e)
{
this.Close();
}
2021-10-24 15:49:48 +00:00
2021-10-30 02:21:45 +00:00
protected void AddSearchItem(string line)
{
memoBox1.Text = memoBox1.Text.Trim();
// above line-break
if (!string.IsNullOrWhiteSpace(memoBox1.Text)) memoBox1.Text += Environment.NewLine;
memoBox1.Text += line + Environment.NewLine;
}
private void CloseCurrentProcess(Process p)
{
if (p == null) return;
try
{
p.CloseMainWindow();
//p.Close();
}
catch (Exception)
{
// do nothing
}
}
private void InvalidateHotKey()
{
//#if !DEBUG
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(() =>
{
UnregisterHotKey((IntPtr)Handle, 1);
}));
}
else
{
UnregisterHotKey((IntPtr)Handle, 1);
}
//#endif
if (this.CurrentSession.NextHotKey != null)
{
if (this.CurrentSession.NextHotKey.KeyCode != Keys.None)
{
//#if !DEBUG
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(() =>
{
RegisterHotKey((IntPtr)Handle, 1, this.CurrentSession.NextHotKey.ModifierCode, this.CurrentSession.NextHotKey.Key);
}));
}
else
{
RegisterHotKey((IntPtr)Handle, 1, this.CurrentSession.NextHotKey.ModifierCode, this.CurrentSession.NextHotKey.Key);
}
//#endif
}
}
}
2021-10-30 23:40:58 +00:00
private void ClearSession()
{
foundFiles = new List<string>();
currentProcess = null;
textBox1.Text = "*.*";
ThreadControl.SetText(label2, "0");
memoBox1.Text = string.Empty;
}
protected async Task LoadSessionFile(string filename)
{
await Task.Run(() =>
{
if (string.IsNullOrWhiteSpace(filename)) return;
if (!File.Exists(filename)) return;
string sourceCode = null;
try
{
sourceCode = File.ReadAllText(filename);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Load session");
return;
}
if (string.IsNullOrWhiteSpace(sourceCode))
{
return;
}
// load options
var options = new JsonSerializerOptions();
//options.Converters.Add(new JsonPointConverter());
//options.Converters.Add(new JsonSizeConverter());
try
{
this.CurrentSession = JsonSerializer.Deserialize<AppSession>(sourceCode, options);
}
catch (Exception exc)
{
MessageBox.Show("Unable to read session", "Load session");
return;
}
if (this.CurrentSession == null) this.CurrentSession = new AppSession();
ClearSession();
textBox1.Text = (string.IsNullOrWhiteSpace(this.CurrentSession.SearchFilePattern) ? "*" : this.CurrentSession.SearchFilePattern?.Trim());
if (this.CurrentSession.SearchItems != null)
{
foreach (string item in this.CurrentSession.SearchItems)
{
AddSearchItem(item);
}
}
// hotkey
InvalidateHotKey();
});
}
2021-10-31 03:23:25 +00:00
protected string ParseOpenFile_FromCMD(string[] args)
{
if (args.Length <= 1)
{
return null;
}
int i = 1;
while (true)
{
if (i > (args.Length - 1))
{
break;
}
switch (args[i].Trim().ToLower())
{
case "-o":
case "-open":
if ((i + 1) > (args.Length - 1)) break;
string openFilename = args[(i + 1)];
if (string.IsNullOrWhiteSpace(openFilename)) break;
if (!File.Exists(openFilename)) break;
return openFilename;
i++;
break;
}
i++;
}
return null;
}
2021-10-30 23:40:58 +00:00
protected async Task SaveSessionFile(string filename)
{
await Task.Run(() =>
{
if (string.IsNullOrWhiteSpace(filename)) return;
if (this.CurrentSession == null) this.CurrentSession = new AppSession();
this.CurrentSession.SearchFilePattern = textBox1.Text;
this.CurrentSession.SearchItems = new List<string>();
if (!string.IsNullOrWhiteSpace(memoBox1.Text))
{
foreach (string item in memoBox1.Text?.Trim().Split('\n'))
{
if (string.IsNullOrWhiteSpace(item))
{
continue;
}
this.CurrentSession.SearchItems.Add(item?.Trim());
}
}
string sourceCode = null;
try
{
sourceCode = JsonSerializer.Serialize(this.CurrentSession);
}
catch (Exception)
{
MessageBox.Show("Unable to write session", "Save session");
return;
}
try
{
File.WriteAllText(filename, sourceCode);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Save session");
return;
}
});
}
2021-10-30 02:21:45 +00:00
2021-10-24 15:49:48 +00:00
}
}