Skip to content

Commit

Permalink
Move constants/runtime constants
Browse files Browse the repository at this point in the history
Makes them shared between SoundManager and DownloadSchemes
  • Loading branch information
ORelio committed Feb 27, 2024
1 parent b871aca commit aaebddc
Show file tree
Hide file tree
Showing 10 changed files with 179 additions and 83 deletions.
3 changes: 3 additions & 0 deletions DownloadSchemes/DownloadSchemes.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,9 @@
<Compile Include="..\SoundManager\WindowsVersion.cs">
<Link>WindowsVersion.cs</Link>
</Compile>
<Compile Include="..\SoundManager\RuntimeConfig.cs">
<Link>RuntimeConfig.cs</Link>
</Compile>
<Compile Include="FormDownload.cs">
<SubType>Form</SubType>
</Compile>
Expand Down
66 changes: 27 additions & 39 deletions DownloadSchemes/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.IO;
using System.Diagnostics;
using SharpTools;
using SoundManager;

namespace DownloadSchemes
{
Expand All @@ -15,20 +16,7 @@ namespace DownloadSchemes
/// </summary>
static class Program
{
const string RepoUsername = "ORelio";
const string RepoName = "Sound-Manager-Schemes";
const string RepoUrl = "https://github.com/" + RepoUsername + "/" + RepoName + "/";
const string SoundManagerExe = "SoundManager.exe";
const string SoundSchemeIcon = "SoundScheme.ico";

static readonly string UninstallProgram = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Uninstall.exe");
static readonly bool PortableMode = !File.Exists(UninstallProgram);
static readonly string TempListFile = Path.Combine(Path.GetTempPath(), RepoName.ToLowerInvariant() + ".txt");
static readonly bool RunningWindows11 = WindowsVersion.FriendlyName.ToLowerInvariant().Contains("windows 11");
static readonly string WindowsNtVersion = String.Format("{0}.{1}", WindowsVersion.WinMajorVersion, WindowsVersion.WinMinorVersion) + (RunningWindows11 ? "_11" : "");
static readonly string SchemesFolder = PortableMode
? Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Schemes")
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyMusic), Translations.Get("app_name"));
static readonly string SchemesListTempFile = Path.Combine(Path.GetTempPath(), RuntimeConfig.SchemesRepositoryName.ToLowerInvariant() + ".txt");

static readonly Dictionary<string, string> SchemesPerNtVersion = new Dictionary<string, string>
{
Expand Down Expand Up @@ -59,19 +47,19 @@ static void Main()
}
catch (NotSupportedException)
{
FailureOfferWebpage("download_schemes_no_tls_title", "download_schemes_no_tls_text", RepoUrl);
FailureOfferWebpage("download_schemes_no_tls_title", "download_schemes_no_tls_text", RuntimeConfig.SchemesRepositoryUrl);
return;
}

// Build a list of schemes to select by default
// On first launch, the pre-selected scheme is the best suited one for the current OS version
// On subsequent launches, already downloaded schemes are pre-selected: un-checking them will delete the files
List<string> selectedSchemes = new List<string>();
if (Directory.Exists(SchemesFolder))
foreach (string scheme in Directory.GetFiles(SchemesFolder))
if (Directory.Exists(RuntimeConfig.SchemesFolder))
foreach (string scheme in Directory.GetFiles(RuntimeConfig.SchemesFolder))
selectedSchemes.Add(Path.GetFileName(scheme));
else if (SchemesPerNtVersion.ContainsKey(WindowsNtVersion))
selectedSchemes.Add(SchemesPerNtVersion[WindowsNtVersion]);
else if (SchemesPerNtVersion.ContainsKey(RuntimeConfig.WindowsNtVersion))
selectedSchemes.Add(SchemesPerNtVersion[RuntimeConfig.WindowsNtVersion]);

// Prompt user for list of schemes to download
FormSelectFiles formSelectFiles = new FormSelectFiles(
Expand All @@ -90,7 +78,7 @@ static void Main()
// Failure? Open in web browser?
if (!formSelectFiles.Success)
{
FailureOfferWebpage("download_schemes_failed_title", "download_schemes_failed_text", RepoUrl);
FailureOfferWebpage("download_schemes_failed_title", "download_schemes_failed_text", RuntimeConfig.SchemesRepositoryUrl);
return;
}

Expand All @@ -99,7 +87,7 @@ static void Main()
{
foreach (string url in formSelectFiles.UnselectedResults)
{
string localPath = Path.Combine(SchemesFolder, Path.GetFileName(url));
string localPath = Path.Combine(RuntimeConfig.SchemesFolder, Path.GetFileName(url));
if (File.Exists(localPath))
File.Delete(localPath);
}
Expand All @@ -109,20 +97,20 @@ static void Main()
if (formSelectFiles.Results.Count > 0)
{
// Create destination Folder
if (!Directory.Exists(SchemesFolder))
if (!Directory.Exists(RuntimeConfig.SchemesFolder))
{
Directory.CreateDirectory(SchemesFolder);
Directory.CreateDirectory(RuntimeConfig.SchemesFolder);

// Set custom folder icon
if (File.Exists(SoundSchemeIcon) && !PortableMode)
if (File.Exists(RuntimeConfig.SoundSchemeIcon) && !RuntimeConfig.RunningInPortableMode)
{
string desktopIniFile = Path.Combine(SchemesFolder, "desktop.ini");
string desktopIniFile = Path.Combine(RuntimeConfig.SchemesFolder, "desktop.ini");
File.WriteAllLines(desktopIniFile, new[] {
"[.ShellClassInfo]",
"IconFile=" + Path.GetFullPath(SoundSchemeIcon),
"IconFile=" + Path.GetFullPath(RuntimeConfig.SoundSchemeIcon),
"IconIndex=0"
});
DirectoryInfo dirInfo = new DirectoryInfo(SchemesFolder);
DirectoryInfo dirInfo = new DirectoryInfo(RuntimeConfig.SchemesFolder);
dirInfo.Attributes |= FileAttributes.System;
FileInfo fileInfo = new FileInfo(desktopIniFile);
fileInfo.Attributes |= FileAttributes.Hidden;
Expand All @@ -133,7 +121,7 @@ static void Main()
List<KeyValuePair<string, string>> schemeDownloads = new List<KeyValuePair<string,string>>();
foreach (string url in formSelectFiles.Results)
{
string localPath = Path.Combine(SchemesFolder, Path.GetFileName(url));
string localPath = Path.Combine(RuntimeConfig.SchemesFolder, Path.GetFileName(url));
if (!File.Exists(localPath))
schemeDownloads.Add(new KeyValuePair<string, string>(url, localPath));
}
Expand All @@ -145,7 +133,7 @@ static void Main()
// Failure? Open in web browser?
if (!formDownload.Success)
{
FailureOfferWebpage("download_schemes_failed_title", "download_schemes_failed_text", RepoUrl);
FailureOfferWebpage("download_schemes_failed_title", "download_schemes_failed_text", RuntimeConfig.SchemesRepositoryUrl);
return;
}

Expand All @@ -155,20 +143,20 @@ static void Main()
schemeFile = schemeDownloads[0].Value;

// If the sound scheme for the current OS is in the set of downloaded files, offer to apply it
if (SchemesPerNtVersion.ContainsKey(WindowsNtVersion)
&& schemeDownloads.Any(scheme => (Path.GetFileName(scheme.Key) == SchemesPerNtVersion[WindowsNtVersion])))
if (SchemesPerNtVersion.ContainsKey(RuntimeConfig.WindowsNtVersion)
&& schemeDownloads.Any(scheme => (Path.GetFileName(scheme.Key) == SchemesPerNtVersion[RuntimeConfig.WindowsNtVersion])))
{
schemeFile = Path.Combine(SchemesFolder, SchemesPerNtVersion[WindowsNtVersion]);
schemeFile = Path.Combine(RuntimeConfig.SchemesFolder, SchemesPerNtVersion[RuntimeConfig.WindowsNtVersion]);
}

// Run SoundManager with the scheme file to offer, or default to opening the Schemes folder
if (schemeFile != null && File.Exists(SoundManagerExe) && File.Exists(schemeFile))
if (schemeFile != null && File.Exists(RuntimeConfig.SoundManagerExe) && File.Exists(schemeFile))
{
Process.Start(SoundManagerExe, String.Format("\"{0}\"", schemeFile));
Process.Start(RuntimeConfig.SoundManagerExe, String.Format("\"{0}\"", schemeFile));
}
else if (schemeDownloads.Count > 0)
{
Process.Start("explorer", '"' + SchemesFolder + '"');
Process.Start("explorer", '"' + RuntimeConfig.SchemesFolder + '"');
}
}
}
Expand Down Expand Up @@ -197,14 +185,14 @@ static void FailureOfferWebpage(string title_translation, string text_translatio
/// <returns>List of sound scheme URLs</returns>
static IEnumerable<string> FetchSchemeList()
{
if (File.Exists(TempListFile) && File.GetLastWriteTime(TempListFile) >= DateTime.Now.AddHours(-1))
if (File.Exists(SchemesListTempFile) && File.GetLastWriteTime(SchemesListTempFile) >= DateTime.Now.AddHours(-1))
{
return File.ReadAllLines(TempListFile);
return File.ReadAllLines(SchemesListTempFile);
}
else
{
IEnumerable<string> urls = GitHubApi.ListFilesInRepo(RepoUsername, RepoName, "/", true).Where(item => item.EndsWith(".ths"));
File.WriteAllLines(TempListFile, urls);
IEnumerable<string> urls = GitHubApi.ListFilesInRepo(RuntimeConfig.SchemesRepositoryUsername, RuntimeConfig.SchemesRepositoryName, "/", true).Where(item => item.EndsWith(".ths"));
File.WriteAllLines(SchemesListTempFile, urls);
return urls;
}
}
Expand Down
16 changes: 8 additions & 8 deletions SoundManager/BgSoundPlayer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,16 @@ namespace SoundManager
/// </summary>
public class BgSoundPlayer : Form
{
private static readonly string LastBootFile = String.Concat(Program.DataFolder, Path.DirectorySeparatorChar, "LastBootTime.ini");
private static readonly string LastBootFile = String.Concat(RuntimeConfig.LocalDataFolder, Path.DirectorySeparatorChar, "LastBootTime.ini");
private static readonly RegistryKey RegistryHKLM64bits = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
private static readonly RegistryKey SystemStartup = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
private static readonly RegistryKey StartupDelay = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Serialize");
private static readonly RegistryKey BootAnimation = RegistryHKLM64bits.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Authentication\\LogonUI\\BootAnimation", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.SetValue);
private static readonly RegistryKey EditionOverrides = RegistryHKLM64bits.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\EditionOverrides", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.SetValue);
private static readonly string StartupCommandExe = String.Concat("\"", Application.ExecutablePath, "\"");
private static readonly string StartupCommand = String.Concat(StartupCommandExe, " ", Program.ArgumentBgSoundPlayer);
private static readonly string StartupCommand = String.Concat(StartupCommandExe, " ", RuntimeConfig.CmdArgumentBgSoundPlayer);
private static readonly string SidCurrentUser = System.Security.Principal.WindowsIdentity.GetCurrent().User.Value;
private static readonly string ScheduledTaskBaseName = Program.InternalName;
private static readonly string ScheduledTaskBaseName = RuntimeConfig.AppInternalName;
private static readonly string ScheduledTaskNameCurrentUser = String.Concat(ScheduledTaskBaseName, "-", SidCurrentUser);
private const string StartupDelay_StartupDelayInMSec = "StartupDelayInMSec";
private const string BootAnimation_DisableStartupSound = "DisableStartupSound";
Expand Down Expand Up @@ -63,7 +63,7 @@ private static bool ShouldToggleBuiltinStartupSound
/// <returns>TRUE when registered on system startup</returns>
public static bool IsRegisteredForStartup()
{
bool registryKeyPresent = (StartupCommand == (SystemStartup.GetValue(Program.InternalName) as string));
bool registryKeyPresent = (StartupCommand == (SystemStartup.GetValue(RuntimeConfig.AppInternalName) as string));
bool taskPresent = false;

try
Expand Down Expand Up @@ -102,7 +102,7 @@ public static void SetRegisteredForStartup(bool registered, bool interactive = f
trigger.UserId = SidCurrentUser;
TaskScheduler.IExecAction action = (TaskScheduler.IExecAction)task.Actions.Create(TaskScheduler._TASK_ACTION_TYPE.TASK_ACTION_EXEC);
action.Path = StartupCommandExe;
action.Arguments = Program.ArgumentBgSoundPlayer;
action.Arguments = RuntimeConfig.CmdArgumentBgSoundPlayer;
task.Settings.DisallowStartIfOnBatteries = false;
task.Settings.StopIfGoingOnBatteries = false;
task.Settings.ExecutionTimeLimit = "PT0S";
Expand Down Expand Up @@ -165,11 +165,11 @@ public static void SetRegisteredForStartup(bool registered, bool interactive = f
}

//Remove registry keys set by previous versions of this program
SystemStartup.DeleteValue(Program.InternalName, false);
SystemStartup.DeleteValue(RuntimeConfig.AppInternalName, false);
StartupDelay.DeleteValue(StartupDelay_StartupDelayInMSec, false);

//Attempt to remove generic scheduled task set by previous versions of this program
try { ts.GetFolder("\\").DeleteTask(Program.InternalName, 0); }
try { ts.GetFolder("\\").DeleteTask(RuntimeConfig.AppInternalName, 0); }
catch (FileNotFoundException) { /* Task was not present */ }
catch (UnauthorizedAccessException) { /* Insufficient privileges */ }
}
Expand Down Expand Up @@ -240,7 +240,7 @@ private static void PlaySound(SoundEvent soundEvent)
/// </summary>
public BgSoundPlayer()
{
this.Text = Program.DisplayName;
this.Text = RuntimeConfig.AppDisplayName;
this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);

this.FormBorderStyle = FormBorderStyle.FixedToolWindow;
Expand Down
10 changes: 5 additions & 5 deletions SoundManager/FormMain.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ public FormMain(string importFile = null)

// Icon and translations

this.Text = Program.DisplayName;
this.Text = RuntimeConfig.AppDisplayName;
this.Icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
tabPageScheme.Text = Translations.Get("tab_current_scheme");
tabPageSettings.Text = Translations.Get("tab_settings");
Expand Down Expand Up @@ -62,8 +62,8 @@ public FormMain(string importFile = null)
buttonReinstall.Text = Translations.Get("button_reinstall");
buttonUninstall.Text = Translations.Get("button_uninstall");
tabPageAbout.Text = Translations.Get("tab_about");
labelProgramName.Text = Program.DisplayName;
labelProgramVersionAuthor.Text = "Version " + Program.Version + " - By ORelio";
labelProgramName.Text = RuntimeConfig.AppDisplayName;
labelProgramVersionAuthor.Text = "Version " + RuntimeConfig.Version + " - By ORelio";
labelTranslationAuthor.Text = Translations.Get("translation_author");
labelProgramDescription.Text = Translations.Get("app_desc");
buttonHelp.Text = Translations.Get("button_help");
Expand All @@ -81,7 +81,7 @@ public FormMain(string importFile = null)
);

labelSystemSupportStatus.Text =
WindowsVersion.IsBetween(Program.WindowsVersionMin, Program.WindowsVersionMax)
WindowsVersion.IsBetween(RuntimeConfig.SupportedWindowsVersionMin, RuntimeConfig.SupportedWindowsVersionMax)
? Translations.Get("supported_system_version")
: Translations.Get("unsupported_system_version");

Expand Down Expand Up @@ -128,7 +128,7 @@ public FormMain(string importFile = null)
// Load system sound schemes list

foreach (SoundScheme scheme in SoundScheme.GetSchemeList())
if (scheme.ToString() != Program.DisplayName && scheme.ToString() != ".None")
if (scheme.ToString() != RuntimeConfig.AppDisplayName && scheme.ToString() != ".None")
comboBoxSystemSchemes.Items.Add(scheme);
if (comboBoxSystemSchemes.Items.Count > 0)
comboBoxSystemSchemes.SelectedIndex = 0;
Expand Down
Loading

0 comments on commit aaebddc

Please sign in to comment.