Code style - Use file scoped namespaces

Code style - Ran code cleanup
This commit is contained in:
Robert committed 2022-08-21 11:36:15 +02:00
1 parent e68e16df4d
commit f6090dc296
691 files changed
+37301 -38119

No files matched your search

+27 -28
View File
@@ -9,38 +9,37 @@ using Avalonia.Threading;
using Ninject;
using ReactiveUI;
namespace Artemis.UI.Windows
namespace Artemis.UI.Windows;
public class App : Application
{
public class App : Application
// ReSharper disable NotAccessedField.Local
private ApplicationStateManager? _applicationStateManager;
// ReSharper restore NotAccessedField.Local
private StandardKernel? _kernel;
public override void Initialize()
{
// ReSharper disable NotAccessedField.Local
private ApplicationStateManager? _applicationStateManager;
// ReSharper restore NotAccessedField.Local
_kernel = ArtemisBootstrapper.Bootstrap(this, new WindowsModule());
Program.CreateLogger(_kernel);
RxApp.MainThreadScheduler = AvaloniaScheduler.Instance;
AvaloniaXamlLoader.Load(this);
}
private StandardKernel? _kernel;
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop || Design.IsDesignMode)
return;
public override void Initialize()
{
_kernel = ArtemisBootstrapper.Bootstrap(this, new WindowsModule());
Program.CreateLogger(_kernel);
RxApp.MainThreadScheduler = AvaloniaScheduler.Instance;
AvaloniaXamlLoader.Load(this);
}
ArtemisBootstrapper.Initialize();
_applicationStateManager = new ApplicationStateManager(_kernel!, desktop.Args);
RegisterProviders(_kernel!);
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is not IClassicDesktopStyleApplicationLifetime desktop || Design.IsDesignMode)
return;
ArtemisBootstrapper.Initialize();
_applicationStateManager = new ApplicationStateManager(_kernel!, desktop.Args);
RegisterProviders(_kernel!);
}
private void RegisterProviders(StandardKernel standardKernel)
{
IInputService inputService = standardKernel.Get<IInputService>();
inputService.AddInputProvider(standardKernel.Get<WindowsInputProvider>());
}
private void RegisterProviders(StandardKernel standardKernel)
{
IInputService inputService = standardKernel.Get<IInputService>();
inputService.AddInputProvider(standardKernel.Get<WindowsInputProvider>());
}
}
+140 -143
View File
@@ -15,179 +15,176 @@ using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using Ninject;
namespace Artemis.UI.Windows
namespace Artemis.UI.Windows;
public class ApplicationStateManager
{
public class ApplicationStateManager
private readonly IWindowService _windowService;
// ReSharper disable once NotAccessedField.Local - Kept in scope to ensure it does not get released
private Mutex? _artemisMutex;
public ApplicationStateManager(IKernel kernel, string[] startupArguments)
{
private readonly IWindowService _windowService;
_windowService = kernel.Get<IWindowService>();
StartupArguments = startupArguments;
IsElevated = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
// ReSharper disable once NotAccessedField.Local - Kept in scope to ensure it does not get released
private Mutex? _artemisMutex;
Core.Utilities.ShutdownRequested += UtilitiesOnShutdownRequested;
Core.Utilities.RestartRequested += UtilitiesOnRestartRequested;
public ApplicationStateManager(IKernel kernel, string[] startupArguments)
{
_windowService = kernel.Get<IWindowService>();
StartupArguments = startupArguments;
IsElevated = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
Core.Utilities.ShutdownRequested += UtilitiesOnShutdownRequested;
Core.Utilities.RestartRequested += UtilitiesOnRestartRequested;
// On Windows shutdown dispose the kernel just so device providers get a chance to clean up
if (Application.Current?.ApplicationLifetime is IControlledApplicationLifetime controlledApplicationLifetime)
// On Windows shutdown dispose the kernel just so device providers get a chance to clean up
if (Application.Current?.ApplicationLifetime is IControlledApplicationLifetime controlledApplicationLifetime)
controlledApplicationLifetime.Exit += (_, _) =>
{
controlledApplicationLifetime.Exit += (_, _) =>
{
RunForcedShutdownIfEnabled();
RunForcedShutdownIfEnabled();
// Dispose plugins before disposing the kernel because plugins might access services during dispose
kernel.Get<IPluginManagementService>().Dispose();
kernel.Dispose();
};
}
// Dispose plugins before disposing the kernel because plugins might access services during dispose
kernel.Get<IPluginManagementService>().Dispose();
kernel.Dispose();
};
// Inform the Core about elevation status
kernel.Get<ICoreService>().IsElevated = IsElevated;
}
// Inform the Core about elevation status
kernel.Get<ICoreService>().IsElevated = IsElevated;
}
public string[] StartupArguments { get; }
public bool IsElevated { get; }
public string[] StartupArguments { get; }
public bool IsElevated { get; }
public bool FocusExistingInstance()
public bool FocusExistingInstance()
{
_artemisMutex = new Mutex(true, "Artemis-3c24b502-64e6-4587-84bf-9072970e535f", out bool createdNew);
if (createdNew)
return false;
return RemoteFocus();
}
public void DisplayException(Exception e)
{
try
{
_artemisMutex = new Mutex(true, "Artemis-3c24b502-64e6-4587-84bf-9072970e535f", out bool createdNew);
if (createdNew)
return false;
_windowService.ShowExceptionDialog("An unhandled exception occured", e);
}
catch
{
// ignored, we tried
}
}
return RemoteFocus();
private bool RemoteFocus()
{
// At this point we cannot read the database yet to retrieve the web server port.
// Instead use the method external applications should use as well.
if (!File.Exists(Path.Combine(Constants.DataFolder, "webserver.txt")))
{
KillOtherInstances();
return false;
}
public void DisplayException(Exception e)
string url = File.ReadAllText(Path.Combine(Constants.DataFolder, "webserver.txt"));
using HttpClient client = new();
try
{
CancellationTokenSource cts = new();
cts.CancelAfter(2000);
HttpResponseMessage httpResponseMessage = client.Send(new HttpRequestMessage(HttpMethod.Post, url + "remote/bring-to-foreground"), cts.Token);
httpResponseMessage.EnsureSuccessStatusCode();
return true;
}
catch (Exception)
{
KillOtherInstances();
return false;
}
}
private void KillOtherInstances()
{
// Kill everything else heh
List<Process> processes = Process.GetProcessesByName("Artemis.UI.Windows").Where(p => p.Id != Process.GetCurrentProcess().Id).ToList();
foreach (Process process in processes)
{
try
{
_windowService.ShowExceptionDialog("An unhandled exception occured", e);
}
catch
{
// ignored, we tried
}
}
private bool RemoteFocus()
{
// At this point we cannot read the database yet to retrieve the web server port.
// Instead use the method external applications should use as well.
if (!File.Exists(Path.Combine(Constants.DataFolder, "webserver.txt")))
{
KillOtherInstances();
return false;
}
string url = File.ReadAllText(Path.Combine(Constants.DataFolder, "webserver.txt"));
using HttpClient client = new();
try
{
CancellationTokenSource cts = new();
cts.CancelAfter(2000);
HttpResponseMessage httpResponseMessage = client.Send(new HttpRequestMessage(HttpMethod.Post, url + "remote/bring-to-foreground"), cts.Token);
httpResponseMessage.EnsureSuccessStatusCode();
return true;
process.Kill(true);
}
catch (Exception)
{
KillOtherInstances();
return false;
// ignored
}
}
}
private void KillOtherInstances()
private void UtilitiesOnRestartRequested(object? sender, RestartEventArgs e)
{
List<string> argsList = new();
argsList.AddRange(StartupArguments);
if (e.ExtraArgs != null)
argsList.AddRange(e.ExtraArgs.Except(argsList));
string args = argsList.Any() ? "-ArgumentList " + string.Join(',', argsList) : "";
string command =
$"-Command \"& {{Start-Sleep -Milliseconds {(int) e.Delay.TotalMilliseconds}; " +
"(Get-Process 'Artemis.UI.Windows').kill(); " +
$"Start-Process -FilePath '{Constants.ExecutablePath}' -WorkingDirectory '{Constants.ApplicationFolder}' {args}}}\"";
// Elevated always runs with RunAs
if (e.Elevate)
{
// Kill everything else heh
List<Process> processes = Process.GetProcessesByName("Artemis.UI.Windows").Where(p => p.Id != Process.GetCurrentProcess().Id).ToList();
foreach (Process process in processes)
{
try
{
process.Kill(true);
}
catch (Exception)
{
// ignored
}
}
}
private void UtilitiesOnRestartRequested(object? sender, RestartEventArgs e)
{
List<string> argsList = new();
argsList.AddRange(StartupArguments);
if (e.ExtraArgs != null)
argsList.AddRange(e.ExtraArgs.Except(argsList));
string args = argsList.Any() ? "-ArgumentList " + string.Join(',', argsList) : "";
string command =
$"-Command \"& {{Start-Sleep -Milliseconds {(int) e.Delay.TotalMilliseconds}; " +
"(Get-Process 'Artemis.UI.Windows').kill(); " +
$"Start-Process -FilePath '{Constants.ExecutablePath}' -WorkingDirectory '{Constants.ApplicationFolder}' {args}}}\"";
// Elevated always runs with RunAs
if (e.Elevate)
{
ProcessStartInfo info = new()
{
Arguments = command.Replace("}\"", " -Verb RunAs}\""),
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
FileName = "PowerShell.exe"
};
Process.Start(info);
}
// Non-elevated runs regularly if currently not elevated
else if (!IsElevated)
{
ProcessStartInfo info = new()
{
Arguments = command,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
FileName = "PowerShell.exe"
};
Process.Start(info);
}
// Non-elevated runs via a utility method is currently elevated (de-elevating is hacky)
else
{
string powerShell = Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
ProcessUtilities.RunAsDesktopUser(powerShell, command, true);
}
// Lets try a graceful shutdown, PowerShell will kill if needed
if (Application.Current?.ApplicationLifetime is IControlledApplicationLifetime controlledApplicationLifetime)
Dispatcher.UIThread.Post(() => controlledApplicationLifetime.Shutdown());
}
private void UtilitiesOnShutdownRequested(object? sender, EventArgs e)
{
// Use PowerShell to kill the process after 8 sec just in case
RunForcedShutdownIfEnabled();
if (Application.Current?.ApplicationLifetime is IControlledApplicationLifetime controlledApplicationLifetime)
Dispatcher.UIThread.Post(() => controlledApplicationLifetime.Shutdown());
}
private void RunForcedShutdownIfEnabled()
{
if (StartupArguments.Contains("--disable-forced-shutdown"))
return;
ProcessStartInfo info = new()
{
Arguments = "-Command \"& {Start-Sleep -s 8; (Get-Process -Id " + Process.GetCurrentProcess().Id + ").kill()}",
Arguments = command.Replace("}\"", " -Verb RunAs}\""),
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
FileName = "PowerShell.exe"
};
Process.Start(info);
}
// Non-elevated runs regularly if currently not elevated
else if (!IsElevated)
{
ProcessStartInfo info = new()
{
Arguments = command,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
FileName = "PowerShell.exe"
};
Process.Start(info);
}
// Non-elevated runs via a utility method is currently elevated (de-elevating is hacky)
else
{
string powerShell = Path.Combine(Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "powershell.exe");
ProcessUtilities.RunAsDesktopUser(powerShell, command, true);
}
// Lets try a graceful shutdown, PowerShell will kill if needed
if (Application.Current?.ApplicationLifetime is IControlledApplicationLifetime controlledApplicationLifetime)
Dispatcher.UIThread.Post(() => controlledApplicationLifetime.Shutdown());
}
private void UtilitiesOnShutdownRequested(object? sender, EventArgs e)
{
// Use PowerShell to kill the process after 8 sec just in case
RunForcedShutdownIfEnabled();
if (Application.Current?.ApplicationLifetime is IControlledApplicationLifetime controlledApplicationLifetime)
Dispatcher.UIThread.Post(() => controlledApplicationLifetime.Shutdown());
}
private void RunForcedShutdownIfEnabled()
{
if (StartupArguments.Contains("--disable-forced-shutdown"))
return;
ProcessStartInfo info = new()
{
Arguments = "-Command \"& {Start-Sleep -s 8; (Get-Process -Id " + Process.GetCurrentProcess().Id + ").kill()}",
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
FileName = "PowerShell.exe"
};
Process.Start(info);
}
}
+193 -194
View File
@@ -4,276 +4,275 @@ using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Artemis.UI.Windows.Models
namespace Artemis.UI.Windows.Models;
public class DevOpsBuilds
{
public class DevOpsBuilds
{
[JsonProperty("count")]
public long Count { get; set; }
[JsonProperty("count")]
public long Count { get; set; }
[JsonProperty("value")]
public List<DevOpsBuild> Builds { get; set; }
}
[JsonProperty("value")]
public List<DevOpsBuild> Builds { get; set; }
}
public class DevOpsBuild
{
[JsonProperty("_links")]
public BuildLinks Links { get; set; }
public class DevOpsBuild
{
[JsonProperty("_links")]
public BuildLinks Links { get; set; }
[JsonProperty("properties")]
public Properties Properties { get; set; }
[JsonProperty("properties")]
public Properties Properties { get; set; }
[JsonProperty("tags")]
public List<object> Tags { get; set; }
[JsonProperty("tags")]
public List<object> Tags { get; set; }
[JsonProperty("validationResults")]
public List<object> ValidationResults { get; set; }
[JsonProperty("validationResults")]
public List<object> ValidationResults { get; set; }
[JsonProperty("plans")]
public List<Plan> Plans { get; set; }
[JsonProperty("plans")]
public List<Plan> Plans { get; set; }
[JsonProperty("triggerInfo")]
public TriggerInfo TriggerInfo { get; set; }
[JsonProperty("triggerInfo")]
public TriggerInfo TriggerInfo { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("buildNumber")]
public string BuildNumber { get; set; }
[JsonProperty("buildNumber")]
public string BuildNumber { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("result")]
public string Result { get; set; }
[JsonProperty("result")]
public string Result { get; set; }
[JsonProperty("queueTime")]
public DateTimeOffset QueueTime { get; set; }
[JsonProperty("queueTime")]
public DateTimeOffset QueueTime { get; set; }
[JsonProperty("startTime")]
public DateTimeOffset StartTime { get; set; }
[JsonProperty("startTime")]
public DateTimeOffset StartTime { get; set; }
[JsonProperty("finishTime")]
public DateTimeOffset FinishTime { get; set; }
[JsonProperty("finishTime")]
public DateTimeOffset FinishTime { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("definition")]
public Definition Definition { get; set; }
[JsonProperty("definition")]
public Definition Definition { get; set; }
[JsonProperty("buildNumberRevision")]
public long BuildNumberRevision { get; set; }
[JsonProperty("buildNumberRevision")]
public long BuildNumberRevision { get; set; }
[JsonProperty("project")]
public Project Project { get; set; }
[JsonProperty("project")]
public Project Project { get; set; }
[JsonProperty("uri")]
public string Uri { get; set; }
[JsonProperty("uri")]
public string Uri { get; set; }
[JsonProperty("sourceBranch")]
public string SourceBranch { get; set; }
[JsonProperty("sourceBranch")]
public string SourceBranch { get; set; }
[JsonProperty("sourceVersion")]
public string SourceVersion { get; set; }
[JsonProperty("sourceVersion")]
public string SourceVersion { get; set; }
[JsonProperty("priority")]
public string Priority { get; set; }
[JsonProperty("priority")]
public string Priority { get; set; }
[JsonProperty("reason")]
public string Reason { get; set; }
[JsonProperty("reason")]
public string Reason { get; set; }
[JsonProperty("requestedFor")]
public LastChangedBy RequestedFor { get; set; }
[JsonProperty("requestedFor")]
public LastChangedBy RequestedFor { get; set; }
[JsonProperty("requestedBy")]
public LastChangedBy RequestedBy { get; set; }
[JsonProperty("requestedBy")]
public LastChangedBy RequestedBy { get; set; }
[JsonProperty("lastChangedDate")]
public DateTimeOffset LastChangedDate { get; set; }
[JsonProperty("lastChangedDate")]
public DateTimeOffset LastChangedDate { get; set; }
[JsonProperty("lastChangedBy")]
public LastChangedBy LastChangedBy { get; set; }
[JsonProperty("lastChangedBy")]
public LastChangedBy LastChangedBy { get; set; }
[JsonProperty("orchestrationPlan")]
public Plan OrchestrationPlan { get; set; }
[JsonProperty("orchestrationPlan")]
public Plan OrchestrationPlan { get; set; }
[JsonProperty("logs")]
public Logs Logs { get; set; }
[JsonProperty("logs")]
public Logs Logs { get; set; }
[JsonProperty("repository")]
public Repository Repository { get; set; }
[JsonProperty("repository")]
public Repository Repository { get; set; }
[JsonProperty("keepForever")]
public bool KeepForever { get; set; }
[JsonProperty("keepForever")]
public bool KeepForever { get; set; }
[JsonProperty("retainedByRelease")]
public bool RetainedByRelease { get; set; }
[JsonProperty("retainedByRelease")]
public bool RetainedByRelease { get; set; }
[JsonProperty("triggeredByBuild")]
public object TriggeredByBuild { get; set; }
}
[JsonProperty("triggeredByBuild")]
public object TriggeredByBuild { get; set; }
}
public class Definition
{
[JsonProperty("drafts")]
public List<object> Drafts { get; set; }
public class Definition
{
[JsonProperty("drafts")]
public List<object> Drafts { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("uri")]
public string Uri { get; set; }
[JsonProperty("uri")]
public string Uri { get; set; }
[JsonProperty("path")]
public string Path { get; set; }
[JsonProperty("path")]
public string Path { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("queueStatus")]
public string QueueStatus { get; set; }
[JsonProperty("queueStatus")]
public string QueueStatus { get; set; }
[JsonProperty("revision")]
public long Revision { get; set; }
[JsonProperty("revision")]
public long Revision { get; set; }
[JsonProperty("project")]
public Project Project { get; set; }
}
[JsonProperty("project")]
public Project Project { get; set; }
}
public class Project
{
[JsonProperty("id")]
public Guid Id { get; set; }
public class Project
{
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("state")]
public string State { get; set; }
[JsonProperty("state")]
public string State { get; set; }
[JsonProperty("revision")]
public long Revision { get; set; }
[JsonProperty("revision")]
public long Revision { get; set; }
[JsonProperty("visibility")]
public string Visibility { get; set; }
[JsonProperty("visibility")]
public string Visibility { get; set; }
[JsonProperty("lastUpdateTime")]
public DateTimeOffset LastUpdateTime { get; set; }
}
[JsonProperty("lastUpdateTime")]
public DateTimeOffset LastUpdateTime { get; set; }
}
public class LastChangedBy
{
[JsonProperty("displayName")]
public string DisplayName { get; set; }
public class LastChangedBy
{
[JsonProperty("displayName")]
public string DisplayName { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("_links")]
public LastChangedByLinks Links { get; set; }
[JsonProperty("_links")]
public LastChangedByLinks Links { get; set; }
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("id")]
public Guid Id { get; set; }
[JsonProperty("uniqueName")]
public object UniqueName { get; set; }
[JsonProperty("uniqueName")]
public object UniqueName { get; set; }
[JsonProperty("imageUrl")]
public object ImageUrl { get; set; }
[JsonProperty("imageUrl")]
public object ImageUrl { get; set; }
[JsonProperty("descriptor")]
public string Descriptor { get; set; }
}
[JsonProperty("descriptor")]
public string Descriptor { get; set; }
}
public class LastChangedByLinks
{
[JsonProperty("avatar")]
public Badge Avatar { get; set; }
}
public class LastChangedByLinks
{
[JsonProperty("avatar")]
public Badge Avatar { get; set; }
}
public class Badge
{
[JsonProperty("href")]
public Uri Href { get; set; }
}
public class Badge
{
[JsonProperty("href")]
public Uri Href { get; set; }
}
public class BuildLinks
{
[JsonProperty("self")]
public Badge Self { get; set; }
public class BuildLinks
{
[JsonProperty("self")]
public Badge Self { get; set; }
[JsonProperty("web")]
public Badge Web { get; set; }
[JsonProperty("web")]
public Badge Web { get; set; }
[JsonProperty("sourceVersionDisplayUri")]
public Badge SourceVersionDisplayUri { get; set; }
[JsonProperty("sourceVersionDisplayUri")]
public Badge SourceVersionDisplayUri { get; set; }
[JsonProperty("timeline")]
public Badge Timeline { get; set; }
[JsonProperty("timeline")]
public Badge Timeline { get; set; }
[JsonProperty("badge")]
public Badge Badge { get; set; }
}
[JsonProperty("badge")]
public Badge Badge { get; set; }
}
public class Logs
{
[JsonProperty("id")]
public long Id { get; set; }
public class Logs
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
}
[JsonProperty("url")]
public Uri Url { get; set; }
}
public class Plan
{
[JsonProperty("planId")]
public Guid PlanId { get; set; }
}
public class Plan
{
[JsonProperty("planId")]
public Guid PlanId { get; set; }
}
public class Properties
{
}
public class Properties
{
}
public class Repository
{
[JsonProperty("id")]
public string Id { get; set; }
public class Repository
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("clean")]
public object Clean { get; set; }
[JsonProperty("clean")]
public object Clean { get; set; }
[JsonProperty("checkoutSubmodules")]
public bool CheckoutSubmodules { get; set; }
}
[JsonProperty("checkoutSubmodules")]
public bool CheckoutSubmodules { get; set; }
}
public class TriggerInfo
{
[JsonProperty("ci.sourceBranch")]
public string CiSourceBranch { get; set; }
public class TriggerInfo
{
[JsonProperty("ci.sourceBranch")]
public string CiSourceBranch { get; set; }
[JsonProperty("ci.sourceSha")]
public string CiSourceSha { get; set; }
[JsonProperty("ci.sourceSha")]
public string CiSourceSha { get; set; }
[JsonProperty("ci.message")]
public string CiMessage { get; set; }
[JsonProperty("ci.message")]
public string CiMessage { get; set; }
[JsonProperty("ci.triggerRepository")]
public string CiTriggerRepository { get; set; }
}
[JsonProperty("ci.triggerRepository")]
public string CiTriggerRepository { get; set; }
}
+167 -168
View File
@@ -3,242 +3,241 @@ using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace Artemis.UI.Windows.Models
namespace Artemis.UI.Windows.Models;
public class GitHubDifference
{
public class GitHubDifference
{
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("html_url")]
public Uri HtmlUrl { get; set; }
[JsonProperty("html_url")]
public Uri HtmlUrl { get; set; }
[JsonProperty("permalink_url")]
public Uri PermalinkUrl { get; set; }
[JsonProperty("permalink_url")]
public Uri PermalinkUrl { get; set; }
[JsonProperty("diff_url")]
public Uri DiffUrl { get; set; }
[JsonProperty("diff_url")]
public Uri DiffUrl { get; set; }
[JsonProperty("patch_url")]
public Uri PatchUrl { get; set; }
[JsonProperty("patch_url")]
public Uri PatchUrl { get; set; }
[JsonProperty("base_commit")]
public BaseCommitClass BaseCommit { get; set; }
[JsonProperty("base_commit")]
public BaseCommitClass BaseCommit { get; set; }
[JsonProperty("merge_base_commit")]
public BaseCommitClass MergeBaseCommit { get; set; }
[JsonProperty("merge_base_commit")]
public BaseCommitClass MergeBaseCommit { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("ahead_by")]
public long AheadBy { get; set; }
[JsonProperty("ahead_by")]
public long AheadBy { get; set; }
[JsonProperty("behind_by")]
public long BehindBy { get; set; }
[JsonProperty("behind_by")]
public long BehindBy { get; set; }
[JsonProperty("total_commits")]
public long TotalCommits { get; set; }
[JsonProperty("total_commits")]
public long TotalCommits { get; set; }
[JsonProperty("commits")]
public List<BaseCommitClass> Commits { get; set; }
[JsonProperty("commits")]
public List<BaseCommitClass> Commits { get; set; }
[JsonProperty("files")]
public List<File> Files { get; set; }
}
[JsonProperty("files")]
public List<File> Files { get; set; }
}
public class BaseCommitClass
{
[JsonProperty("sha")]
public string Sha { get; set; }
public class BaseCommitClass
{
[JsonProperty("sha")]
public string Sha { get; set; }
[JsonProperty("node_id")]
public string NodeId { get; set; }
[JsonProperty("node_id")]
public string NodeId { get; set; }
[JsonProperty("commit")]
public BaseCommitCommit Commit { get; set; }
[JsonProperty("commit")]
public BaseCommitCommit Commit { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("html_url")]
public Uri HtmlUrl { get; set; }
[JsonProperty("html_url")]
public Uri HtmlUrl { get; set; }
[JsonProperty("comments_url")]
public Uri CommentsUrl { get; set; }
[JsonProperty("comments_url")]
public Uri CommentsUrl { get; set; }
[JsonProperty("author")]
public BaseCommitAuthor Author { get; set; }
[JsonProperty("author")]
public BaseCommitAuthor Author { get; set; }
[JsonProperty("committer")]
public BaseCommitAuthor Committer { get; set; }
[JsonProperty("committer")]
public BaseCommitAuthor Committer { get; set; }
[JsonProperty("parents")]
public List<Parent> Parents { get; set; }
}
[JsonProperty("parents")]
public List<Parent> Parents { get; set; }
}
public class BaseCommitAuthor
{
[JsonProperty("login")]
public string Login { get; set; }
public class BaseCommitAuthor
{
[JsonProperty("login")]
public string Login { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("node_id")]
public string NodeId { get; set; }
[JsonProperty("node_id")]
public string NodeId { get; set; }
[JsonProperty("avatar_url")]
public Uri AvatarUrl { get; set; }
[JsonProperty("avatar_url")]
public Uri AvatarUrl { get; set; }
[JsonProperty("gravatar_id")]
public string GravatarId { get; set; }
[JsonProperty("gravatar_id")]
public string GravatarId { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("html_url")]
public Uri HtmlUrl { get; set; }
[JsonProperty("html_url")]
public Uri HtmlUrl { get; set; }
[JsonProperty("followers_url")]
public Uri FollowersUrl { get; set; }
[JsonProperty("followers_url")]
public Uri FollowersUrl { get; set; }
[JsonProperty("following_url")]
public string FollowingUrl { get; set; }
[JsonProperty("following_url")]
public string FollowingUrl { get; set; }
[JsonProperty("gists_url")]
public string GistsUrl { get; set; }
[JsonProperty("gists_url")]
public string GistsUrl { get; set; }
[JsonProperty("starred_url")]
public string StarredUrl { get; set; }
[JsonProperty("starred_url")]
public string StarredUrl { get; set; }
[JsonProperty("subscriptions_url")]
public Uri SubscriptionsUrl { get; set; }
[JsonProperty("subscriptions_url")]
public Uri SubscriptionsUrl { get; set; }
[JsonProperty("organizations_url")]
public Uri OrganizationsUrl { get; set; }
[JsonProperty("organizations_url")]
public Uri OrganizationsUrl { get; set; }
[JsonProperty("repos_url")]
public Uri ReposUrl { get; set; }
[JsonProperty("repos_url")]
public Uri ReposUrl { get; set; }
[JsonProperty("events_url")]
public string EventsUrl { get; set; }
[JsonProperty("events_url")]
public string EventsUrl { get; set; }
[JsonProperty("received_events_url")]
public Uri ReceivedEventsUrl { get; set; }
[JsonProperty("received_events_url")]
public Uri ReceivedEventsUrl { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("site_admin")]
public bool SiteAdmin { get; set; }
}
[JsonProperty("site_admin")]
public bool SiteAdmin { get; set; }
}
public class BaseCommitCommit
{
[JsonProperty("author")]
public PurpleAuthor Author { get; set; }
public class BaseCommitCommit
{
[JsonProperty("author")]
public PurpleAuthor Author { get; set; }
[JsonProperty("committer")]
public PurpleAuthor Committer { get; set; }
[JsonProperty("committer")]
public PurpleAuthor Committer { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("tree")]
public Tree Tree { get; set; }
[JsonProperty("tree")]
public Tree Tree { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("comment_count")]
public long CommentCount { get; set; }
[JsonProperty("comment_count")]
public long CommentCount { get; set; }
[JsonProperty("verification")]
public Verification Verification { get; set; }
}
[JsonProperty("verification")]
public Verification Verification { get; set; }
}
public class PurpleAuthor
{
[JsonProperty("name")]
public string Name { get; set; }
public class PurpleAuthor
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("date")]
public DateTimeOffset Date { get; set; }
}
[JsonProperty("date")]
public DateTimeOffset Date { get; set; }
}
public class Tree
{
[JsonProperty("sha")]
public string Sha { get; set; }
public class Tree
{
[JsonProperty("sha")]
public string Sha { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
}
[JsonProperty("url")]
public Uri Url { get; set; }
}
public class Verification
{
[JsonProperty("verified")]
public bool Verified { get; set; }
public class Verification
{
[JsonProperty("verified")]
public bool Verified { get; set; }
[JsonProperty("reason")]
public string Reason { get; set; }
[JsonProperty("reason")]
public string Reason { get; set; }
[JsonProperty("signature")]
public string Signature { get; set; }
[JsonProperty("signature")]
public string Signature { get; set; }
[JsonProperty("payload")]
public string Payload { get; set; }
}
[JsonProperty("payload")]
public string Payload { get; set; }
}
public class Parent
{
[JsonProperty("sha")]
public string Sha { get; set; }
public class Parent
{
[JsonProperty("sha")]
public string Sha { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("html_url")]
public Uri HtmlUrl { get; set; }
}
[JsonProperty("html_url")]
public Uri HtmlUrl { get; set; }
}
public class File
{
[JsonProperty("sha")]
public string Sha { get; set; }
public class File
{
[JsonProperty("sha")]
public string Sha { get; set; }
[JsonProperty("filename")]
public string Filename { get; set; }
[JsonProperty("filename")]
public string Filename { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("additions")]
public long Additions { get; set; }
[JsonProperty("additions")]
public long Additions { get; set; }
[JsonProperty("deletions")]
public long Deletions { get; set; }
[JsonProperty("deletions")]
public long Deletions { get; set; }
[JsonProperty("changes")]
public long Changes { get; set; }
[JsonProperty("changes")]
public long Changes { get; set; }
[JsonProperty("blob_url")]
public Uri BlobUrl { get; set; }
[JsonProperty("blob_url")]
public Uri BlobUrl { get; set; }
[JsonProperty("raw_url")]
public Uri RawUrl { get; set; }
[JsonProperty("raw_url")]
public Uri RawUrl { get; set; }
[JsonProperty("contents_url")]
public Uri ContentsUrl { get; set; }
[JsonProperty("contents_url")]
public Uri ContentsUrl { get; set; }
[JsonProperty("patch")]
public string Patch { get; set; }
[JsonProperty("patch")]
public string Patch { get; set; }
[JsonProperty("previous_filename", NullValueHandling = NullValueHandling.Ignore)]
public string PreviousFilename { get; set; }
}
[JsonProperty("previous_filename", NullValueHandling = NullValueHandling.Ignore)]
public string PreviousFilename { get; set; }
}
@@ -1,5 +1,4 @@
using Artemis.Core.Providers;
using Artemis.Core.Services;
using Artemis.UI.Shared.Providers;
using Artemis.UI.Windows.Providers;
using Ninject.Modules;
+34 -35
View File
@@ -4,46 +4,45 @@ using Avalonia.ReactiveUI;
using Ninject;
using Serilog;
namespace Artemis.UI.Windows
namespace Artemis.UI.Windows;
internal class Program
{
internal class Program
private static ILogger? Logger { get; set; }
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
[STAThread]
public static void Main(string[] args)
{
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
[STAThread]
public static void Main(string[] args)
try
{
try
{
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
catch (Exception e)
{
Logger?.Fatal(e, "Fatal exception, shutting down");
throw;
}
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
catch (Exception e)
{
return AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace()
.With(new Win32PlatformOptions()
{
UseWindowsUIComposition = true,
CompositionBackdropCornerRadius = 8f
})
.UseReactiveUI();
}
private static ILogger? Logger { get; set; }
public static void CreateLogger(IKernel kernel)
{
Logger = kernel.Get<ILogger>().ForContext<Program>();
Logger?.Fatal(e, "Fatal exception, shutting down");
throw;
}
}
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
{
return AppBuilder.Configure<App>()
.UsePlatformDetect()
.LogToTrace()
.With(new Win32PlatformOptions
{
UseWindowsUIComposition = true,
CompositionBackdropCornerRadius = 8f
})
.UseReactiveUI();
}
public static void CreateLogger(IKernel kernel)
{
Logger = kernel.Get<ILogger>().ForContext<Program>();
}
}
@@ -64,7 +64,9 @@ public class AutoRunProvider : IAutoRunProvider
string xmlPath = Path.GetTempFileName();
await using (Stream fileStream = new FileStream(xmlPath, FileMode.Create))
{
await document.SaveAsync(fileStream, SaveOptions.None, CancellationToken.None);
}
Process schtasks = new()
{
@@ -106,7 +108,7 @@ public class AutoRunProvider : IAutoRunProvider
public async Task EnableAutoRun(bool recreate, int autoRunDelay)
{
// if (Constants.BuildInfo.IsLocalBuild)
// return;
// return;
// Create or remove the task if necessary
bool taskCreated = false;
@@ -1,26 +1,25 @@
using System;
using Avalonia.Win32;
namespace Artemis.UI.Windows.Providers.Input
namespace Artemis.UI.Windows.Providers.Input;
public class SpongeWindow : WindowImpl
{
public class SpongeWindow : WindowImpl
public event EventHandler<SpongeWindowEventArgs>? WndProcCalled;
#region Overrides of WindowImpl
/// <inheritdoc />
protected override IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
#region Overrides of WindowImpl
OnWndProcCalled(new SpongeWindowEventArgs(hWnd, msg, wParam, lParam));
return base.WndProc(hWnd, msg, wParam, lParam);
}
/// <inheritdoc />
protected override IntPtr WndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
OnWndProcCalled(new SpongeWindowEventArgs(hWnd, msg, wParam, lParam));
return base.WndProc(hWnd, msg, wParam, lParam);
}
#endregion
#endregion
public event EventHandler<SpongeWindowEventArgs>? WndProcCalled;
protected virtual void OnWndProcCalled(SpongeWindowEventArgs e)
{
WndProcCalled?.Invoke(this, e);
}
protected virtual void OnWndProcCalled(SpongeWindowEventArgs e)
{
WndProcCalled?.Invoke(this, e);
}
}
@@ -1,20 +1,19 @@
using System;
namespace Artemis.UI.Windows.Providers.Input
{
public class SpongeWindowEventArgs : EventArgs
{
public IntPtr HWnd { get; }
public uint Msg { get; }
public IntPtr WParam { get; }
public IntPtr LParam { get; }
namespace Artemis.UI.Windows.Providers.Input;
public SpongeWindowEventArgs(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
HWnd = hWnd;
Msg = msg;
WParam = wParam;
LParam = lParam;
}
public class SpongeWindowEventArgs : EventArgs
{
public SpongeWindowEventArgs(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
HWnd = hWnd;
Msg = msg;
WParam = wParam;
LParam = lParam;
}
public IntPtr HWnd { get; }
public uint Msg { get; }
public IntPtr WParam { get; }
public IntPtr LParam { get; }
}
@@ -8,276 +8,268 @@ using Artemis.UI.Windows.Utilities;
using Linearstar.Windows.RawInput;
using Linearstar.Windows.RawInput.Native;
using Serilog;
using MouseButton = Artemis.Core.Services.MouseButton;
namespace Artemis.UI.Windows.Providers.Input
namespace Artemis.UI.Windows.Providers.Input;
public class WindowsInputProvider : InputProvider
{
public class WindowsInputProvider : InputProvider
private const int WM_INPUT = 0x00FF;
private readonly IInputService _inputService;
private readonly ILogger _logger;
private readonly Timer _taskManagerTimer;
private DateTime _lastMouseUpdate;
private int _lastProcessId;
private readonly SpongeWindow _sponge;
public WindowsInputProvider(ILogger logger, IInputService inputService)
{
private const int WM_INPUT = 0x00FF;
_logger = logger;
_inputService = inputService;
private readonly IInputService _inputService;
private readonly ILogger _logger;
private DateTime _lastMouseUpdate;
private int _lastProcessId;
private SpongeWindow _sponge;
private readonly Timer _taskManagerTimer;
_sponge = new SpongeWindow();
_sponge.WndProcCalled += SpongeOnWndProcCalled;
public WindowsInputProvider(ILogger logger, IInputService inputService)
{
_logger = logger;
_inputService = inputService;
_taskManagerTimer = new Timer(500);
_taskManagerTimer.Elapsed += TaskManagerTimerOnElapsed;
_taskManagerTimer.Start();
_sponge = new SpongeWindow();
_sponge.WndProcCalled += SpongeOnWndProcCalled;
_taskManagerTimer = new Timer(500);
_taskManagerTimer.Elapsed += TaskManagerTimerOnElapsed;
_taskManagerTimer.Start();
RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.InputSink, _sponge.Handle.Handle);
RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.InputSink, _sponge.Handle.Handle);
}
#region Overrides of InputProvider
/// <inheritdoc />
public override void OnKeyboardToggleStatusRequested()
{
UpdateToggleStatus();
}
#endregion
#region IDisposable
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (disposing)
{
_sponge.Dispose();
_taskManagerTimer.Dispose();
}
base.Dispose(disposing);
}
#endregion
private void SpongeOnWndProcCalled(object? sender, SpongeWindowEventArgs message)
{
if (message.Msg != WM_INPUT)
return;
RawInputData data = RawInputData.FromHandle(message.LParam);
switch (data)
{
case RawInputMouseData mouse:
HandleMouseData(data, mouse);
break;
case RawInputKeyboardData keyboard:
HandleKeyboardData(data, keyboard);
break;
}
}
private void TaskManagerTimerOnElapsed(object? sender, ElapsedEventArgs e)
{
int processId = WindowUtilities.GetActiveProcessId();
if (processId == _lastProcessId)
return;
_lastProcessId = processId;
// If task manager has focus then we can't track keys properly, release everything to avoid them getting stuck
// Same goes for Idle which is what you get when you press Ctrl+Alt+Del
Process active = Process.GetProcessById(processId);
if (active?.ProcessName == "Taskmgr" || active?.ProcessName == "Idle")
_inputService.ReleaseAll();
}
#region Keyboard
private void HandleKeyboardData(RawInputData data, RawInputKeyboardData keyboardData)
{
KeyboardKey key = InputUtilities.KeyFromVirtualKey(keyboardData.Keyboard.VirutalKey);
// Debug.WriteLine($"VK: {key} ({keyboardData.Keyboard.VirutalKey}), Flags: {keyboardData.Keyboard.Flags}, Scan code: {keyboardData.Keyboard.ScanCode}");
// Sometimes we get double hits and they resolve to None, ignore those
if (key == KeyboardKey.None)
return;
// Right alt triggers LeftCtrl with a different scan code for some reason, ignore those
if (key == KeyboardKey.LeftCtrl && keyboardData.Keyboard.ScanCode == 56)
return;
string? identifier = data.Device?.DevicePath;
// Let the core know there is an identifier so it can store new identifications if applicable
if (identifier != null)
OnIdentifierReceived(identifier, InputDeviceType.Keyboard);
ArtemisDevice? device = null;
if (identifier != null)
try
{
device = _inputService.GetDeviceByIdentifier(this, identifier, InputDeviceType.Keyboard);
}
catch (Exception e)
{
_logger.Warning(e, "Failed to retrieve input device by its identifier");
}
// Duplicate keys with different positions can be identified by the LeftKey flag (even though its set of the key that's physically on the right)
if (keyboardData.Keyboard.Flags == RawKeyboardFlags.KeyE0 || keyboardData.Keyboard.Flags == (RawKeyboardFlags.KeyE0 | RawKeyboardFlags.Up))
{
if (key == KeyboardKey.Enter)
key = KeyboardKey.NumPadEnter;
if (key == KeyboardKey.LeftCtrl)
key = KeyboardKey.RightCtrl;
if (key == KeyboardKey.LeftAlt)
key = KeyboardKey.RightAlt;
}
if (key == KeyboardKey.LeftShift && keyboardData.Keyboard.ScanCode == 54)
key = KeyboardKey.RightShift;
bool isDown = keyboardData.Keyboard.Flags != RawKeyboardFlags.Up &&
keyboardData.Keyboard.Flags != (RawKeyboardFlags.Up | RawKeyboardFlags.KeyE0) &&
keyboardData.Keyboard.Flags != (RawKeyboardFlags.Up | RawKeyboardFlags.KeyE1);
OnKeyboardDataReceived(device, key, isDown);
UpdateToggleStatus();
}
private void UpdateToggleStatus()
{
OnKeyboardToggleStatusReceived(new KeyboardToggleStatus(
InputUtilities.IsKeyToggled(KeyboardKey.NumLock),
InputUtilities.IsKeyToggled(KeyboardKey.CapsLock),
InputUtilities.IsKeyToggled(KeyboardKey.Scroll)
));
}
#endregion
#region Mouse
private int _mouseDeltaX;
private int _mouseDeltaY;
private void HandleMouseData(RawInputData data, RawInputMouseData mouseData)
{
// Only submit mouse movement 25 times per second but increment the delta
// This can create a small inaccuracy of course, but Artemis is not a shooter :')
if (mouseData.Mouse.Buttons == RawMouseButtonFlags.None)
{
_mouseDeltaX += mouseData.Mouse.LastX;
_mouseDeltaY += mouseData.Mouse.LastY;
if (DateTime.Now - _lastMouseUpdate < TimeSpan.FromMilliseconds(40))
return;
}
ArtemisDevice? device = null;
string? identifier = data.Device?.DevicePath;
if (identifier != null)
{
try
{
device = _inputService.GetDeviceByIdentifier(this, identifier, InputDeviceType.Mouse);
}
catch (Exception e)
{
_logger.Warning(e, "Failed to retrieve input device by its identifier");
}
}
// Debug.WriteLine($"Buttons: {mouseData.Mouse.Buttons}, Data: {mouseData.Mouse.ButtonData}, Flags: {mouseData.Mouse.Flags}, XY: {mouseData.Mouse.LastX},{mouseData.Mouse.LastY}");
// Movement
if (mouseData.Mouse.Buttons == RawMouseButtonFlags.None)
{
Win32Point cursorPosition = GetCursorPosition();
OnMouseMoveDataReceived(device, cursorPosition.X, cursorPosition.Y, _mouseDeltaX, _mouseDeltaY);
_mouseDeltaX = 0;
_mouseDeltaY = 0;
_lastMouseUpdate = DateTime.Now;
return;
}
// Now we know its not movement, let the core know there is an identifier so it can store new identifications if applicable
if (identifier != null)
OnIdentifierReceived(identifier, InputDeviceType.Mouse);
// Scrolling
if (mouseData.Mouse.ButtonData != 0)
{
if (mouseData.Mouse.Buttons == RawMouseButtonFlags.MouseWheel)
OnMouseScrollDataReceived(device, MouseScrollDirection.Vertical, mouseData.Mouse.ButtonData);
else if (mouseData.Mouse.Buttons == RawMouseButtonFlags.MouseHorizontalWheel)
OnMouseScrollDataReceived(device, MouseScrollDirection.Horizontal, mouseData.Mouse.ButtonData);
return;
}
// Button presses
MouseButton button = MouseButton.Left;
bool isDown = false;
// Left
if (DetermineMouseButton(mouseData, RawMouseButtonFlags.LeftButtonDown, RawMouseButtonFlags.LeftButtonUp, ref isDown))
button = MouseButton.Left;
// Middle
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.MiddleButtonDown, RawMouseButtonFlags.MiddleButtonUp, ref isDown))
button = MouseButton.Middle;
// Right
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.RightButtonDown, RawMouseButtonFlags.RightButtonUp, ref isDown))
button = MouseButton.Right;
// Button 4
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.Button4Down, RawMouseButtonFlags.Button4Up, ref isDown))
button = MouseButton.Button4;
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.Button5Down, RawMouseButtonFlags.Button5Up, ref isDown))
button = MouseButton.Button5;
OnMouseButtonDataReceived(device, button, isDown);
}
private bool DetermineMouseButton(RawInputMouseData data, RawMouseButtonFlags downButton, RawMouseButtonFlags upButton, ref bool isDown)
{
if (data.Mouse.Buttons == downButton || data.Mouse.Buttons == upButton)
{
isDown = data.Mouse.Buttons == downButton;
return true;
}
isDown = false;
return false;
}
#endregion
#region Native
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
private struct Win32Point
{
public readonly int X;
public readonly int Y;
}
private static Win32Point GetCursorPosition()
{
Win32Point w32Mouse = new();
GetCursorPos(ref w32Mouse);
return w32Mouse;
}
#endregion
RawInputDevice.RegisterDevice(HidUsageAndPage.Keyboard, RawInputDeviceFlags.InputSink, _sponge.Handle.Handle);
RawInputDevice.RegisterDevice(HidUsageAndPage.Mouse, RawInputDeviceFlags.InputSink, _sponge.Handle.Handle);
}
#region Overrides of InputProvider
/// <inheritdoc />
public override void OnKeyboardToggleStatusRequested()
{
UpdateToggleStatus();
}
#endregion
/// <inheritdoc />
protected override void Dispose(bool disposing)
{
if (disposing)
{
_sponge.Dispose();
_taskManagerTimer.Dispose();
}
base.Dispose(disposing);
}
private void SpongeOnWndProcCalled(object? sender, SpongeWindowEventArgs message)
{
if (message.Msg != WM_INPUT)
return;
RawInputData data = RawInputData.FromHandle(message.LParam);
switch (data)
{
case RawInputMouseData mouse:
HandleMouseData(data, mouse);
break;
case RawInputKeyboardData keyboard:
HandleKeyboardData(data, keyboard);
break;
}
}
private void TaskManagerTimerOnElapsed(object? sender, ElapsedEventArgs e)
{
int processId = WindowUtilities.GetActiveProcessId();
if (processId == _lastProcessId)
return;
_lastProcessId = processId;
// If task manager has focus then we can't track keys properly, release everything to avoid them getting stuck
// Same goes for Idle which is what you get when you press Ctrl+Alt+Del
Process active = Process.GetProcessById(processId);
if (active?.ProcessName == "Taskmgr" || active?.ProcessName == "Idle")
_inputService.ReleaseAll();
}
#region Keyboard
private void HandleKeyboardData(RawInputData data, RawInputKeyboardData keyboardData)
{
KeyboardKey key = InputUtilities.KeyFromVirtualKey(keyboardData.Keyboard.VirutalKey);
// Debug.WriteLine($"VK: {key} ({keyboardData.Keyboard.VirutalKey}), Flags: {keyboardData.Keyboard.Flags}, Scan code: {keyboardData.Keyboard.ScanCode}");
// Sometimes we get double hits and they resolve to None, ignore those
if (key == KeyboardKey.None)
return;
// Right alt triggers LeftCtrl with a different scan code for some reason, ignore those
if (key == KeyboardKey.LeftCtrl && keyboardData.Keyboard.ScanCode == 56)
return;
string? identifier = data.Device?.DevicePath;
// Let the core know there is an identifier so it can store new identifications if applicable
if (identifier != null)
OnIdentifierReceived(identifier, InputDeviceType.Keyboard);
ArtemisDevice? device = null;
if (identifier != null)
try
{
device = _inputService.GetDeviceByIdentifier(this, identifier, InputDeviceType.Keyboard);
}
catch (Exception e)
{
_logger.Warning(e, "Failed to retrieve input device by its identifier");
}
// Duplicate keys with different positions can be identified by the LeftKey flag (even though its set of the key that's physically on the right)
if (keyboardData.Keyboard.Flags == RawKeyboardFlags.KeyE0 || keyboardData.Keyboard.Flags == (RawKeyboardFlags.KeyE0 | RawKeyboardFlags.Up))
{
if (key == KeyboardKey.Enter)
key = KeyboardKey.NumPadEnter;
if (key == KeyboardKey.LeftCtrl)
key = KeyboardKey.RightCtrl;
if (key == KeyboardKey.LeftAlt)
key = KeyboardKey.RightAlt;
}
if (key == KeyboardKey.LeftShift && keyboardData.Keyboard.ScanCode == 54)
key = KeyboardKey.RightShift;
bool isDown = keyboardData.Keyboard.Flags != RawKeyboardFlags.Up &&
keyboardData.Keyboard.Flags != (RawKeyboardFlags.Up | RawKeyboardFlags.KeyE0) &&
keyboardData.Keyboard.Flags != (RawKeyboardFlags.Up | RawKeyboardFlags.KeyE1);
OnKeyboardDataReceived(device, key, isDown);
UpdateToggleStatus();
}
private void UpdateToggleStatus()
{
OnKeyboardToggleStatusReceived(new KeyboardToggleStatus(
InputUtilities.IsKeyToggled(KeyboardKey.NumLock),
InputUtilities.IsKeyToggled(KeyboardKey.CapsLock),
InputUtilities.IsKeyToggled(KeyboardKey.Scroll)
));
}
#endregion
#region Mouse
private int _mouseDeltaX;
private int _mouseDeltaY;
private void HandleMouseData(RawInputData data, RawInputMouseData mouseData)
{
// Only submit mouse movement 25 times per second but increment the delta
// This can create a small inaccuracy of course, but Artemis is not a shooter :')
if (mouseData.Mouse.Buttons == RawMouseButtonFlags.None)
{
_mouseDeltaX += mouseData.Mouse.LastX;
_mouseDeltaY += mouseData.Mouse.LastY;
if (DateTime.Now - _lastMouseUpdate < TimeSpan.FromMilliseconds(40))
return;
}
ArtemisDevice? device = null;
string? identifier = data.Device?.DevicePath;
if (identifier != null)
try
{
device = _inputService.GetDeviceByIdentifier(this, identifier, InputDeviceType.Mouse);
}
catch (Exception e)
{
_logger.Warning(e, "Failed to retrieve input device by its identifier");
}
// Debug.WriteLine($"Buttons: {mouseData.Mouse.Buttons}, Data: {mouseData.Mouse.ButtonData}, Flags: {mouseData.Mouse.Flags}, XY: {mouseData.Mouse.LastX},{mouseData.Mouse.LastY}");
// Movement
if (mouseData.Mouse.Buttons == RawMouseButtonFlags.None)
{
Win32Point cursorPosition = GetCursorPosition();
OnMouseMoveDataReceived(device, cursorPosition.X, cursorPosition.Y, _mouseDeltaX, _mouseDeltaY);
_mouseDeltaX = 0;
_mouseDeltaY = 0;
_lastMouseUpdate = DateTime.Now;
return;
}
// Now we know its not movement, let the core know there is an identifier so it can store new identifications if applicable
if (identifier != null)
OnIdentifierReceived(identifier, InputDeviceType.Mouse);
// Scrolling
if (mouseData.Mouse.ButtonData != 0)
{
if (mouseData.Mouse.Buttons == RawMouseButtonFlags.MouseWheel)
OnMouseScrollDataReceived(device, MouseScrollDirection.Vertical, mouseData.Mouse.ButtonData);
else if (mouseData.Mouse.Buttons == RawMouseButtonFlags.MouseHorizontalWheel)
OnMouseScrollDataReceived(device, MouseScrollDirection.Horizontal, mouseData.Mouse.ButtonData);
return;
}
// Button presses
MouseButton button = MouseButton.Left;
bool isDown = false;
// Left
if (DetermineMouseButton(mouseData, RawMouseButtonFlags.LeftButtonDown, RawMouseButtonFlags.LeftButtonUp, ref isDown))
button = MouseButton.Left;
// Middle
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.MiddleButtonDown, RawMouseButtonFlags.MiddleButtonUp, ref isDown))
button = MouseButton.Middle;
// Right
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.RightButtonDown, RawMouseButtonFlags.RightButtonUp, ref isDown))
button = MouseButton.Right;
// Button 4
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.Button4Down, RawMouseButtonFlags.Button4Up, ref isDown))
button = MouseButton.Button4;
else if (DetermineMouseButton(mouseData, RawMouseButtonFlags.Button5Down, RawMouseButtonFlags.Button5Up, ref isDown))
button = MouseButton.Button5;
OnMouseButtonDataReceived(device, button, isDown);
}
private bool DetermineMouseButton(RawInputMouseData data, RawMouseButtonFlags downButton, RawMouseButtonFlags upButton, ref bool isDown)
{
if (data.Mouse.Buttons == downButton || data.Mouse.Buttons == upButton)
{
isDown = data.Mouse.Buttons == downButton;
return true;
}
isDown = false;
return false;
}
#endregion
#region Native
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetCursorPos(ref Win32Point pt);
[StructLayout(LayoutKind.Sequential)]
private struct Win32Point
{
public readonly int X;
public readonly int Y;
}
private static Win32Point GetCursorPosition()
{
Win32Point w32Mouse = new();
GetCursorPos(ref w32Mouse);
return w32Mouse;
}
#endregion
}
+122 -125
View File
@@ -6,6 +6,7 @@ using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Artemis.Core;
using Artemis.UI.Exceptions;
using Artemis.UI.Shared.Providers;
using Artemis.UI.Shared.Services;
@@ -27,8 +28,8 @@ public class UpdateProvider : IUpdateProvider, IDisposable
private const string InstallerUrl = "https://builds.artemis-rgb.com/binaries/Artemis.Installer.exe";
private readonly ILogger _logger;
private readonly IWindowService _windowService;
private readonly IMainWindowService _mainWindowService;
private readonly IWindowService _windowService;
public UpdateProvider(ILogger logger, IWindowService windowService, IMainWindowService mainWindowService)
{
@@ -39,128 +40,6 @@ public class UpdateProvider : IUpdateProvider, IDisposable
ToastNotificationManagerCompat.OnActivated += ToastNotificationManagerCompatOnOnActivated;
}
private async void ToastNotificationManagerCompatOnOnActivated(ToastNotificationActivatedEventArgsCompat e)
{
ToastArguments args = ToastArguments.Parse(e.Argument);
string channel = args.Get("channel");
string action = "view-changes";
if (args.Contains("action"))
action = args.Get("action");
if (action == "install")
await RunInstaller(channel, true);
else if (action == "view-changes")
{
await Dispatcher.UIThread.InvokeAsync(async () =>
{
_mainWindowService.OpenMainWindow();
await OfferUpdate(channel, true);
});
}
}
private async Task RunInstaller(string channel, bool silent)
{
_logger.Information("ApplyUpdate: Applying update");
// Ensure the installer is up-to-date, get installer build info
DevOpsBuild? buildInfo = await GetBuildInfo(6);
string installerPath = Path.Combine(Core.Constants.DataFolder, "installer", "Artemis.Installer.exe");
// Always update installer if it is missing ^^
if (!File.Exists(installerPath))
await UpdateInstaller();
// Compare the creation date of the installer with the build date and update if needed
else
{
if (buildInfo != null && File.GetLastWriteTime(installerPath) < buildInfo.FinishTime)
await UpdateInstaller();
}
_logger.Information("ApplyUpdate: Running installer at {InstallerPath}", installerPath);
try
{
Process.Start(new ProcessStartInfo(installerPath, "-autoupdate")
{
UseShellExecute = true,
Verb = "runas"
});
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == 0x4c7)
_logger.Warning("ApplyUpdate: Operation was cancelled, user likely clicked No in UAC dialog");
else
throw;
}
}
private async Task UpdateInstaller()
{
string installerDirectory = Path.Combine(Core.Constants.DataFolder, "installer");
string installerPath = Path.Combine(installerDirectory, "Artemis.Installer.exe");
_logger.Information("UpdateInstaller: Downloading installer from {DownloadUrl}", InstallerUrl);
using HttpClient client = new();
HttpResponseMessage httpResponseMessage = await client.GetAsync(InstallerUrl);
if (!httpResponseMessage.IsSuccessStatusCode)
throw new ArtemisUIException($"Failed to download installer, status code {httpResponseMessage.StatusCode}");
_logger.Information("UpdateInstaller: Writing installer file to {InstallerPath}", installerPath);
if (File.Exists(installerPath))
File.Delete(installerPath);
Core.Utilities.CreateAccessibleDirectory(installerDirectory);
await using FileStream fs = new(installerPath, FileMode.Create, FileAccess.Write, FileShare.None);
await httpResponseMessage.Content.CopyToAsync(fs);
}
/// <inheritdoc />
public async Task<bool> CheckForUpdate(string channel)
{
DevOpsBuild? buildInfo = await GetBuildInfo(1);
if (buildInfo == null)
return false;
double buildNumber = double.Parse(buildInfo.BuildNumber, CultureInfo.InvariantCulture);
string buildNumberDisplay = buildNumber.ToString(CultureInfo.InvariantCulture);
_logger.Information("Latest build is {BuildNumber}, we're running {LocalBuildNumber}", buildNumberDisplay, Core.Constants.BuildInfo.BuildNumberDisplay);
return buildNumber > Core.Constants.BuildInfo.BuildNumber;
}
/// <inheritdoc />
public async Task ApplyUpdate(string channel, bool silent)
{
await RunInstaller(channel, silent);
}
/// <inheritdoc />
public async Task OfferUpdate(string channel, bool windowOpen)
{
if (windowOpen)
{
bool update = await _windowService.ShowDialogAsync<UpdateDialogViewModel, bool>(("channel", channel));
if (update)
await RunInstaller(channel, false);
}
else
{
ShowDesktopNotification(channel);
}
}
private void ShowDesktopNotification(string channel)
{
new ToastContentBuilder()
.AddArgument("channel", channel)
.AddText("An update is available")
.AddButton(new ToastButton().SetContent("Install").AddArgument("action", "install").SetBackgroundActivation())
.AddButton(new ToastButton().SetContent("View changes").AddArgument("action", "view-changes"))
.Show();
}
public async Task<DevOpsBuild?> GetBuildInfo(int buildDefinition, string? buildNumber = null)
{
Url request = ApiUrl.AppendPathSegments("build", "builds")
@@ -202,7 +81,92 @@ public class UpdateProvider : IUpdateProvider, IDisposable
.GetJsonAsync<GitHubDifference>();
}
#region IDisposable
private async void ToastNotificationManagerCompatOnOnActivated(ToastNotificationActivatedEventArgsCompat e)
{
ToastArguments args = ToastArguments.Parse(e.Argument);
string channel = args.Get("channel");
string action = "view-changes";
if (args.Contains("action"))
action = args.Get("action");
if (action == "install")
await RunInstaller(channel, true);
else if (action == "view-changes")
await Dispatcher.UIThread.InvokeAsync(async () =>
{
_mainWindowService.OpenMainWindow();
await OfferUpdate(channel, true);
});
}
private async Task RunInstaller(string channel, bool silent)
{
_logger.Information("ApplyUpdate: Applying update");
// Ensure the installer is up-to-date, get installer build info
DevOpsBuild? buildInfo = await GetBuildInfo(6);
string installerPath = Path.Combine(Constants.DataFolder, "installer", "Artemis.Installer.exe");
// Always update installer if it is missing ^^
if (!File.Exists(installerPath))
{
await UpdateInstaller();
}
// Compare the creation date of the installer with the build date and update if needed
else
{
if (buildInfo != null && File.GetLastWriteTime(installerPath) < buildInfo.FinishTime)
await UpdateInstaller();
}
_logger.Information("ApplyUpdate: Running installer at {InstallerPath}", installerPath);
try
{
Process.Start(new ProcessStartInfo(installerPath, "-autoupdate")
{
UseShellExecute = true,
Verb = "runas"
});
}
catch (Win32Exception e)
{
if (e.NativeErrorCode == 0x4c7)
_logger.Warning("ApplyUpdate: Operation was cancelled, user likely clicked No in UAC dialog");
else
throw;
}
}
private async Task UpdateInstaller()
{
string installerDirectory = Path.Combine(Constants.DataFolder, "installer");
string installerPath = Path.Combine(installerDirectory, "Artemis.Installer.exe");
_logger.Information("UpdateInstaller: Downloading installer from {DownloadUrl}", InstallerUrl);
using HttpClient client = new();
HttpResponseMessage httpResponseMessage = await client.GetAsync(InstallerUrl);
if (!httpResponseMessage.IsSuccessStatusCode)
throw new ArtemisUIException($"Failed to download installer, status code {httpResponseMessage.StatusCode}");
_logger.Information("UpdateInstaller: Writing installer file to {InstallerPath}", installerPath);
if (File.Exists(installerPath))
File.Delete(installerPath);
Core.Utilities.CreateAccessibleDirectory(installerDirectory);
await using FileStream fs = new(installerPath, FileMode.Create, FileAccess.Write, FileShare.None);
await httpResponseMessage.Content.CopyToAsync(fs);
}
private void ShowDesktopNotification(string channel)
{
new ToastContentBuilder()
.AddArgument("channel", channel)
.AddText("An update is available")
.AddButton(new ToastButton().SetContent("Install").AddArgument("action", "install").SetBackgroundActivation())
.AddButton(new ToastButton().SetContent("View changes").AddArgument("action", "view-changes"))
.Show();
}
/// <inheritdoc />
public void Dispose()
@@ -211,5 +175,38 @@ public class UpdateProvider : IUpdateProvider, IDisposable
ToastNotificationManagerCompat.Uninstall();
}
#endregion
/// <inheritdoc />
public async Task<bool> CheckForUpdate(string channel)
{
DevOpsBuild? buildInfo = await GetBuildInfo(1);
if (buildInfo == null)
return false;
double buildNumber = double.Parse(buildInfo.BuildNumber, CultureInfo.InvariantCulture);
string buildNumberDisplay = buildNumber.ToString(CultureInfo.InvariantCulture);
_logger.Information("Latest build is {BuildNumber}, we're running {LocalBuildNumber}", buildNumberDisplay, Constants.BuildInfo.BuildNumberDisplay);
return buildNumber > Constants.BuildInfo.BuildNumber;
}
/// <inheritdoc />
public async Task ApplyUpdate(string channel, bool silent)
{
await RunInstaller(channel, silent);
}
/// <inheritdoc />
public async Task OfferUpdate(string channel, bool windowOpen)
{
if (windowOpen)
{
bool update = await _windowService.ShowDialogAsync<UpdateDialogViewModel, bool>(("channel", channel));
if (update)
await RunInstaller(channel, false);
}
else
{
ShowDesktopNotification(channel);
}
}
}
@@ -1,11 +1,10 @@
using Artemis.UI.Shared;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace Artemis.UI.Windows.Screens.Update;
public partial class UpdateDialogView : ReactiveCoreWindow<UpdateDialogViewModel>
public class UpdateDialogView : ReactiveCoreWindow<UpdateDialogViewModel>
{
public UpdateDialogView()
{
@@ -4,6 +4,7 @@ using System.Linq;
using System.Reactive;
using System.Reactive.Disposables;
using System.Threading.Tasks;
using Artemis.Core;
using Artemis.UI.Shared;
using Artemis.UI.Shared.Providers;
using Artemis.UI.Shared.Services;
@@ -18,9 +19,6 @@ namespace Artemis.UI.Windows.Screens.Update;
public class UpdateDialogViewModel : DialogViewModelBase<bool>
{
private readonly UpdateProvider _updateProvider;
private readonly INotificationService _notificationService;
// Based on https://docs.microsoft.com/en-us/azure/devops/pipelines/repos/github?view=azure-devops&tabs=yaml#skipping-ci-for-individual-commits
private readonly string[] _excludedCommitMessages =
{
@@ -37,17 +35,20 @@ public class UpdateDialogViewModel : DialogViewModelBase<bool>
"***NO_CI***"
};
private bool _retrievingChanges;
private readonly INotificationService _notificationService;
private readonly UpdateProvider _updateProvider;
private bool _hasChanges;
private string? _latestBuild;
private bool _retrievingChanges;
public UpdateDialogViewModel(string channel, IUpdateProvider updateProvider, INotificationService notificationService)
{
_updateProvider = (UpdateProvider) updateProvider;
_notificationService = notificationService;
Channel = channel;
CurrentBuild = Core.Constants.BuildInfo.BuildNumberDisplay;
CurrentBuild = Constants.BuildInfo.BuildNumberDisplay;
this.WhenActivated((CompositeDisposable _) => Dispatcher.UIThread.InvokeAsync(GetBuildChanges));
Install = ReactiveCommand.Create(() => Close(true));
@@ -59,7 +60,7 @@ public class UpdateDialogViewModel : DialogViewModelBase<bool>
public string Channel { get; }
public string CurrentBuild { get; }
public ObservableCollection<string> Changes { get; } = new();
public bool RetrievingChanges
@@ -4,61 +4,60 @@ using Artemis.UI.Exceptions;
using Artemis.UI.Windows.SkiaSharp.Vulkan;
using SkiaSharp;
namespace Artemis.UI.Windows.SkiaSharp
namespace Artemis.UI.Windows.SkiaSharp;
public class VulkanContext : IManagedGraphicsContext
{
public class VulkanContext : IManagedGraphicsContext
private readonly GRVkBackendContext _vulkanBackendContext;
private readonly Win32VkContext _vulkanContext;
public VulkanContext()
{
private readonly GRVkBackendContext _vulkanBackendContext;
private readonly Win32VkContext _vulkanContext;
public VulkanContext()
// Try everything in separate try-catch blocks to provide some accuracy in error reporting
try
{
// Try everything in separate try-catch blocks to provide some accuracy in error reporting
try
{
_vulkanContext = new Win32VkContext();
}
catch (Exception e)
{
throw new ArtemisGraphicsContextException("Failed to create Vulkan context", e);
}
try
{
_vulkanBackendContext = new GRVkBackendContext
{
VkInstance = (IntPtr) _vulkanContext.Instance.RawHandle.ToUInt64(),
VkPhysicalDevice = (IntPtr) _vulkanContext.PhysicalDevice.RawHandle.ToUInt64(),
VkDevice = (IntPtr) _vulkanContext.Device.RawHandle.ToUInt64(),
VkQueue = (IntPtr) _vulkanContext.GraphicsQueue.RawHandle.ToUInt64(),
GraphicsQueueIndex = _vulkanContext.GraphicsFamily,
GetProcedureAddress = _vulkanContext.GetProc
};
}
catch (Exception e)
{
throw new ArtemisGraphicsContextException("Failed to create Vulkan backend context", e);
}
try
{
GraphicsContext = GRContext.CreateVulkan(_vulkanBackendContext);
if (GraphicsContext == null)
throw new ArtemisGraphicsContextException("GRContext.CreateVulkan returned null");
}
catch (Exception e)
{
throw new ArtemisGraphicsContextException("Failed to create Vulkan graphics context", e);
}
GraphicsContext.Flush();
_vulkanContext = new Win32VkContext();
}
catch (Exception e)
{
throw new ArtemisGraphicsContextException("Failed to create Vulkan context", e);
}
/// <inheritdoc />
public void Dispose()
try
{
_vulkanBackendContext = new GRVkBackendContext
{
VkInstance = (IntPtr) _vulkanContext.Instance.RawHandle.ToUInt64(),
VkPhysicalDevice = (IntPtr) _vulkanContext.PhysicalDevice.RawHandle.ToUInt64(),
VkDevice = (IntPtr) _vulkanContext.Device.RawHandle.ToUInt64(),
VkQueue = (IntPtr) _vulkanContext.GraphicsQueue.RawHandle.ToUInt64(),
GraphicsQueueIndex = _vulkanContext.GraphicsFamily,
GetProcedureAddress = _vulkanContext.GetProc
};
}
catch (Exception e)
{
throw new ArtemisGraphicsContextException("Failed to create Vulkan backend context", e);
}
public GRContext GraphicsContext { get; }
try
{
GraphicsContext = GRContext.CreateVulkan(_vulkanBackendContext);
if (GraphicsContext == null)
throw new ArtemisGraphicsContextException("GRContext.CreateVulkan returned null");
}
catch (Exception e)
{
throw new ArtemisGraphicsContextException("Failed to create Vulkan graphics context", e);
}
GraphicsContext.Flush();
}
/// <inheritdoc />
public void Dispose()
{
}
public GRContext GraphicsContext { get; }
}
File diff suppressed because it is too large. Load diff
@@ -3,233 +3,232 @@ using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
namespace Artemis.UI.Windows.Utilities
namespace Artemis.UI.Windows.Utilities;
public static class ProcessUtilities
{
public static class ProcessUtilities
public static Process? RunAsDesktopUser(string fileName, string arguments, bool hideWindow)
{
public static Process? RunAsDesktopUser(string fileName, string arguments, bool hideWindow)
if (string.IsNullOrWhiteSpace(fileName))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(fileName));
// To start process as shell user you will need to carry out these steps:
// 1. Enable the SeIncreaseQuotaPrivilege in your current token
// 2. Get an HWND representing the desktop shell (GetShellWindow)
// 3. Get the Process ID(PID) of the process associated with that window(GetWindowThreadProcessId)
// 4. Open that process(OpenProcess)
// 5. Get the access token from that process (OpenProcessToken)
// 6. Make a primary token with that token(DuplicateTokenEx)
// 7. Start the new process with that primary token(CreateProcessWithTokenW)
IntPtr hProcessToken = IntPtr.Zero;
// Enable SeIncreaseQuotaPrivilege in this process. (This won't work if current process is not elevated.)
try
{
if (string.IsNullOrWhiteSpace(fileName))
throw new ArgumentException("Value cannot be null or whitespace.", nameof(fileName));
// To start process as shell user you will need to carry out these steps:
// 1. Enable the SeIncreaseQuotaPrivilege in your current token
// 2. Get an HWND representing the desktop shell (GetShellWindow)
// 3. Get the Process ID(PID) of the process associated with that window(GetWindowThreadProcessId)
// 4. Open that process(OpenProcess)
// 5. Get the access token from that process (OpenProcessToken)
// 6. Make a primary token with that token(DuplicateTokenEx)
// 7. Start the new process with that primary token(CreateProcessWithTokenW)
IntPtr hProcessToken = IntPtr.Zero;
// Enable SeIncreaseQuotaPrivilege in this process. (This won't work if current process is not elevated.)
try
{
IntPtr process = GetCurrentProcess();
if (!OpenProcessToken(process, 0x0020, ref hProcessToken))
return null;
TOKEN_PRIVILEGES tkp = new()
{
PrivilegeCount = 1,
Privileges = new LUID_AND_ATTRIBUTES[1]
};
if (!LookupPrivilegeValue(null, "SeIncreaseQuotaPrivilege", ref tkp.Privileges[0].Luid))
return null;
tkp.Privileges[0].Attributes = 0x00000002;
if (!AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero))
return null;
}
finally
{
CloseHandle(hProcessToken);
}
// Get an HWND representing the desktop shell.
// CAVEATS: This will fail if the shell is not running (crashed or terminated), or the default shell has been
// replaced with a custom shell. This also won't return what you probably want if Explorer has been terminated and
// restarted elevated.
IntPtr hwnd = GetShellWindow();
if (hwnd == IntPtr.Zero)
IntPtr process = GetCurrentProcess();
if (!OpenProcessToken(process, 0x0020, ref hProcessToken))
return null;
IntPtr hShellProcess = IntPtr.Zero;
IntPtr hShellProcessToken = IntPtr.Zero;
IntPtr hPrimaryToken = IntPtr.Zero;
try
TOKEN_PRIVILEGES tkp = new()
{
// Get the PID of the desktop shell process.
uint dwPID;
if (GetWindowThreadProcessId(hwnd, out dwPID) == 0)
return null;
PrivilegeCount = 1,
Privileges = new LUID_AND_ATTRIBUTES[1]
};
// Open the desktop shell process in order to query it (get the token)
hShellProcess = OpenProcess(ProcessAccessFlags.QueryInformation, false, dwPID);
if (hShellProcess == IntPtr.Zero)
return null;
if (!LookupPrivilegeValue(null, "SeIncreaseQuotaPrivilege", ref tkp.Privileges[0].Luid))
return null;
// Get the process token of the desktop shell.
if (!OpenProcessToken(hShellProcess, 0x0002, ref hShellProcessToken))
return null;
tkp.Privileges[0].Attributes = 0x00000002;
uint dwTokenRights = 395U;
if (!AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero))
return null;
}
finally
{
CloseHandle(hProcessToken);
}
// Duplicate the shell's process token to get a primary token.
// Based on experimentation, this is the minimal set of rights required for CreateProcessWithTokenW (contrary to current documentation).
if (!DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out hPrimaryToken))
return null;
// Get an HWND representing the desktop shell.
// CAVEATS: This will fail if the shell is not running (crashed or terminated), or the default shell has been
// replaced with a custom shell. This also won't return what you probably want if Explorer has been terminated and
// restarted elevated.
IntPtr hwnd = GetShellWindow();
if (hwnd == IntPtr.Zero)
return null;
// Start the target process with the new token.
STARTUPINFO si = new();
if (hideWindow)
{
si.dwFlags = 0x00000001;
si.wShowWindow = 0;
}
IntPtr hShellProcess = IntPtr.Zero;
IntPtr hShellProcessToken = IntPtr.Zero;
IntPtr hPrimaryToken = IntPtr.Zero;
try
{
// Get the PID of the desktop shell process.
uint dwPID;
if (GetWindowThreadProcessId(hwnd, out dwPID) == 0)
return null;
PROCESS_INFORMATION pi = new();
if (!CreateProcessWithTokenW(hPrimaryToken, 0, fileName, $"\"{fileName}\" {arguments}", 0, IntPtr.Zero, Path.GetDirectoryName(fileName)!, ref si, out pi))
{
// Get the last error and display it.
int error = Marshal.GetLastWin32Error();
return null;
}
// Open the desktop shell process in order to query it (get the token)
hShellProcess = OpenProcess(ProcessAccessFlags.QueryInformation, false, dwPID);
if (hShellProcess == IntPtr.Zero)
return null;
return Process.GetProcessById(pi.dwProcessId);
}
finally
// Get the process token of the desktop shell.
if (!OpenProcessToken(hShellProcess, 0x0002, ref hShellProcessToken))
return null;
uint dwTokenRights = 395U;
// Duplicate the shell's process token to get a primary token.
// Based on experimentation, this is the minimal set of rights required for CreateProcessWithTokenW (contrary to current documentation).
if (!DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out hPrimaryToken))
return null;
// Start the target process with the new token.
STARTUPINFO si = new();
if (hideWindow)
{
CloseHandle(hShellProcessToken);
CloseHandle(hPrimaryToken);
CloseHandle(hShellProcess);
si.dwFlags = 0x00000001;
si.wShowWindow = 0;
}
PROCESS_INFORMATION pi = new();
if (!CreateProcessWithTokenW(hPrimaryToken, 0, fileName, $"\"{fileName}\" {arguments}", 0, IntPtr.Zero, Path.GetDirectoryName(fileName)!, ref si, out pi))
{
// Get the last error and display it.
int error = Marshal.GetLastWin32Error();
return null;
}
return Process.GetProcessById(pi.dwProcessId);
}
#region Interop
private struct TOKEN_PRIVILEGES
finally
{
public uint PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public LUID_AND_ATTRIBUTES[] Privileges;
CloseHandle(hShellProcessToken);
CloseHandle(hPrimaryToken);
CloseHandle(hShellProcess);
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
private struct LUID
{
public readonly uint LowPart;
public readonly int HighPart;
}
[Flags]
private enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VirtualMemoryOperation = 0x00000008,
VirtualMemoryRead = 0x00000010,
VirtualMemoryWrite = 0x00000020,
DuplicateHandle = 0x00000040,
CreateProcess = 0x000000080,
SetQuota = 0x00000100,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
QueryLimitedInformation = 0x00001000,
Synchronize = 0x00100000
}
private enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
private enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION
{
public readonly IntPtr hProcess;
public readonly IntPtr hThread;
public readonly int dwProcessId;
public readonly int dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct STARTUPINFO
{
public readonly int cb;
public readonly string lpReserved;
public readonly string lpDesktop;
public readonly string lpTitle;
public readonly int dwX;
public readonly int dwY;
public readonly int dwXSize;
public readonly int dwYSize;
public readonly int dwXCountChars;
public readonly int dwYCountChars;
public readonly int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public readonly short cbReserved2;
public readonly IntPtr lpReserved2;
public readonly IntPtr hStdInput;
public readonly IntPtr hStdOutput;
public readonly IntPtr hStdError;
}
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LookupPrivilegeValue(string? host, string name, ref LUID pluid);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
private static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TOKEN_PRIVILEGES newst, int len, IntPtr prev, IntPtr relen);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("user32.dll")]
private static extern IntPtr GetShellWindow();
[DllImport("user32.dll", SetLastError = true)]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, uint processId);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL impersonationLevel, TOKEN_TYPE tokenType,
out IntPtr phNewToken);
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool CreateProcessWithTokenW(IntPtr hToken, int dwLogonFlags, string lpApplicationName, string lpCommandLine, int dwCreationFlags, IntPtr lpEnvironment,
string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
#endregion
}
#region Interop
private struct TOKEN_PRIVILEGES
{
public uint PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public LUID_AND_ATTRIBUTES[] Privileges;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
private struct LUID_AND_ATTRIBUTES
{
public LUID Luid;
public uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
private struct LUID
{
public readonly uint LowPart;
public readonly int HighPart;
}
[Flags]
private enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VirtualMemoryOperation = 0x00000008,
VirtualMemoryRead = 0x00000010,
VirtualMemoryWrite = 0x00000020,
DuplicateHandle = 0x00000040,
CreateProcess = 0x000000080,
SetQuota = 0x00000100,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
QueryLimitedInformation = 0x00001000,
Synchronize = 0x00100000
}
private enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
private enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION
{
public readonly IntPtr hProcess;
public readonly IntPtr hThread;
public readonly int dwProcessId;
public readonly int dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct STARTUPINFO
{
public readonly int cb;
public readonly string lpReserved;
public readonly string lpDesktop;
public readonly string lpTitle;
public readonly int dwX;
public readonly int dwY;
public readonly int dwXSize;
public readonly int dwYSize;
public readonly int dwXCountChars;
public readonly int dwYCountChars;
public readonly int dwFillAttribute;
public int dwFlags;
public short wShowWindow;
public readonly short cbReserved2;
public readonly IntPtr lpReserved2;
public readonly IntPtr hStdInput;
public readonly IntPtr hStdOutput;
public readonly IntPtr hStdError;
}
[DllImport("kernel32.dll", ExactSpelling = true)]
private static extern IntPtr GetCurrentProcess();
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr phtok);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool LookupPrivilegeValue(string? host, string name, ref LUID pluid);
[DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)]
private static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TOKEN_PRIVILEGES newst, int len, IntPtr prev, IntPtr relen);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("user32.dll")]
private static extern IntPtr GetShellWindow();
[DllImport("user32.dll", SetLastError = true)]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, uint processId);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern bool DuplicateTokenEx(IntPtr hExistingToken, uint dwDesiredAccess, IntPtr lpTokenAttributes, SECURITY_IMPERSONATION_LEVEL impersonationLevel, TOKEN_TYPE tokenType,
out IntPtr phNewToken);
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool CreateProcessWithTokenW(IntPtr hToken, int dwLogonFlags, string lpApplicationName, string lpCommandLine, int dwCreationFlags, IntPtr lpEnvironment,
string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
#endregion
}
@@ -1,23 +1,22 @@
using System;
using System.Runtime.InteropServices;
namespace Artemis.UI.Windows.Utilities
namespace Artemis.UI.Windows.Utilities;
public static class WindowUtilities
{
public static class WindowUtilities
public static int GetActiveProcessId()
{
public static int GetActiveProcessId()
{
// Get foreground window handle
IntPtr hWnd = GetForegroundWindow();
// Get foreground window handle
IntPtr hWnd = GetForegroundWindow();
GetWindowThreadProcessId(hWnd, out uint processId);
return (int) processId;
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
GetWindowThreadProcessId(hWnd, out uint processId);
return (int) processId;
}
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
}