Random stuff

This commit is contained in:
CreepyCrafter24 2020-03-24 22:43:48 +01:00
parent 4b7980d138
commit 18c8419495
20 changed files with 342 additions and 196 deletions

View File

@ -28,18 +28,18 @@
/// </summary> /// </summary>
private void InitializeComponent() private void InitializeComponent()
{ {
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(InstallerForm)); System.ComponentModel.ComponentResourceManager resources =
new System.ComponentModel.ComponentResourceManager(typeof(Installer.InstallerForm));
this.install = new System.Windows.Forms.Button(); this.install = new System.Windows.Forms.Button();
this.installLabel = new System.Windows.Forms.Label(); this.installLabel = new System.Windows.Forms.Label();
this.progress = new System.Windows.Forms.ProgressBar(); this.progress = new System.Windows.Forms.ProgressBar();
this.processLabel = new System.Windows.Forms.Label(); this.processLabel = new System.Windows.Forms.Label();
this.log = new System.Windows.Forms.Button(); this.log = new System.Windows.Forms.Button();
this.SuspendLayout(); this.SuspendLayout();
// this.install.Anchor =
// install ((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Bottom |
// System.Windows.Forms.AnchorStyles.Left) |
this.install.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) System.Windows.Forms.AnchorStyles.Right)));
| System.Windows.Forms.AnchorStyles.Right)));
this.install.Location = new System.Drawing.Point(12, 92); this.install.Location = new System.Drawing.Point(12, 92);
this.install.Name = "install"; this.install.Name = "install";
this.install.Size = new System.Drawing.Size(539, 27); this.install.Size = new System.Drawing.Size(539, 27);
@ -47,39 +47,31 @@
this.install.Text = "Install"; this.install.Text = "Install";
this.install.UseVisualStyleBackColor = true; this.install.UseVisualStyleBackColor = true;
this.install.Click += new System.EventHandler(this.install_Click); this.install.Click += new System.EventHandler(this.install_Click);
//
// installLabel
//
this.installLabel.AutoSize = true; this.installLabel.AutoSize = true;
this.installLabel.Location = new System.Drawing.Point(12, 9); this.installLabel.Location = new System.Drawing.Point(12, 9);
this.installLabel.Name = "installLabel"; this.installLabel.Name = "installLabel";
this.installLabel.Size = new System.Drawing.Size(550, 75); this.installLabel.Size = new System.Drawing.Size(550, 75);
this.installLabel.TabIndex = 1; this.installLabel.TabIndex = 1;
this.installLabel.Text = resources.GetString("installLabel.Text"); this.installLabel.Text = resources.GetString("installLabel.Text");
// this.progress.Anchor =
// progress ((System.Windows.Forms.AnchorStyles) (((System.Windows.Forms.AnchorStyles.Bottom |
// System.Windows.Forms.AnchorStyles.Left) |
this.progress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) System.Windows.Forms.AnchorStyles.Right)));
| System.Windows.Forms.AnchorStyles.Right)));
this.progress.Location = new System.Drawing.Point(12, 92); this.progress.Location = new System.Drawing.Point(12, 92);
this.progress.Maximum = 6; this.progress.Maximum = 6;
this.progress.Name = "progress"; this.progress.Name = "progress";
this.progress.Size = new System.Drawing.Size(539, 27); this.progress.Size = new System.Drawing.Size(539, 27);
this.progress.TabIndex = 2; this.progress.TabIndex = 2;
this.progress.Visible = false; this.progress.Visible = false;
//
// processLabel
//
this.processLabel.ForeColor = System.Drawing.SystemColors.ControlText; this.processLabel.ForeColor = System.Drawing.SystemColors.ControlText;
this.processLabel.Location = new System.Drawing.Point(422, 70); this.processLabel.Location = new System.Drawing.Point(422, 70);
this.processLabel.Name = "processLabel"; this.processLabel.Name = "processLabel";
this.processLabel.Size = new System.Drawing.Size(129, 19); this.processLabel.Size = new System.Drawing.Size(129, 19);
this.processLabel.TabIndex = 3; this.processLabel.TabIndex = 3;
this.processLabel.TextAlign = System.Drawing.ContentAlignment.TopRight; this.processLabel.TextAlign = System.Drawing.ContentAlignment.TopRight;
// this.log.Anchor =
// log ((System.Windows.Forms.AnchorStyles) ((System.Windows.Forms.AnchorStyles.Top |
// System.Windows.Forms.AnchorStyles.Right)));
this.log.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.log.Location = new System.Drawing.Point(524, 3); this.log.Location = new System.Drawing.Point(524, 3);
this.log.Name = "log"; this.log.Name = "log";
this.log.Size = new System.Drawing.Size(36, 23); this.log.Size = new System.Drawing.Size(36, 23);
@ -88,9 +80,6 @@
this.log.UseVisualStyleBackColor = true; this.log.UseVisualStyleBackColor = true;
this.log.Visible = false; this.log.Visible = false;
this.log.Click += new System.EventHandler(this.log_Click); this.log.Click += new System.EventHandler(this.log_Click);
//
// InstallerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(563, 132); this.ClientSize = new System.Drawing.Size(563, 132);
@ -100,13 +89,12 @@
this.Controls.Add(this.installLabel); this.Controls.Add(this.installLabel);
this.Controls.Add(this.install); this.Controls.Add(this.install);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Icon = ((System.Drawing.Icon) (resources.GetObject("$this.Icon")));
this.Name = "InstallerForm"; this.Name = "InstallerForm";
this.ShowIcon = false; this.ShowIcon = false;
this.Text = "UpTool2 Installer"; this.Text = "UpTool2 Installer";
this.ResumeLayout(false); this.ResumeLayout(false);
this.PerformLayout(); this.PerformLayout();
} }
#endregion #endregion

View File

@ -3,6 +3,7 @@ using System.Drawing;
using System.Globalization; using System.Globalization;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Linq;
using System.Net; using System.Net;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Threading; using System.Threading;
@ -54,7 +55,10 @@ namespace Installer
Step(5, "Creating shortcut"); Step(5, "Creating shortcut");
Shortcut.Make(PathTool.GetRelative("Install", "UpTool2.exe"), Shortcut.Make(PathTool.GetRelative("Install", "UpTool2.exe"),
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "UpTool2.lnk")); Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "UpTool2.lnk"));
Step(6, "Done!"); Step(6, "Creating PATH entry");
if (!PATH.Content.Contains(PATH.GetName(PathTool.GetRelative("Install"))))
PATH.Append(PathTool.GetRelative("Install"));
Step(7, "Done!");
} }
catch (Exception ex) catch (Exception ex)
{ {

View File

@ -61,7 +61,7 @@
<value>Thank you for downloading UpTool2. <value>Thank you for downloading UpTool2.
To prevent inconsistent behavior you will need to install this before running. To prevent inconsistent behavior you will need to install this before running.
Files will be placed in %appdata%\UpTool2 and %appdata%\Microsoft\Windows\Start Menu\Programs Files will be placed in %appdata%\UpTool2 and %appdata%\Microsoft\Windows\Start Menu\Programs
There will also be a new PATH Entry for your user.
Do you want to continue?</value> Do you want to continue?</value>
</data> </data>
<assembly alias="System.Drawing.Common" name="System.Drawing.Common, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" /> <assembly alias="System.Drawing.Common" name="System.Drawing.Common, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51" />

43
Installer/Lock.cs Normal file
View File

@ -0,0 +1,43 @@
using System;
using System.Threading;
namespace Installer
{
public static class MutexLock
{
private static Mutex _mutex;
private static bool _hasHandle;
public static void Lock()
{
_mutex = new Mutex(false,
"Global\\{c0c1e002-9e13-4e8f-a035-dbdc5128e00e}",
out bool _);
_hasHandle = false;
try
{
_hasHandle = _mutex.WaitOne(5000, false);
if (_hasHandle)
return;
throw new MutexLockLockedException();
}
catch (AbandonedMutexException)
{
#if DEBUG
Debug.WriteLine("Mutex abandoned");
#endif
_hasHandle = true;
}
}
public static void Unlock()
{
if (_hasHandle)
_mutex.ReleaseMutex();
}
}
public class MutexLockLockedException : Exception
{
}
}

20
Installer/PATH.cs Normal file
View File

@ -0,0 +1,20 @@
using System;
using System.IO;
using System.Linq;
namespace Installer
{
public static class PATH
{
public static string[] Content
{
get => Environment.GetEnvironmentVariable("path", EnvironmentVariableTarget.User).Split(';');
set => Environment.SetEnvironmentVariable("path", string.Join(';', value), EnvironmentVariableTarget.User);
}
public static void Append(string path, bool escape = true) =>
Content = Content.Append(escape ? GetName(path) : path).ToArray();
public static string GetName(string path) => Path.GetFullPath(path);
}
}

View File

@ -11,10 +11,18 @@ namespace Installer
[STAThread] [STAThread]
private static void Main() private static void Main()
{ {
Application.SetHighDpiMode(HighDpiMode.SystemAware); MutexLock.Lock();
Application.EnableVisualStyles(); try
Application.SetCompatibleTextRenderingDefault(false); {
Application.Run(new InstallerForm()); Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new InstallerForm());
}
finally
{
MutexLock.Unlock();
}
} }
} }
} }

View File

@ -18,8 +18,10 @@ namespace UpTool_build_tool
build.AddOption(new Option<string>("--binDir", "Directory to package")); build.AddOption(new Option<string>("--binDir", "Directory to package"));
build.AddOption(new Option<string>("--mainBin", "The applications main binary")); build.AddOption(new Option<string>("--mainBin", "The applications main binary"));
build.AddOption(new Option<string>("--packageFile", "Directory to package")); build.AddOption(new Option<string>("--packageFile", "Directory to package"));
build.AddOption(new Option<string>("--postInstall", () => "", "Command(s) to run after installing the package")); build.AddOption(new Option<string>("--postInstall", () => "",
build.AddOption(new Option<string>("--postRemove", () => "", "Command(s) to run after removing the package")); "Command(s) to run after installing the package"));
build.AddOption(
new Option<string>("--postRemove", () => "", "Command(s) to run after removing the package"));
build.AddOption(new Option<bool>("--noLogo", "Disables the logo")); build.AddOption(new Option<bool>("--noLogo", "Disables the logo"));
build.AddOption(new Option<bool>("--noShortcuts", build.AddOption(new Option<bool>("--noShortcuts",
"When this is enabled the scripts will not generate a start-menu item")); "When this is enabled the scripts will not generate a start-menu item"));
@ -28,7 +30,8 @@ namespace UpTool_build_tool
return rootCommand.InvokeAsync(args).Result; return rootCommand.InvokeAsync(args).Result;
} }
private static void Build(string binDir, string mainBin, string packageFile, string postInstall, string postRemove, bool noLogo, bool noShortcuts) private static void Build(string binDir, string mainBin, string packageFile, string postInstall,
string postRemove, bool noLogo, bool noShortcuts)
{ {
Stopwatch watch = Stopwatch.StartNew(); Stopwatch watch = Stopwatch.StartNew();
if (!noLogo) if (!noLogo)

View File

@ -1,13 +1,13 @@
using System; using System;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Linq;
using System.Reflection; using System.Reflection;
using System.Windows.Forms; using System.Windows.Forms;
using UpTool2.Properties; using UpTool2.Properties;
using UpToolLib; using UpToolLib;
using UpToolLib.DataStructures; using UpToolLib.DataStructures;
using UpToolLib.Tool; using UpToolLib.Tool;
using System.Linq;
#if DEBUG #if DEBUG
using System.Threading; using System.Threading;
@ -19,6 +19,7 @@ namespace UpTool2
public sealed partial class MainForm : Form public sealed partial class MainForm : Form
{ {
private readonly HelpEventHandler _help; private readonly HelpEventHandler _help;
public MainForm() public MainForm()
{ {
InitializeComponent(); InitializeComponent();
@ -145,7 +146,8 @@ namespace UpTool2
action_update.Tag = app; action_update.Tag = app;
action_update.Enabled = updateable; action_update.Enabled = updateable;
action_run.Tag = app; action_run.Tag = app;
action_run.Enabled = (app.status & Status.Installed) == Status.Installed && !app.Local && app.Runnable && Directory.Exists(app.appPath); action_run.Enabled = (app.status & Status.Installed) == Status.Installed && !app.Local &&
app.Runnable && Directory.Exists(app.appPath);
}; };
if (updateable) if (updateable)
availableUpdates++; availableUpdates++;
@ -220,15 +222,16 @@ namespace UpTool2
else else
{ {
#endif #endif
App[] apps = AppExtras.FindApps(searchBox.Text); App[] apps = AppExtras.FindApps(searchBox.Text);
Enum.TryParse(filterBox.SelectedValue.ToString(), out Status status); Enum.TryParse(filterBox.SelectedValue.ToString(), out Status status);
for (int i = 0; i < sidebarPanel.Controls.Count; i++) for (int i = 0; i < sidebarPanel.Controls.Count; i++)
{ {
Panel sidebarIcon = (Panel) sidebarPanel.Controls[i]; Panel sidebarIcon = (Panel) sidebarPanel.Controls[i];
App app = (App) sidebarIcon.Tag; App app = (App) sidebarIcon.Tag;
sidebarIcon.Visible = apps.Contains(app) && ((int) app.status & (int) (Program.Online ? status : Status.Installed)) != 0; sidebarIcon.Visible = apps.Contains(app) &&
} ((int) app.status & (int) (Program.Online ? status : Status.Installed)) != 0;
ClearSelection(); }
ClearSelection();
#if DEBUG #if DEBUG
} }
#endif #endif
@ -242,7 +245,7 @@ namespace UpTool2
} }
else else
{ {
Program.Splash.Invoke((Action)Program.Splash.Hide); Program.Splash.Invoke((Action) Program.Splash.Hide);
BringToFront(); BringToFront();
} }
} }
@ -262,10 +265,7 @@ namespace UpTool2
} }
finally finally
{ {
if (stream != null) if (stream != null) stream.Close();
{
stream.Close();
}
} }
int i = BitConverter.ToInt32(buffer, headerOffset); int i = BitConverter.ToInt32(buffer, headerOffset);

View File

@ -4,16 +4,15 @@ using System.Drawing;
using System.IO; using System.IO;
using System.IO.Compression; using System.IO.Compression;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography; using System.Security.Cryptography;
using System.Threading; using System.Threading;
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml; using System.Xml;
using System.Xml.Linq; using System.Xml.Linq;
using UpTool2.Tool;
using UpToolLib.Tool;
using CC_Functions.Misc; using CC_Functions.Misc;
using UpTool2.Tool;
using UpToolLib; using UpToolLib;
using UpToolLib.Tool;
namespace UpTool2 namespace UpTool2
{ {
@ -31,33 +30,22 @@ namespace UpTool2
Application.SetCompatibleTextRenderingDefault(false); Application.SetCompatibleTextRenderingDefault(false);
BuildSplash(); BuildSplash();
new Thread(() => { Splash.ShowDialog(); }).Start(); new Thread(() => { Splash.ShowDialog(); }).Start();
using Mutex mutex = new Mutex(false, try
$"Global\\{{{((GuidAttribute) Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value}}}", {
out bool _); MutexLock.Lock();
bool hasHandle = false; }
catch (MutexLockLockedException)
{
Console.WriteLine("Mutex property of other process, quitting");
Process[] processes = Process.GetProcessesByName("UpTool2");
if (processes.Length > 0)
WindowHelper.BringProcessToFront(Process.GetProcessesByName("UpTool2")[0]);
return;
}
#if !DEBUG #if !DEBUG
try try
{ {
#endif #endif
try
{
hasHandle = mutex.WaitOne(5000, false);
if (hasHandle == false)
{
Console.WriteLine("Mutex property of other process, quitting");
Process[] processes = Process.GetProcessesByName("UpTool2");
if (processes.Length > 0)
WindowHelper.BringProcessToFront(Process.GetProcessesByName("UpTool2")[0]);
Environment.Exit(0);
}
}
catch (AbandonedMutexException)
{
#if DEBUG
Debug.WriteLine("Mutex abandoned");
#endif
hasHandle = true;
}
ExternalFunctionalityManager.Init(new UTLibFunctions()); ExternalFunctionalityManager.Init(new UTLibFunctions());
SetSplash(1, "Initializing paths"); SetSplash(1, "Initializing paths");
if (!Directory.Exists(PathTool.dir)) if (!Directory.Exists(PathTool.dir))
@ -67,7 +55,9 @@ namespace UpTool2
string metaXml = XDocument.Load(PathTool.InfoXml).Element("meta").Element("UpdateSource").Value; string metaXml = XDocument.Load(PathTool.InfoXml).Element("meta").Element("UpdateSource").Value;
Online = new Uri(metaXml).Ping(); Online = new Uri(metaXml).Ping();
if (Application.ExecutablePath != PathTool.GetRelative("Install", "UpTool2.dll")) if (Application.ExecutablePath != PathTool.GetRelative("Install", "UpTool2.dll"))
Splash.Invoke((Action)(() => MessageBox.Show(Splash, $"WARNING!{Environment.NewLine}Running from outside the install directory is not recommended!"))); Splash.Invoke((Action) (() => MessageBox.Show(Splash,
$"WARNING!{Environment.NewLine}Running from outside the install directory is not recommended!")
));
if (!Directory.Exists(PathTool.GetRelative("Apps"))) if (!Directory.Exists(PathTool.GetRelative("Apps")))
Directory.CreateDirectory(PathTool.GetRelative("Apps")); Directory.CreateDirectory(PathTool.GetRelative("Apps"));
if (!Online) if (!Online)
@ -80,7 +70,7 @@ namespace UpTool2
{ {
try try
{ {
Splash.Invoke((Action)Splash.Hide); Splash.Invoke((Action) Splash.Hide);
} }
catch catch
{ {
@ -90,8 +80,7 @@ namespace UpTool2
} }
finally finally
{ {
if (hasHandle) MutexLock.Unlock();
mutex.ReleaseMutex();
} }
#endif #endif
} }
@ -116,36 +105,40 @@ namespace UpTool2
{ {
Graphics g = e.Graphics; Graphics g = e.Graphics;
//Draw background //Draw background
Brush[] brushes = {Brushes.Purple, Brushes.MediumPurple, Brushes.Indigo, Brushes.Fuchsia, Brushes.OrangeRed}; Brush[] brushes =
{Brushes.Purple, Brushes.MediumPurple, Brushes.Indigo, Brushes.Fuchsia, Brushes.OrangeRed};
const int barWidth = 50; const int barWidth = 50;
const int topOffset = 100; const int topOffset = 100;
for (int i = 0; i < Splash.Width + topOffset; i += barWidth) for (int i = 0; i < Splash.Width + topOffset; i += barWidth)
{ g.FillPolygon(brushes[(i / barWidth) % brushes.Length], new[]
g.FillPolygon(brushes[(i / barWidth) % brushes.Length], new []
{ {
new PointF(i, 0), new PointF(i, 0),
new PointF(i + barWidth, 0), new PointF(i + barWidth, 0),
new PointF(i, Splash.Height), new PointF(i, Splash.Height),
new PointF(i - topOffset, Splash.Height) new PointF(i - topOffset, Splash.Height)
}); });
}
//Draw Text: UpTool2 (by JFronny)^ //Draw Text: UpTool2 (by JFronny)^
Font font = new Font(FontFamily.GenericSansSerif, 40, FontStyle.Bold); Font font = new Font(FontFamily.GenericSansSerif, 40, FontStyle.Bold);
const string text = "UpTool2"; const string text = "UpTool2";
SizeF size = g.MeasureString(text, font); SizeF size = g.MeasureString(text, font);
RectangleF rect = new RectangleF((Splash.Width / 2f) - (size.Width / 2), (Splash.Height / 2f) - (size.Height / 2), size.Width, size.Height); RectangleF rect = new RectangleF((Splash.Width / 2f) - (size.Width / 2),
(Splash.Height / 2f) - (size.Height / 2), size.Width, size.Height);
g.DrawString(text, font, Brushes.White, rect); g.DrawString(text, font, Brushes.White, rect);
Font smallFont = new Font(FontFamily.GenericSansSerif, 10); Font smallFont = new Font(FontFamily.GenericSansSerif, 10);
const string subtitle = "by JFronny"; const string subtitle = "by JFronny";
SizeF size2 = g.MeasureString(subtitle, smallFont); SizeF size2 = g.MeasureString(subtitle, smallFont);
g.DrawString(subtitle, smallFont, Brushes.White, new RectangleF(rect.Right - size2.Width, rect.Bottom - size2.Height, size2.Width, size2.Height)); g.DrawString(subtitle, smallFont, Brushes.White,
new RectangleF(rect.Right - size2.Width, rect.Bottom - size2.Height, size2.Width, size2.Height));
//Draw progress bar //Draw progress bar
Rectangle bar = new Rectangle((3 * Splash.Width) / 8, ((Splash.Height * 3) / 4) - 10, Splash.Width / 4, 20); Rectangle bar = new Rectangle((3 * Splash.Width) / 8, ((Splash.Height * 3) / 4) - 10, Splash.Width / 4,
20);
g.FillRectangle(Brushes.Gray, bar); g.FillRectangle(Brushes.Gray, bar);
g.FillRectangle(Brushes.Black, new Rectangle(bar.X, bar.Y, (bar.Width * SplashProgress) / 10, bar.Height)); g.FillRectangle(Brushes.Black,
new Rectangle(bar.X, bar.Y, (bar.Width * SplashProgress) / 10, bar.Height));
g.DrawRectangle(Pens.DimGray, bar); g.DrawRectangle(Pens.DimGray, bar);
//g.DrawString(SplashMessage, smallFont, Brushes.White, new PointF(bar.Left, bar.Bottom)); //g.DrawString(SplashMessage, smallFont, Brushes.White, new PointF(bar.Left, bar.Bottom));
g.DrawString(SplashMessage, smallFont, Brushes.White, bar, new StringFormat {Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center}); g.DrawString(SplashMessage, smallFont, Brushes.White, bar,
new StringFormat {Alignment = StringAlignment.Near, LineAlignment = StringAlignment.Center});
}; };
int xOff = 0; int xOff = 0;
int yOff = 0; int yOff = 0;

View File

@ -1,6 +1,5 @@
using System.Windows.Forms; using System.Windows.Forms;
using System.Xml.Linq; using System.Xml.Linq;
using UpTool2.Tool;
using UpToolLib.Tool; using UpToolLib.Tool;
namespace UpTool2 namespace UpTool2

View File

@ -7,12 +7,11 @@ using System.Net;
using System.Windows.Forms; using System.Windows.Forms;
using UpTool2.Properties; using UpTool2.Properties;
using UpTool2.Tool; using UpTool2.Tool;
using UpToolLib;
using UpToolLib.DataStructures; using UpToolLib.DataStructures;
namespace UpTool2 namespace UpTool2
{ {
class UTLibFunctions : IExternalFunctionality internal class UTLibFunctions : IExternalFunctionality
{ {
public Tuple<bool, byte[]> Download(Uri link) public Tuple<bool, byte[]> Download(Uri link)
{ {
@ -45,11 +44,17 @@ namespace UpTool2
return Convert.ToBase64String(ms.ToArray()); return Convert.ToBase64String(ms.ToArray());
} }
public bool YesNoDialog(string text, bool _) => MessageBox.Show(text, "", MessageBoxButtons.YesNo) == DialogResult.Yes; public bool YesNoDialog(string text, bool _) =>
MessageBox.Show(text, "", MessageBoxButtons.YesNo) == DialogResult.Yes;
public void OKDialog(string text) => MessageBox.Show(text); public void OKDialog(string text) => MessageBox.Show(text);
public object GetDefaultIcon() => Resources.C_64.ToBitmap(); public object GetDefaultIcon() => Resources.C_64.ToBitmap();
public object ImageFromB64(string b64) => (Bitmap) new ImageConverter().ConvertFrom(Convert.FromBase64String(b64));
public void Log(string text) { } public object ImageFromB64(string b64) =>
(Bitmap) new ImageConverter().ConvertFrom(Convert.FromBase64String(b64));
public void Log(string text)
{
}
} }
} }

View File

@ -13,78 +13,84 @@ namespace UpToolCLI
{ {
public static int Main(string[] args) public static int Main(string[] args)
{ {
ExternalFunctionalityManager.Init(new UTLibFunctions()); MutexLock.Lock();
RootCommand rootCommand = new RootCommand(); try
rootCommand.AddCommand(new Command("update", "Updates the cache")
{ {
Handler = CommandHandler.Create(Update) ExternalFunctionalityManager.Init(new UTLibFunctions());
}); RootCommand rootCommand = new RootCommand();
rootCommand.AddCommand(new Command("update", "Updates the cache")
{
Handler = CommandHandler.Create(Update)
});
Command install = new Command("install", "Install a package") Command install = new Command("install", "Install a package")
{
Handler = CommandHandler.Create<string, bool>(Install)
};
install.AddOption(new Option<string>(new[] {"--identifier", "-i"}, "Something to identify the app"));
install.AddOption(new Option<bool>(new[] {"--force", "-f"}, "Overwrites older files"));
rootCommand.AddCommand(install);
Command upgrade = new Command("upgrade", "Upgrade a package")
{
Handler = CommandHandler.Create<string, bool>(Upgrade)
};
upgrade.AddOption(new Option<string>(new[] {"--identifier", "-i"}, "Something to identify the app"));
upgrade.AddOption(new Option<bool>(new[] {"--force", "-f"}, "Overwrites older files"));
rootCommand.AddCommand(upgrade);
Command reinstall = new Command("reinstall", "Reinstall a package")
{
Handler = CommandHandler.Create<string, bool>(Reinstall)
};
reinstall.AddOption(new Option<string>(new[] {"--identifier", "-i"}, "Something to identify the app"));
reinstall.AddOption(new Option<bool>(new[] {"--force", "-f"}, "Overwrites older files"));
rootCommand.AddCommand(reinstall);
Command remove = new Command("remove", "Remove a package")
{
Handler = CommandHandler.Create<string>(Remove)
};
remove.AddOption(new Option<string>(new[] {"--identifier", "-i"}, "Something to identify the app"));
rootCommand.AddCommand(remove);
Command purge = new Command("purge", "Completely remove a package")
{
Handler = CommandHandler.Create<string>(Purge)
};
purge.AddOption(new Option<string>(new[] {"--identifier", "-i"}, "Something to identify the app"));
rootCommand.AddCommand(purge);
rootCommand.AddCommand(new Command("list", "Lists installed packages")
{
Handler = CommandHandler.Create(List)
});
rootCommand.AddCommand(new Command("dist-upgrade", "Upgrades all packages")
{
Handler = CommandHandler.Create(DistUpgrade)
});
Command search = new Command("search", "Search for packages")
{
Handler = CommandHandler.Create<string>(Search)
};
search.AddOption(new Option<string>(new[] {"--identifier", "-i"}, "Something to identify the app"));
rootCommand.AddCommand(search);
Command show = new Command("show", "Shows package info")
{
Handler = CommandHandler.Create<string>(Show)
};
show.AddOption(new Option<string>(new[] {"--identifier", "-i"}, "Something to identify the app"));
rootCommand.AddCommand(show);
return rootCommand.InvokeAsync(args).Result;
}
finally
{ {
Handler = CommandHandler.Create<string, bool>(Install) MutexLock.Unlock();
}; }
install.AddOption(new Option<string>(new[] { "--identifier", "-i" }, "Something to identify the app"));
install.AddOption(new Option<bool>(new[] { "--force", "-f" }, "Overwrites older files"));
rootCommand.AddCommand(install);
Command upgrade = new Command("upgrade", "Upgrade a package")
{
Handler = CommandHandler.Create<string, bool>(Upgrade)
};
upgrade.AddOption(new Option<string>(new[] { "--identifier", "-i" }, "Something to identify the app"));
upgrade.AddOption(new Option<bool>(new[] { "--force", "-f" }, "Overwrites older files"));
rootCommand.AddCommand(upgrade);
Command reinstall = new Command("reinstall", "Reinstall a package")
{
Handler = CommandHandler.Create<string, bool>(Reinstall)
};
reinstall.AddOption(new Option<string>(new[] { "--identifier", "-i" }, "Something to identify the app"));
reinstall.AddOption(new Option<bool>(new[] { "--force", "-f" }, "Overwrites older files"));
rootCommand.AddCommand(reinstall);
Command remove = new Command("remove", "Remove a package")
{
Handler = CommandHandler.Create<string>(Remove)
};
remove.AddOption(new Option<string>(new[] { "--identifier", "-i" }, "Something to identify the app"));
rootCommand.AddCommand(remove);
Command purge = new Command("purge", "Completely remove a package")
{
Handler = CommandHandler.Create<string>(Purge)
};
purge.AddOption(new Option<string>(new[] { "--identifier", "-i" }, "Something to identify the app"));
rootCommand.AddCommand(purge);
rootCommand.AddCommand(new Command("list", "Lists installed packages")
{
Handler = CommandHandler.Create(List)
});
rootCommand.AddCommand(new Command("dist-upgrade", "Upgrades all packages")
{
Handler = CommandHandler.Create(DistUpgrade)
});
Command search = new Command("search", "Search for packages")
{
Handler = CommandHandler.Create<string>(Search)
};
search.AddOption(new Option<string>(new[] { "--identifier", "-i" }, "Something to identify the app"));
rootCommand.AddCommand(search);
Command show = new Command("show", "Shows package info")
{
Handler = CommandHandler.Create<string>(Show)
};
show.AddOption(new Option<string>(new[] { "--identifier", "-i" }, "Something to identify the app"));
rootCommand.AddCommand(show);
return rootCommand.InvokeAsync(args).Result;
} }
private static void Update() private static void Update()
@ -97,11 +103,14 @@ namespace UpToolCLI
private static void List() private static void List()
{ {
RepoManagement.GetReposFromDisk(); RepoManagement.GetReposFromDisk();
foreach (KeyValuePair<Guid, App> app in GlobalVariables.Apps.Where(s => (s.Value.status & Status.Installed) == Status.Installed)) foreach (KeyValuePair<Guid, App> app in GlobalVariables.Apps.Where(s =>
(s.Value.status & Status.Installed) == Status.Installed))
{ {
Console.BackgroundColor = (app.Value.status & Status.Local) == Status.Local ? ConsoleColor.DarkRed : ((app.Value.status & Status.Updatable) == Status.Updatable ? ConsoleColor.DarkGreen : ConsoleColor.Black); Console.BackgroundColor = (app.Value.status & Status.Local) == Status.Local ? ConsoleColor.DarkRed :
(app.Value.status & Status.Updatable) == Status.Updatable ? ConsoleColor.DarkGreen :
ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"{app.Value.Name} ({app.Key}"); Console.WriteLine($"{app.Value.Name} ({app.Key})");
} }
Console.ResetColor(); Console.ResetColor();
} }
@ -109,7 +118,8 @@ namespace UpToolCLI
private static void DistUpgrade() private static void DistUpgrade()
{ {
RepoManagement.GetReposFromDisk(); RepoManagement.GetReposFromDisk();
foreach (KeyValuePair<Guid, App> app in GlobalVariables.Apps.Where(s => (s.Value.status & Status.Updatable) == Status.Updatable)) foreach (KeyValuePair<Guid, App> app in GlobalVariables.Apps.Where(s =>
(s.Value.status & Status.Updatable) == Status.Updatable))
{ {
Console.WriteLine($"Updating {app.Value.Name}"); Console.WriteLine($"Updating {app.Value.Name}");
AppExtras.Update(app.Value, false); AppExtras.Update(app.Value, false);
@ -133,7 +143,7 @@ namespace UpToolCLI
App[] apps = AppExtras.FindApps(identifier); App[] apps = AppExtras.FindApps(identifier);
Console.WriteLine($"Found {apps.Length} app(s)"); Console.WriteLine($"Found {apps.Length} app(s)");
for (int i = 0; i < apps.Length; i++) for (int i = 0; i < apps.Length; i++)
Console.WriteLine($"{apps[i].Name} ({apps[i].Id}"); Console.WriteLine($"{apps[i].Name} ({apps[i].Id})");
} }
private static void Upgrade(string identifier, bool force) private static void Upgrade(string identifier, bool force)
@ -141,7 +151,9 @@ namespace UpToolCLI
RepoManagement.GetReposFromDisk(); RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier); App[] apps = AppExtras.FindApps(identifier);
if (apps.Length == 0) if (apps.Length == 0)
{
Console.WriteLine("Package not found."); Console.WriteLine("Package not found.");
}
else else
{ {
App tmp = apps.First(); App tmp = apps.First();
@ -151,7 +163,9 @@ namespace UpToolCLI
AppExtras.Update(tmp, force); AppExtras.Update(tmp, force);
} }
else else
{
Console.WriteLine("Package is up-to-date"); Console.WriteLine("Package is up-to-date");
}
} }
Console.WriteLine("Done!"); Console.WriteLine("Done!");
} }
@ -161,7 +175,9 @@ namespace UpToolCLI
RepoManagement.GetReposFromDisk(); RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier); App[] apps = AppExtras.FindApps(identifier);
if (apps.Length == 0) if (apps.Length == 0)
{
Console.WriteLine("Package not found."); Console.WriteLine("Package not found.");
}
else else
{ {
App tmp = apps.First(); App tmp = apps.First();
@ -176,7 +192,9 @@ namespace UpToolCLI
RepoManagement.GetReposFromDisk(); RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier); App[] apps = AppExtras.FindApps(identifier);
if (apps.Length == 0) if (apps.Length == 0)
{
Console.WriteLine("Package not found."); Console.WriteLine("Package not found.");
}
else else
{ {
App tmp = apps.First(); App tmp = apps.First();
@ -186,7 +204,9 @@ namespace UpToolCLI
AppExtras.Remove(tmp, false); AppExtras.Remove(tmp, false);
} }
else else
{
Console.WriteLine("Package is not installed"); Console.WriteLine("Package is not installed");
}
} }
Console.WriteLine("Done!"); Console.WriteLine("Done!");
} }
@ -196,7 +216,9 @@ namespace UpToolCLI
RepoManagement.GetReposFromDisk(); RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier); App[] apps = AppExtras.FindApps(identifier);
if (apps.Length == 0) if (apps.Length == 0)
{
Console.WriteLine("Package not found."); Console.WriteLine("Package not found.");
}
else else
{ {
App tmp = apps.First(); App tmp = apps.First();
@ -206,7 +228,9 @@ namespace UpToolCLI
AppExtras.Remove(tmp, true); AppExtras.Remove(tmp, true);
} }
else else
{
Console.WriteLine("Package is not installed"); Console.WriteLine("Package is not installed");
}
} }
Console.WriteLine("Done!"); Console.WriteLine("Done!");
} }
@ -216,12 +240,16 @@ namespace UpToolCLI
RepoManagement.GetReposFromDisk(); RepoManagement.GetReposFromDisk();
App[] apps = AppExtras.FindApps(identifier); App[] apps = AppExtras.FindApps(identifier);
if (apps.Length == 0) if (apps.Length == 0)
{
Console.WriteLine("Package not found."); Console.WriteLine("Package not found.");
}
else else
{ {
App tmp = apps.First(); App tmp = apps.First();
if ((tmp.status & Status.Installed) == Status.Installed) if ((tmp.status & Status.Installed) == Status.Installed)
{
Console.WriteLine("Package is already installed"); Console.WriteLine("Package is already installed");
}
else else
{ {
Console.WriteLine($"Installing {tmp.Name}"); Console.WriteLine($"Installing {tmp.Name}");

View File

@ -1,9 +1,9 @@
using SixLabors.ImageSharp; using System;
using SixLabors.ImageSharp.Processing;
using System;
using System.IO; using System.IO;
using System.Net; using System.Net;
using System.Threading; using System.Threading;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Processing;
using UpToolLib.DataStructures; using UpToolLib.DataStructures;
namespace UpToolCLI namespace UpToolCLI
@ -25,7 +25,8 @@ namespace UpToolCLI
}; };
client.DownloadProgressChanged += (sender, e) => client.DownloadProgressChanged += (sender, e) =>
{ {
Console.Write($"{new string('=', e.ProgressPercentage / 10)}[{e.ProgressPercentage}]{new string('-', 10 - e.ProgressPercentage / 10)}"); Console.Write(
$"{new string('=', e.ProgressPercentage / 10)}[{e.ProgressPercentage}]{new string('-', 10 - (e.ProgressPercentage / 10))}");
Console.CursorLeft = 0; Console.CursorLeft = 0;
}; };
client.DownloadDataAsync(link); client.DownloadDataAsync(link);

View File

@ -12,4 +12,4 @@ namespace UpToolLib.DataStructures
public object ImageFromB64(string b64); public object ImageFromB64(string b64);
public void Log(string text); public void Log(string text);
} }
} }

View File

@ -1,7 +1,4 @@
using System; using UpToolLib.DataStructures;
using System.Collections.Generic;
using System.Text;
using UpToolLib.DataStructures;
namespace UpToolLib namespace UpToolLib
{ {
@ -9,7 +6,9 @@ namespace UpToolLib
{ {
internal static IExternalFunctionality instance; internal static IExternalFunctionality instance;
public static void Init(IExternalFunctionality externalFunctionality) => public static void Init(IExternalFunctionality externalFunctionality)
{
instance = externalFunctionality; instance = externalFunctionality;
}
} }
} }

43
UpToolLib/Lock.cs Normal file
View File

@ -0,0 +1,43 @@
using System;
using System.Threading;
namespace UpToolLib
{
public static class MutexLock
{
private static Mutex _mutex;
private static bool _hasHandle;
public static void Lock()
{
_mutex = new Mutex(false,
"Global\\{c0c1e002-9e13-4e8f-a035-dbdc5128e00e}",
out bool _);
_hasHandle = false;
try
{
_hasHandle = _mutex.WaitOne(5000, false);
if (_hasHandle)
return;
throw new MutexLockLockedException();
}
catch (AbandonedMutexException)
{
#if DEBUG
Debug.WriteLine("Mutex abandoned");
#endif
_hasHandle = true;
}
}
public static void Unlock()
{
if (_hasHandle)
_mutex.ReleaseMutex();
}
}
public class MutexLockLockedException : Exception
{
}
}

View File

@ -48,7 +48,9 @@ namespace UpToolLib.Tool
File.Delete(app.infoPath); File.Delete(app.infoPath);
if (File.Exists(Path.Combine(app.appPath, "package.zip"))) if (File.Exists(Path.Combine(app.appPath, "package.zip")))
File.Delete(Path.Combine(app.appPath, "package.zip")); File.Delete(Path.Combine(app.appPath, "package.zip"));
if (deleteAll || (Directory.Exists(app.dataPath) && Directory.GetFiles(app.dataPath).Length + Directory.GetDirectories(app.dataPath).Length == 0)) if (deleteAll || (Directory.Exists(app.dataPath) &&
Directory.GetFiles(app.dataPath).Length + Directory.GetDirectories(app.dataPath).Length ==
0))
Directory.Delete(app.appPath, true); Directory.Delete(app.appPath, true);
} }

View File

@ -11,7 +11,7 @@ namespace UpToolLib.Tool
public static class AppInstall public static class AppInstall
{ {
/// <summary> /// <summary>
/// Install an application /// Install an application
/// </summary> /// </summary>
/// <param name="appI">The app to install</param> /// <param name="appI">The app to install</param>
/// <param name="force">Set to true to overwrite all old data</param> /// <param name="force">Set to true to overwrite all old data</param>
@ -102,14 +102,18 @@ Online: {appI.Hash.ToUpper()}");
//Use //Use
//PowerShell -Command "Add-Type -AssemblyName PresentationFramework;[System.Windows.MessageBox]::Show('Hello World')" //PowerShell -Command "Add-Type -AssemblyName PresentationFramework;[System.Windows.MessageBox]::Show('Hello World')"
//for message boxes //for message boxes
private static void CompleteInstall(App app, bool force) => CompleteInstall(app.appPath, app.Name, app.Description, app.Version, app.MainFile, force); private static void CompleteInstall(App app, bool force) => CompleteInstall(app.appPath, app.Name,
app.Description, app.Version, app.MainFile, force);
private static void CompleteInstall(string appPath, string name, string description, Version version, string mainFile, bool force) private static void CompleteInstall(string appPath, string name, string description, Version version,
string mainFile, bool force)
{ {
string tmp = PathTool.tempPath; string tmp = PathTool.tempPath;
ZipFile.ExtractToDirectory(Path.Combine(appPath, "package.zip"), tmp); ZipFile.ExtractToDirectory(Path.Combine(appPath, "package.zip"), tmp);
if (force) if (force)
{
Directory.Move(Path.Combine(tmp, "Data"), Path.Combine(appPath, "app")); Directory.Move(Path.Combine(tmp, "Data"), Path.Combine(appPath, "app"));
}
else else
{ {
CopyAll(Path.Combine(tmp, "Data"), Path.Combine(appPath, "app", "Data")); CopyAll(Path.Combine(tmp, "Data"), Path.Combine(appPath, "app", "Data"));
@ -129,14 +133,16 @@ Online: {appI.Hash.ToUpper()}");
WindowStyle = ProcessWindowStyle.Hidden WindowStyle = ProcessWindowStyle.Hidden
}).WaitForExit(); }).WaitForExit();
} }
private static void CopyAll(string source, string target) private static void CopyAll(string source, string target)
{ {
if (string.Equals(Path.GetFullPath(source), Path.GetFullPath(target), StringComparison.CurrentCultureIgnoreCase)) if (string.Equals(Path.GetFullPath(source), Path.GetFullPath(target),
StringComparison.CurrentCultureIgnoreCase))
return; return;
if (!Directory.Exists(target)) if (!Directory.Exists(target))
Directory.CreateDirectory(target); Directory.CreateDirectory(target);
foreach (string file in Directory.GetFiles(source)) File.Copy(file, Path.Combine(target, Path.GetFileName(file)), true); foreach (string file in Directory.GetFiles(source))
File.Copy(file, Path.Combine(target, Path.GetFileName(file)), true);
foreach (string dir in Directory.GetDirectories(source)) foreach (string dir in Directory.GetDirectories(source))
CopyAll(dir, Path.Combine(target, Path.GetFileName(dir))); CopyAll(dir, Path.Combine(target, Path.GetFileName(dir)));
} }

View File

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Net;
using System.Xml.Linq; using System.Xml.Linq;
using CC_Functions.Misc; using CC_Functions.Misc;
using UpToolLib.DataStructures; using UpToolLib.DataStructures;
@ -63,7 +62,9 @@ namespace UpToolLib.Tool
try try
{ {
tmpAppsList.Last() tmpAppsList.Last()
.Add(new XElement("Icon", ExternalFunctionalityManager.instance.FetchImageB64(new Uri(app.Element("Icon").Value).Unshorten()))); .Add(new XElement("Icon",
ExternalFunctionalityManager.instance.FetchImageB64(
new Uri(app.Element("Icon").Value).Unshorten())));
} }
catch catch
{ {
@ -78,7 +79,8 @@ namespace UpToolLib.Tool
} }
catch (Exception e) catch (Exception e)
{ {
ExternalFunctionalityManager.instance.OKDialog($"Failed to load repo: {repArr[i]}{Environment.NewLine}{e}"); ExternalFunctionalityManager.instance.OKDialog(
$"Failed to load repo: {repArr[i]}{Environment.NewLine}{e}");
} }
#endif #endif
i++; i++;
@ -97,7 +99,7 @@ namespace UpToolLib.Tool
int.TryParse(el.Value, out int i) ? new Version(0, 0, 0, i) : Version.Parse(el.Value); int.TryParse(el.Value, out int i) ? new Version(0, 0, 0, i) : Version.Parse(el.Value);
/// <summary> /// <summary>
/// Load the repository cache /// Load the repository cache
/// </summary> /// </summary>
/// <param name="errorHandler">Function to call on an exception, will ask the user whether he wants to quit</param> /// <param name="errorHandler">Function to call on an exception, will ask the user whether he wants to quit</param>
public static void GetReposFromDisk() public static void GetReposFromDisk()
@ -139,13 +141,15 @@ namespace UpToolLib.Tool
XElement data = XDocument.Load(PathTool.GetInfoPath(tmp)).Element("app"); XElement data = XDocument.Load(PathTool.GetInfoPath(tmp)).Element("app");
GlobalVariables.Apps.Add(tmp, GlobalVariables.Apps.Add(tmp,
new App("(local) " + data.Element("Name").Value, data.Element("Description").Value, new App("(local) " + data.Element("Name").Value, data.Element("Description").Value,
GlobalVariables.minimumVer, "", true, "", tmp, Color.Red, ExternalFunctionalityManager.instance.GetDefaultIcon(), GlobalVariables.minimumVer, "", true, "", tmp, Color.Red,
ExternalFunctionalityManager.instance.GetDefaultIcon(),
data.Element("MainFile") != null, data.Element("MainFile") != null,
data.Element("MainFile") == null ? "" : data.Element("MainFile").Value)); data.Element("MainFile") == null ? "" : data.Element("MainFile").Value));
} }
catch (Exception e) catch (Exception e)
{ {
if (ExternalFunctionalityManager.instance.YesNoDialog($@"An error occured while loading this local repo: if (ExternalFunctionalityManager.instance.YesNoDialog(
$@"An error occured while loading this local repo:
{e.Message} {e.Message}
Do you want to exit? Otherwise the folder will be deleted, possibly causeing problems later.", false)) Do you want to exit? Otherwise the folder will be deleted, possibly causeing problems later.", false))
Environment.Exit(0); Environment.Exit(0);

View File

@ -44,4 +44,4 @@ namespace UpToolLib.Tool
x.Save(PathTool.InfoXml); x.Save(PathTool.InfoXml);
} }
} }
} }