Merge pull request #2816 from sylveon/master

[WIP - DO NOT MERGE] Refactor Start with Windows settings into a factory and interface
This commit is contained in:
Jaex 2017-10-05 01:30:11 +03:00 committed by GitHub
commit 07943143fc
16 changed files with 153 additions and 280 deletions

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
</configuration>

View file

@ -26,74 +26,16 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using Windows.ApplicationModel;
namespace DesktopBridgeHelper
{
internal class Program
{
private const string TaskID = "ShareX";
private static int Main(string[] args)
{
return MainAsync(args).GetAwaiter().GetResult();
}
private async static Task<int> MainAsync(string[] args)
{
try
{
if (args.Length > 0)
{
string argument = args[0];
if (argument.Equals("-StartupState", StringComparison.InvariantCultureIgnoreCase))
{
return (int)await GetStartupState();
}
else if (argument.Equals("-StartupEnable", StringComparison.InvariantCultureIgnoreCase))
{
return (int)await SetStartupState(true);
}
else if (argument.Equals("-StartupDisable", StringComparison.InvariantCultureIgnoreCase))
{
return (int)await SetStartupState(false);
}
}
else
{
string path = GetAbsolutePath("ShareX.exe");
Process.Start(path, "-silent");
return 0;
}
}
catch
{
}
return -1;
}
private async static Task<StartupTaskState> GetStartupState()
{
StartupTask startupTask = await StartupTask.GetAsync(TaskID);
return startupTask.State;
}
private async static Task<StartupTaskState> SetStartupState(bool enable)
{
StartupTask startupTask = await StartupTask.GetAsync(TaskID);
if (enable)
{
return await startupTask.RequestEnableAsync();
}
else
{
startupTask.Disable();
return StartupTaskState.Disabled;
}
string path = GetAbsolutePath("ShareX.exe");
Process.Start(path, "-silent");
return 0;
}
private static string GetAbsolutePath(string path)

View file

@ -37,27 +37,10 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll</HintPath>
</Reference>
<Reference Include="Windows, Version=255.255.255.255, Culture=neutral, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Facade\Windows.WinMD</HintPath>
</Reference>
<Reference Include="Windows.ApplicationModel.StartupTaskContract">
<HintPath>C:\Program Files (x86)\Windows Kits\10\References\10.0.15063.0\Windows.ApplicationModel.StartupTaskContract\1.0.0.0\Windows.ApplicationModel.StartupTaskContract.winmd</HintPath>
</Reference>
<Reference Include="Windows.Foundation.FoundationContract">
<HintPath>C:\Program Files (x86)\Windows Kits\10\References\10.0.15063.0\Windows.Foundation.FoundationContract\3.0.0.0\Windows.Foundation.FoundationContract.winmd</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View file

@ -262,7 +262,6 @@ public enum RegionCaptureType
public enum StartupTaskState
{
Error = -1,
Disabled = 0,
DisabledByUser = 1,
Enabled = 2

View file

@ -25,6 +25,7 @@
using ShareX.HelpersLib;
using ShareX.Properties;
using ShareX.StartupManagers;
using ShareX.UploadersLib;
using System;
using System.Drawing;
@ -40,6 +41,8 @@ public partial class ApplicationSettingsForm : Form
private bool ready;
private string lastPersonalPath;
private IStartupManager startupManager = StartupManagerFactory.GetStartupManager();
public ApplicationSettingsForm()
{
InitializeControls();
@ -70,12 +73,10 @@ private void SettingsForm_FormClosed(object sender, FormClosedEventArgs e)
private void tttvMain_TabChanged(TabPage tabPage)
{
#if WindowsStore
if (tabPage == tpIntegration)
{
CheckWindowsStoreStartup();
UpdateStartWithWindows();
}
#endif
}
private void InitializeControls()
@ -131,13 +132,11 @@ private void UpdateControls()
// Integration
#if WindowsStore
cbStartWithWindows.Enabled = false;
cbShellContextMenu.Visible = false;
cbSendToMenu.Visible = false;
gbChrome.Visible = false;
gbFirefox.Visible = false;
#else
cbStartWithWindows.Checked = IntegrationHelpers.CheckStartupShortcut();
cbShellContextMenu.Checked = IntegrationHelpers.CheckShellContextMenuButton();
cbSendToMenu.Checked = IntegrationHelpers.CheckSendToMenuButton();
cbChromeExtensionSupport.Checked = IntegrationHelpers.CheckChromeExtensionSupport();
@ -251,6 +250,17 @@ private void ChangeLanguage(SupportedLanguage language)
}
}
private void UpdateStartWithWindows()
{
StartupTaskState state = startupManager.State;
cbStartWithWindows.Checked = state == StartupTaskState.Enabled;
if (state == StartupTaskState.DisabledByUser)
{
cbStartWithWindows.Enabled = false;
lblWindowsStoreStartupStatus.Text = Resources.ApplicationSettingsForm_lblWindowsStoreStartupStatus_DisabledByUser;
}
}
private void UpdateProxyControls()
{
switch (Program.Settings.ProxySettings.ProxyMethod)
@ -301,78 +311,6 @@ private void UpdateExportButton()
btnExport.Enabled = Program.Settings.ExportSettings || Program.Settings.ExportHistory || Program.Settings.ExportLogs;
}
private void CheckWindowsStoreStartup()
{
if (cbStartWithWindows.Enabled) return;
lblWindowsStoreStartupStatus.Text = "Checking startup state...";
lblWindowsStoreStartupStatus.Visible = true;
StartupTaskState state = StartupTaskState.Error;
TaskEx.Run(() =>
{
state = IntegrationHelpers.CheckStartupWindowsStore();
},
() =>
{
if (!IsDisposed)
{
if (state == StartupTaskState.Error)
{
lblWindowsStoreStartupStatus.Text = "Startup state check failed. Check debug log for more info.";
}
else if (state == StartupTaskState.DisabledByUser)
{
lblWindowsStoreStartupStatus.Text = "The startup has been disabled by the user.";
}
else
{
lblWindowsStoreStartupStatus.Visible = false;
cbStartWithWindows.Checked = state == StartupTaskState.Enabled;
cbStartWithWindows.Enabled = true;
}
}
});
}
private void ConfigureWindowsStoreStartup()
{
if (cbStartWithWindows.Enabled)
{
cbStartWithWindows.Enabled = false;
lblWindowsStoreStartupStatus.Text = "Configuring startup...";
lblWindowsStoreStartupStatus.Visible = true;
bool enable = cbStartWithWindows.Checked;
StartupTaskState state = StartupTaskState.Error;
TaskEx.Run(() =>
{
state = IntegrationHelpers.ConfigureStartupWindowsStore(enable);
},
() =>
{
if (!IsDisposed)
{
if (state == StartupTaskState.Error)
{
lblWindowsStoreStartupStatus.Text = "Startup configuration failed. Check debug log for more info.";
}
else if (state == StartupTaskState.DisabledByUser)
{
lblWindowsStoreStartupStatus.Text = "The startup has been disabled by the user.";
}
else
{
lblWindowsStoreStartupStatus.Visible = false;
cbStartWithWindows.Enabled = true;
}
}
});
}
}
#region General
private void cbShowTray_CheckedChanged(object sender, EventArgs e)
@ -450,11 +388,7 @@ private void cbStartWithWindows_CheckedChanged(object sender, EventArgs e)
{
if (ready)
{
#if WindowsStore
ConfigureWindowsStoreStartup();
#else
IntegrationHelpers.CreateStartupShortcut(cbStartWithWindows.Checked);
#endif
startupManager.State = cbStartWithWindows.Checked ? StartupTaskState.Enabled : StartupTaskState.Disabled;
}
}

View file

@ -24,6 +24,7 @@
#endregion License Information (GPL v3)
using ShareX.HelpersLib;
using ShareX.StartupManagers;
using System;
using System.Windows.Forms;
@ -32,13 +33,17 @@ namespace ShareX
public partial class FirstTimeConfigForm : BlackStyleForm
{
private bool loaded;
private IStartupManager startupManager = StartupManagerFactory.GetStartupManager();
public FirstTimeConfigForm()
{
InitializeComponent();
pbLogo.Image = ImageHelpers.ResizeImage(ShareXResources.Logo, 128, 128);
StartupTaskState state = startupManager.State;
cbRunStartup.Checked = state == StartupTaskState.Enabled;
cbRunStartup.Enabled = state != StartupTaskState.DisabledByUser;
cbRunStartup.Checked = IntegrationHelpers.CheckStartupShortcut();
cbShellContextMenuButton.Checked = IntegrationHelpers.CheckShellContextMenuButton();
cbSendToMenu.Checked = IntegrationHelpers.CheckSendToMenuButton();
@ -60,7 +65,7 @@ private void cbRunStartup_CheckedChanged(object sender, EventArgs e)
{
if (loaded)
{
IntegrationHelpers.CreateStartupShortcut(cbRunStartup.Checked);
startupManager.State = cbRunStartup.Checked ? StartupTaskState.Enabled : StartupTaskState.Disabled;
}
}

View file

@ -27,6 +27,7 @@
using Newtonsoft.Json;
using ShareX.HelpersLib;
using ShareX.Properties;
using ShareX.StartupManagers;
using System;
using System.Diagnostics;
using System.IO;
@ -40,16 +41,6 @@ public static class IntegrationHelpers
private static readonly string ApplicationName = "ShareX";
private static readonly string ApplicationPath = string.Format("\"{0}\"", Application.ExecutablePath);
private static readonly string StartupTargetPath =
#if STEAM
Helpers.GetAbsolutePath("../ShareX_Launcher.exe");
#else
Application.ExecutablePath;
#endif
private static readonly string StartupRegistryPath = @"Software\Microsoft\Windows\CurrentVersion\Run";
private static readonly string StartupRegistryValue = $"\"{StartupTargetPath}\" -silent";
private static readonly string ShellExtMenuFiles = @"Software\Classes\*\shell\" + ApplicationName;
private static readonly string ShellExtMenuFilesCmd = ShellExtMenuFiles + @"\command";
@ -75,106 +66,6 @@ public static class IntegrationHelpers
private static readonly string ChromeNativeMessagingHosts = @"SOFTWARE\Google\Chrome\NativeMessagingHosts\com.getsharex.sharex";
private static readonly string FirefoxNativeMessagingHosts = @"SOFTWARE\Mozilla\NativeMessagingHosts\ShareX";
public static bool CheckStartupShortcut()
{
return ShortcutHelpers.CheckShortcut(Environment.SpecialFolder.Startup, StartupTargetPath);
}
public static bool CreateStartupShortcut(bool create)
{
return ShortcutHelpers.SetShortcut(create, Environment.SpecialFolder.Startup, StartupTargetPath, "-silent");
}
public static bool CheckStartWithWindows()
{
try
{
return RegistryHelpers.CheckRegistry(StartupRegistryPath, ApplicationName, StartupRegistryValue);
}
catch (Exception e)
{
DebugHelper.WriteException(e);
}
return false;
}
public static void CreateStartWithWindows(bool create)
{
try
{
using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(StartupRegistryPath, true))
{
if (rk != null)
{
if (create)
{
rk.SetValue(ApplicationName, StartupRegistryValue, RegistryValueKind.String);
}
else
{
rk.DeleteValue(ApplicationName, false);
}
}
}
}
catch (Exception e)
{
DebugHelper.WriteException(e);
}
}
private static StartupTaskState RunStartupWindowsStore(string argument, string info)
{
string filepath = Helpers.GetAbsolutePath("ShareX_DesktopBridgeHelper.exe");
if (!string.IsNullOrEmpty(filepath) && File.Exists(filepath))
{
try
{
DebugHelper.WriteLine($"Start: {filepath} {argument}");
ProcessStartInfo startInfo = new ProcessStartInfo()
{
FileName = filepath,
Arguments = argument,
UseShellExecute = false,
CreateNoWindow = true
};
Process process = Process.Start(startInfo);
if (process.WaitForExit(5000))
{
int code = process.ExitCode;
DebugHelper.WriteLine($"{info} result: {code}");
if (code > -1)
{
return (StartupTaskState)code;
}
}
}
catch (Exception e)
{
DebugHelper.WriteException(e, $"{info} failed");
}
}
return StartupTaskState.Error;
}
public static StartupTaskState CheckStartupWindowsStore()
{
return RunStartupWindowsStore("-StartupState", "Startup state check");
}
public static StartupTaskState ConfigureStartupWindowsStore(bool enable)
{
return RunStartupWindowsStore(enable ? "-StartupEnable" : "-StartupDisable", "Startup configuration");
}
public static bool CheckShellContextMenuButton()
{
try
@ -459,7 +350,7 @@ public static void SteamShowInApp(bool showInApp)
public static void Uninstall()
{
CreateStartupShortcut(false);
StartupManagerFactory.GetStartupManager().State = StartupTaskState.Disabled;
CreateShellContextMenuButton(false);
CreateCustomUploaderExtension(false);
CreateSendToMenuButton(false);

View file

@ -474,6 +474,15 @@ public class Resources {
}
}
/// <summary>
/// Looks up a localized string similar to Startup has been disabled in Task Manager..
/// </summary>
public static string ApplicationSettingsForm_lblWindowsStoreStartupStatus_DisabledByUser {
get {
return ResourceManager.GetString("ApplicationSettingsForm_lblWindowsStoreStartupStatus_DisabledByUser", resourceCulture);
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>

View file

@ -960,4 +960,7 @@ Middle click to close</value>
<data name="QRCodeForm_InputTextToEncode" xml:space="preserve">
<value>Input text to encode</value>
</data>
<data name="ApplicationSettingsForm_lblWindowsStoreStartupStatus_DisabledByUser" xml:space="preserve">
<value>Startup has been disabled in Task Manager.</value>
</data>
</root>

View file

@ -83,6 +83,7 @@
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'WindowsStoreDebug|AnyCPU'">
<DebugSymbols>true</DebugSymbols>
@ -93,6 +94,7 @@
<GenerateSerializationAssemblies>Off</GenerateSerializationAssemblies>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.VisualBasic" />
@ -110,10 +112,18 @@
<Reference Include="System.Data" />
<Reference Include="System.Design" />
<Reference Include="System.Drawing" />
<Reference Include="System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL" Condition="'$(Configuration)' == 'WindowsStore' Or '$(Configuration)' == 'WindowsStoreDebug'">
<SpecificVersion>False</SpecificVersion>
<HintPath>$(MSBuildProgramFiles32)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll</HintPath>
</Reference>
<Reference Include="System.Speech" />
<Reference Include="System.Web" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
<Reference Include="Windows" Condition="'$(Configuration)' == 'WindowsStore' Or '$(Configuration)' == 'WindowsStoreDebug'">
<HintPath>$(MSBuildProgramFiles32)\Windows Kits\10\UnionMetadata\Windows.winmd</HintPath>
<Private>False</Private>
</Reference>
<Reference Include="zxing, Version=0.16.0.0, Culture=neutral, PublicKeyToken=830ae994e36ac27d, processorArchitecture=MSIL">
<HintPath>..\packages\ZXing.Net.0.16.0\lib\net40\zxing.dll</HintPath>
</Reference>
@ -309,6 +319,12 @@
</Compile>
<Compile Include="LanguageHelper.cs" />
<Compile Include="RecentTaskManager.cs" />
<Compile Include="StartupManagers\CentennialStartupManager.cs" />
<Compile Include="StartupManagers\DesktopStartupManager.cs" />
<Compile Include="StartupManagers\GenericStartupManager.cs" />
<Compile Include="StartupManagers\IStartupManager.cs" />
<Compile Include="StartupManagers\StartupManagerFactory.cs" />
<Compile Include="StartupManagers\SteamDesktopManager.cs" />
<Compile Include="TaskHelpers.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />

View file

@ -0,0 +1,31 @@
#if WindowsStore
using System;
using Windows.ApplicationModel;
namespace ShareX.StartupManagers
{
public class CentennialStartupManager : IStartupManager
{
public int StartupTargetIndex;
public StartupTaskState State
{
get => (StartupTaskState)StartupTask.GetForCurrentPackageAsync().GetResults()[StartupTargetIndex].State;
set
{
if (value == StartupTaskState.Enabled)
{
StartupTask.GetForCurrentPackageAsync().GetResults()[StartupTargetIndex].RequestEnableAsync().GetResults();
}
else if (value == StartupTaskState.Disabled)
{
StartupTask.GetForCurrentPackageAsync().GetResults()[StartupTargetIndex].Disable();
}
else
{
throw new NotSupportedException();
}
}
}
}
}
#endif

View file

@ -0,0 +1,9 @@
using System.Windows.Forms;
namespace ShareX.StartupManagers
{
public class DesktopStartupManager : GenericStartupManager
{
public override string StartupTargetPath() => Application.ExecutablePath;
}
}

View file

@ -0,0 +1,25 @@
using ShareX.HelpersLib;
using System;
namespace ShareX.StartupManagers
{
public abstract class GenericStartupManager : IStartupManager
{
abstract public string StartupTargetPath();
public StartupTaskState State
{
get => ShortcutHelpers.CheckShortcut(Environment.SpecialFolder.Startup, StartupTargetPath()) ? StartupTaskState.Enabled : StartupTaskState.Disabled;
set
{
if (value == StartupTaskState.Enabled || value == StartupTaskState.Disabled)
{
ShortcutHelpers.SetShortcut(value == StartupTaskState.Enabled, Environment.SpecialFolder.Startup, StartupTargetPath(), "-silent");
}
else
{
throw new NotSupportedException();
}
}
}
}
}

View file

@ -0,0 +1,7 @@
namespace ShareX.StartupManagers
{
public interface IStartupManager
{
StartupTaskState State { get; set; }
}
}

View file

@ -0,0 +1,16 @@
namespace ShareX.StartupManagers
{
public class StartupManagerFactory
{
public static IStartupManager GetStartupManager()
{
#if WindowsStore
return new CentennialStartupManager();
#elif STEAM
return new SteamStartupManager();
#else
return new DesktopStartupManager();
#endif
}
}
}

View file

@ -0,0 +1,9 @@
using ShareX.HelpersLib;
namespace ShareX.StartupManagers
{
public class SteamStartupManager : GenericStartupManager
{
public override string StartupTargetPath() => Helpers.GetAbsolutePath("../ShareX_Launcher.exe");
}
}