diff --git a/.gitignore b/.gitignore index 4c407536..d5751c7b 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ installer/syncthing.exe *.tmp Coverage RefitStubs.cs +SyncTrayzorPortable diff --git a/CHANGELOG.txt b/CHANGELOG.txt index 97596c4a..92eb5cd9 100644 --- a/CHANGELOG.txt +++ b/CHANGELOG.txt @@ -1,6 +1,16 @@ Changelog ========= +v1.0.5 +------ + + - Replace syncthing.exe in APPDATA if it goes missing for some reason + - Add option to run Syncthing with a custom home directory + - Add portable build + - Add 'Minimize to Tray' option + - Improve error messages and logging + - Close Synchthing gracefully on application exit + v1.0.4 ------ diff --git a/README.md b/README.md index 2b8299eb..53d92ff1 100644 --- a/README.md +++ b/README.md @@ -11,9 +11,13 @@ Features include: - Has a built-in web browser, so you don't need to fire up an external browser. - Optionally starts on login, so you don't need to set up Syncthing as a service. - - Can watch your folders for changes, and informs Syncthing about them instantly. This means you can have large polling intervals, but still have changes propagated straight await. - - Optional tray messages when folders have finished syncing. + - Can watch your folders for changes, so you don't have to poll them frequently: + - Syncthing on its own has to poll your folders, in order to see if any files have changed. + - SyncTrayzor will watch your folders for changes, and alert Syncthing the second anything changes. + - This means you can increase the polling interval in Syncthing, avoiding the resource usage of high-frequency polling, but still have any changes propagated straight away. + - Folder watching respects the ignores configured in Syncthing. - Tray icon indicates when synchronization is occurring. + - Optional tray messages when folders have finished syncing. ![Screenshot](readme/screenshot.png) @@ -21,7 +25,46 @@ Features include: Installation ------------ -Grab the latest installer from the [releases](https://github.com/canton7/SyncTrayzor/releases) tab. +SyncTrayzor is packged as both an installer and a standalone zip. + +### Installer + +Grab and run the latest installer from the [releases](https://github.com/canton7/SyncTrayzor/releases) tab. +If you already have SyncTrayzor installed, this will update it. + +### Standalone + +First, you'll need .net 4.5. [Download the offline](http://www.microsoft.com/en-gb/download/details.aspx?id=42642) or +[web installer](http://www.microsoft.com/en-gb/download/details.aspx?id=42643) if you don't have it installed already. + +Grab the latest standalone .zip from the [releases](https://github.com/canton7/SyncTrayzor/releases) tab. +Unzip, and run `SyncTrayzor.exe`. If you're updating, you'll need to copy the `data` folder across from your previous standalone installation. + + +What will SyncTrayzor do to my system? +-------------------------------------- + +Good question. The answer depends on whether you installed SyncTrayzor using the installer, or are running it standalone. + +### Installer + +SyncTrayzor will install itself into `C:\Program Files\SyncTrayzor`. + +By default, SyncTrayzor will put its own configuration in `C:\Users\\AppData\Roaming\SyncTrayor`, and let Syncthing use its default folder for its database, which is `C:\Users\\AppData\Local\Syncthing`. +It will also create a registry key at `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\SyncTrayzor` the first time that it is run, which will let it start when you log in. + +You can delete this registry key by unchecking "Automatically start on login" in the settings. + +If you check "Use custom home directory or Syncthing" in the settings, then SyncTrayzor will tell Syncthing to use `C:\Users\\AppData\Local\SyncTrayzor\syncthing` for its database. +This is useful if you want to keep the copy of Syncthing managed by SyncTrayzor separate from another copy running on your machine. + +### Standalone + +SyncTrayzor will put its own configuration in `SyncTrayzorPortable\data`, and tell Syncthing to use `SyncTrayzorPortable\data\syncthing` for its database. +This means that, when upgrading, you can simply move the 'data' folder over to move all your settings, and database. +If you uncheck "Use custom home directory or Syncthing" in the settings, then Syncthing will use its default folder for its database, which is `C:\Users\\AppData\Local\Syncthing`. + +The portable version won't start on login by default. If you check "Automatically start on login" in the settings, then a registry key will be created at `HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run\SyncTrayzor`. Building from Source @@ -29,5 +72,4 @@ Building from Source You'll need [Visual Studio 2013](http://www.visualstudio.com/en-us/news/vs2013-community-vs.aspx). Clone/download the repository, open `src\SyncTrayzor.sln`, and compile. -For Debug builds, you'll need to [download syncthing.exe](https://github.com/syncthing/syncthing/releases) and place it in the `bin\x86\Debug` or `bin\x64\Debug` folder, as appropriate. -For Release builds, you'll need to place it in `%APPDATA%\SyncTrayzor`. \ No newline at end of file +You'll also need to [download syncthing.exe](https://github.com/syncthing/syncthing/releases) and place it in the `bin\x86\Debug`, `bin\x64\Debug`, `bin\x86\Release`, or `bin\x64\Release` folder as appropriate. \ No newline at end of file diff --git a/Rakefile b/Rakefile new file mode 100644 index 00000000..958ab740 --- /dev/null +++ b/Rakefile @@ -0,0 +1,92 @@ +require 'rexml/document' +begin + require 'albacore' +rescue LoadError + warn "Please run 'gem install albacore --pre'" + exit 1 +end + +ISCC = '"C:\Program Files (x86)\Inno Setup 5\ISCC.exe"' + +BIN_DIR = 'bin/x64/Release' +SRC_DIR = 'src/SyncTrayzor' +INSTALLER_DIR = 'installer' +INSTALLER = File.join(INSTALLER_DIR, 'SyncTrayzorSetup.exe') + +PORTABLE_OUTPUT_DIR = File.absolute_path('SyncTrayzorPortable') + +CONFIG = ENV['CONFIG'] || 'Release' +PLATFORM = ENV['PLATFORM'] || 'x64' + +def cp_to_portable(src) + dest = File.join(PORTABLE_OUTPUT_DIR, src) + mkdir_p File.dirname(dest) unless File.exist?(File.dirname(dest)) + cp src, dest +end + +desc 'Build the project' +build :build do |b| + b.sln = 'src/SyncTrayzor.sln' + b.target = [:Clean, :Build] + b.prop 'Configuration', CONFIG + b.prop 'Platform', PLATFORM +end + +task :installer do + rm INSTALLER if File.exist?(INSTALLER) + sh ISCC, File.join(INSTALLER_DIR, 'installer.iss') +end + +desc 'Create the portable release directory' +task :portable do + rm_rf PORTABLE_OUTPUT_DIR + mkdir_p PORTABLE_OUTPUT_DIR + + Dir.chdir(BIN_DIR) do + files = FileList[ + '*.exe', + '*.exe.config', + '*.dll', + '*.pdb', + '*.pak', + '*.dat', + File.join('locales', '*'), + ].exclude('*.vshost.*') + + files.each do |file| + cp_to_portable(file) + end + end + + cp File.join(SRC_DIR, 'Icons', 'default.ico'), PORTABLE_OUTPUT_DIR + + FileList['*.md', '*.txt'].each do |file| + cp_to_portable(file) + end + + Dir.chdir(INSTALLER_DIR) do + FileList['syncthing.exe', '*.dll'].each do |file| + cp_to_portable(file) + end + end + + puts 'Rewriting app.config' + config_path = File.join(PORTABLE_OUTPUT_DIR, 'SyncTrayzor.exe.config') + doc = File.open(config_path, 'r') do |f| + doc = REXML::Document.new(f) + REXML::XPath.first(doc, '/configuration/applicationSettings//setting[@name="PortableMode"]/value').text = 'True' + doc + end + File.open(config_path, 'w') do |f| + doc.write(f) + end +end + +desc 'Build and package everything' +task :package => [:build, :installer, :portable] + +desc 'Remove portable and installer' +task :clean do + rm_rf PORTABLE_OUTPUT_DIR if File.exist?(PORTABLE_OUTPUT_DIR) + rm INSTALLER if File.exist?(INSTALLER) +end \ No newline at end of file diff --git a/installer/installer.iss b/installer/installer.iss index e9d40c32..2e58f8d5 100644 --- a/installer/installer.iss +++ b/installer/installer.iss @@ -54,7 +54,7 @@ Source: "{#AppSrc}\Icons\default.ico"; DestDir: "{app}"; Flags: ignoreversion Source: "{#AppRoot}\*.md"; DestDir: "{app}"; Flags: ignoreversion Source: "{#AppRoot}\*.txt"; DestDir: "{app}"; Flags: ignoreversion Source: "*.dll"; DestDir: "{app}"; Flags: ignoreversion -Source: "syncthing.exe"; DestDir: "{userappdata}\{#AppDataFolder}" +Source: "syncthing.exe"; DestDir: "{app}" Source: "dotNet451Setup.exe"; DestDir: {tmp}; Flags: deleteafterinstall; Check: FrameworkIsNotInstalled [Icons] @@ -76,19 +76,6 @@ begin result := not exists or (release < 378758); end; -procedure CurStepChanged(CurStep: TSetupStep); -begin - if CurStep = ssInstall then begin - { Since we're shifting from 32-bit to 64-bit, clean up the 32-bit installation dir } - if DirExists(ExpandConstant('{pf32}\SyncTrayzor')) then - DelTree(ExpandConstant('{pf32}\SyncTrayzor'), True, True, True); - - { If we mistakenly wrote to the admin user's registry before, undo that now } - if RegValueExists(HKCU64, ExpandConstant('{#RunRegKey}'), 'SyncTrayzor') then - RegDeleteValue(HKCU64, ExpandConstant('{#RunRegKey}'), 'SyncTrayzor'); - end; -end; - [UninstallDelete] -Type: files; Name: "{userappdata}\{#AppDataFolder}\config.xml" -Type: dirifempty; Name: "{userappdata}\{#AppDataFolder}" \ No newline at end of file +Type: filesandordirs; Name: "{userappdata}\{#AppDataFolder}" +Type: filesandordirs; Name: "{userappdata}\{#AppDataFolder}" \ No newline at end of file diff --git a/src/SyncTrayzor.sln b/src/SyncTrayzor.sln index 0e1f0ad8..3cec0033 100644 --- a/src/SyncTrayzor.sln +++ b/src/SyncTrayzor.sln @@ -19,8 +19,8 @@ Global {D1F89B3D-7967-4DC6-AE45-50A7817FE54F}.Debug|x86.Build.0 = Debug|x86 {D1F89B3D-7967-4DC6-AE45-50A7817FE54F}.Release|x64.ActiveCfg = Release|x64 {D1F89B3D-7967-4DC6-AE45-50A7817FE54F}.Release|x64.Build.0 = Release|x64 - {D1F89B3D-7967-4DC6-AE45-50A7817FE54F}.Release|x86.ActiveCfg = Release|x64 - {D1F89B3D-7967-4DC6-AE45-50A7817FE54F}.Release|x86.Build.0 = Release|x64 + {D1F89B3D-7967-4DC6-AE45-50A7817FE54F}.Release|x86.ActiveCfg = Release|x86 + {D1F89B3D-7967-4DC6-AE45-50A7817FE54F}.Release|x86.Build.0 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/src/SyncTrayzor/App.config b/src/SyncTrayzor/App.config index aba5d48a..2511f9aa 100644 --- a/src/SyncTrayzor/App.config +++ b/src/SyncTrayzor/App.config @@ -5,6 +5,7 @@
+ @@ -27,6 +28,9 @@ http://github.com/canton7/SyncTrayzor/issues + + False + @@ -41,10 +45,20 @@ layout="${longdate} [${level}] ${logger}: ${message} ${exception:format=type,message,method,stacktrace,tostring:maxInnerExceptionLevel=10:innerFormat=shortType,message,method}"/> + + + \ No newline at end of file diff --git a/src/SyncTrayzor/App.xaml b/src/SyncTrayzor/App.xaml index 0e763dd1..626f147b 100644 --- a/src/SyncTrayzor/App.xaml +++ b/src/SyncTrayzor/App.xaml @@ -11,7 +11,7 @@ - + diff --git a/src/SyncTrayzor/Bootstrapper.cs b/src/SyncTrayzor/Bootstrapper.cs index dd1be0a1..0221b146 100644 --- a/src/SyncTrayzor/Bootstrapper.cs +++ b/src/SyncTrayzor/Bootstrapper.cs @@ -4,6 +4,7 @@ using StyletIoC; using SyncTrayzor.NotifyIcon; using SyncTrayzor.Pages; +using SyncTrayzor.Properties; using SyncTrayzor.Services; using SyncTrayzor.Services.UpdateChecker; using SyncTrayzor.SyncThing; @@ -12,6 +13,7 @@ using System.Diagnostics; using System.Linq; using System.Text; +using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; @@ -39,13 +41,32 @@ protected override void ConfigureIoC(IStyletIoCBuilder builder) protected override void Configure() { - GlobalDiagnosticsContext.Set("LogFilePath", this.Container.Get().BasePath); + var configurationProvider = this.Container.Get(); + // Debug builds are always 'portable' +#if DEBUG + configurationProvider.IsPortableMode = true; +#else + configurationProvider.IsPortableMode = Settings.Default.PortableMode; +#endif + configurationProvider.EnsureEnvironmentConsistency(); + + GlobalDiagnosticsContext.Set("LogFilePath", configurationProvider.LogFilePath); - // Must be done before ConfigurationApplicator.ApplyConfiguration + var autostartProvider = this.Container.Get(); #if DEBUG - this.Container.Get().IsEnabled = false; + autostartProvider.IsEnabled = false; #endif + if (autostartProvider.CanWrite) + { + // If it's not in portable mode, and if we had to create config (i.e. it's the first start ever), then enable autostart + // Else, keep the config as it was, but update the path to us (if we're not in debug) + if (!configurationProvider.IsPortableMode && configurationProvider.HadToCreateConfiguration) + autostartProvider.SetAutoStart(new AutostartConfiguration() { AutoStart = true, StartMinimized = true }); + else + autostartProvider.UpdatePathToSelf(); + } + var notifyIconManager = this.Container.Get(); notifyIconManager.Setup((INotifyIconDelegate)this.RootViewModel); this.Container.Get().ApplyConfiguration(); @@ -70,7 +91,8 @@ protected override void OnLaunch() ((ShellViewModel)this.RootViewModel).Start(); // We don't care if this fails - this.Container.Get().CheckForUpdatesAsync(); + if (config.NotifyOfNewVersions) + this.Container.Get().CheckForUpdatesAsync(); } protected override void OnUnhandledException(DispatcherUnhandledExceptionEventArgs e) @@ -92,5 +114,11 @@ protected override void OnUnhandledException(DispatcherUnhandledExceptionEventAr windowManager.ShowDialog(vm); } } + + protected override void OnExit(ExitEventArgs e) + { + // Try and be nice and close SyncTrayzor gracefully, before the Dispose call on SyncThingProcessRunning kills it dead + this.Container.Get().StopAsync().Wait(500); + } } } diff --git a/src/SyncTrayzor/NotifyIcon/NotifyIconManager.cs b/src/SyncTrayzor/NotifyIcon/NotifyIconManager.cs index 754d419a..a419c513 100644 --- a/src/SyncTrayzor/NotifyIcon/NotifyIconManager.cs +++ b/src/SyncTrayzor/NotifyIcon/NotifyIconManager.cs @@ -14,6 +14,7 @@ namespace SyncTrayzor.NotifyIcon public interface INotifyIconManager { bool ShowOnlyOnClose { get; set; } + bool MinimizeToTray { get; set; } bool CloseToTray { get; set; } bool ShowSynchronizedBalloon { get; set; } @@ -43,15 +44,13 @@ public bool ShowOnlyOnClose } } + public bool MinimizeToTray { get; set; } + private bool _closeToTray; public bool CloseToTray { get { return this._closeToTray; } - set - { - this._closeToTray = value; - this.application.ShutdownMode = this._closeToTray ? ShutdownMode.OnExplicitShutdown : ShutdownMode.OnMainWindowClose; - } + set { this._closeToTray = value; this.SetShutdownMode(); } } public bool ShowSynchronizedBalloon { get; set; } @@ -86,6 +85,11 @@ public NotifyIconManager( }; } + private void SetShutdownMode() + { + this.application.ShutdownMode = this._closeToTray ? ShutdownMode.OnExplicitShutdown : ShutdownMode.OnMainWindowClose; + } + public void Setup(INotifyIconDelegate rootViewModel) { this.rootViewModel = rootViewModel; @@ -94,6 +98,7 @@ public void Setup(INotifyIconDelegate rootViewModel) this.viewManager.BindViewToModel(this.taskbarIcon, this.viewModel); this.rootViewModel.Activated += rootViewModelActivated; + this.rootViewModel.Deactivated += rootViewModelDeactivated; this.rootViewModel.Closed += rootViewModelClosed; } @@ -104,11 +109,31 @@ public void EnsureIconVisible() private void rootViewModelActivated(object sender, ActivationEventArgs e) { + // If it's minimize to tray, not close to tray, then we'll have set the shutdown mode to OnExplicitShutdown just before closing + // In this case, re-set Shutdownmode + this.SetShutdownMode(); + this.viewModel.MainWindowVisible = true; if (this.ShowOnlyOnClose) this.viewModel.Visible = false; } + private void rootViewModelDeactivated(object sender, DeactivationEventArgs e) + { + if (this.MinimizeToTray) + { + // Don't do this if it's shutting down + if (this.application.HasMainWindow) + this.application.ShutdownMode = ShutdownMode.OnExplicitShutdown; + + this.rootViewModel.CloseToTray(); + + this.viewModel.MainWindowVisible = false; + if (this.ShowOnlyOnClose) + this.viewModel.Visible = true; + } + } + private void rootViewModelClosed(object sender, CloseEventArgs e) { this.viewModel.MainWindowVisible = false; diff --git a/src/SyncTrayzor/NotifyIcon/NotifyIconViewModel.cs b/src/SyncTrayzor/NotifyIcon/NotifyIconViewModel.cs index 0f80ae77..9a44a0c0 100644 --- a/src/SyncTrayzor/NotifyIcon/NotifyIconViewModel.cs +++ b/src/SyncTrayzor/NotifyIcon/NotifyIconViewModel.cs @@ -1,4 +1,5 @@ using Stylet; +using SyncTrayzor.Pages; using SyncTrayzor.SyncThing; using System; using System.Collections.Generic; @@ -10,7 +11,9 @@ namespace SyncTrayzor.NotifyIcon { public class NotifyIconViewModel : PropertyChangedBase { + private readonly IWindowManager windowManager; private readonly ISyncThingManager syncThingManager; + private readonly Func settingsViewModelFactory; public bool Visible { get; set; } public bool MainWindowVisible { get; set; } @@ -28,9 +31,14 @@ public bool SyncThingStarted public bool SyncThingSyncing { get; private set; } - public NotifyIconViewModel(ISyncThingManager syncThingManager) + public NotifyIconViewModel( + IWindowManager windowManager, + ISyncThingManager syncThingManager, + Func settingsViewModelFactory) { + this.windowManager = windowManager; this.syncThingManager = syncThingManager; + this.settingsViewModelFactory = settingsViewModelFactory; this.syncThingManager.StateChanged += (o, e) => { @@ -52,6 +60,12 @@ public void DoubleClick() this.OnWindowOpenRequested(); } + public void ShowSettings() + { + var vm = this.settingsViewModelFactory(); + this.windowManager.ShowDialog(vm); + } + public void Restore() { this.OnWindowOpenRequested(); diff --git a/src/SyncTrayzor/NotifyIcon/TaskbarIconResources.xaml b/src/SyncTrayzor/NotifyIcon/TaskbarIconResources.xaml index 327af678..11d35001 100644 --- a/src/SyncTrayzor/NotifyIcon/TaskbarIconResources.xaml +++ b/src/SyncTrayzor/NotifyIcon/TaskbarIconResources.xaml @@ -3,12 +3,12 @@ xmlns:s="https://github.com/canton7/Stylet" xmlns:tb="http://www.hardcodet.net/taskbar"> - - - - - - + + + + + + + diff --git a/src/SyncTrayzor/Pages/AboutView.xaml b/src/SyncTrayzor/Pages/AboutView.xaml index e335a718..1e58eac0 100644 --- a/src/SyncTrayzor/Pages/AboutView.xaml +++ b/src/SyncTrayzor/Pages/AboutView.xaml @@ -2,8 +2,8 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="https://github.com/canton7/Stylet" - Height="250" Width="250" - WindowStyle="None" SizeToContent="Width" + Height="300" Width="250" + WindowStyle="None" SizeToContent="WidthAndHeight" ShowInTaskbar="False"> @@ -13,8 +13,9 @@ Version: + (portable) - + Syncthing Version: @@ -28,13 +29,16 @@ - Created by Antony Male - Released under the MIT license + Created by Antony Male. + Released under the MIT license. - + + Show Open Source Licenses + + diff --git a/src/SyncTrayzor/Pages/AboutViewModel.cs b/src/SyncTrayzor/Pages/AboutViewModel.cs index ec0d9839..03a31bec 100644 --- a/src/SyncTrayzor/Pages/AboutViewModel.cs +++ b/src/SyncTrayzor/Pages/AboutViewModel.cs @@ -1,5 +1,6 @@ using Stylet; using SyncTrayzor.Properties; +using SyncTrayzor.Services; using SyncTrayzor.Services.UpdateChecker; using SyncTrayzor.SyncThing; using System; @@ -14,22 +15,33 @@ namespace SyncTrayzor.Pages { public class AboutViewModel : Screen { + private readonly IWindowManager windowManager; private readonly ISyncThingManager syncThingManager; private readonly IUpdateChecker updateChecker; + private readonly Func thirdPartyComponentsViewModelFactory; public string Version { get; set; } + public bool IsPortable { get; set; } public string SyncthingVersion { get; set; } public string HomepageUrl { get; set; } public string NewerVersion { get; set; } private string newerVersionDownloadUrl; - public AboutViewModel(ISyncThingManager syncThingManager, IUpdateChecker updateChecker) + public AboutViewModel( + IWindowManager windowManager, + ISyncThingManager syncThingManager, + IConfigurationProvider configurationProvider, + IUpdateChecker updateChecker, + Func thirdPartyComponentsViewModelFactory) { + this.windowManager = windowManager; this.syncThingManager = syncThingManager; this.updateChecker = updateChecker; + this.thirdPartyComponentsViewModelFactory = thirdPartyComponentsViewModelFactory; this.Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(3); + this.IsPortable = configurationProvider.IsPortableMode; this.HomepageUrl = Settings.Default.HomepageUrl; this.SyncthingVersion = this.syncThingManager.Version == null ? "Unknown" : this.syncThingManager.Version.Version; @@ -73,6 +85,13 @@ public void DownloadNewerVersion() Process.Start(this.newerVersionDownloadUrl); } + public void ShowLicenses() + { + var vm = this.thirdPartyComponentsViewModelFactory(); + this.windowManager.ShowDialog(vm); + this.RequestClose(true); + } + public void Close() { this.RequestClose(true); diff --git a/src/SyncTrayzor/Pages/NewVersionAlertView.xaml b/src/SyncTrayzor/Pages/NewVersionAlertView.xaml index f166e474..77c76498 100644 --- a/src/SyncTrayzor/Pages/NewVersionAlertView.xaml +++ b/src/SyncTrayzor/Pages/NewVersionAlertView.xaml @@ -2,19 +2,30 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="https://github.com/canton7/Stylet" - Width="400" MaxHeight="600" + Width="600" MaxHeight="600" + Title="SyncTrayzor Update Available" SizeToContent="Height"> A new version of SyncTrayzor is available! Version: - Do you want to download it now? You won't be prompted again for this version. + Do you want to download it now? Changelog: - - + + + + + + + + 'Don't Remind Me Again' will silence reminders for this version. You can permanently disable + new version alerts from the Settings page. Visit Help -> About to manually check for a new version. + diff --git a/src/SyncTrayzor/Pages/NewVersionAlertViewModel.cs b/src/SyncTrayzor/Pages/NewVersionAlertViewModel.cs index efac8fbd..3f277bba 100644 --- a/src/SyncTrayzor/Pages/NewVersionAlertViewModel.cs +++ b/src/SyncTrayzor/Pages/NewVersionAlertViewModel.cs @@ -12,18 +12,21 @@ public class NewVersionAlertViewModel : Screen public Version Version { get; set; } public string Changelog { get; set; } - public NewVersionAlertViewModel() - { - this.DisplayName = "SyncTrayzor update available"; - } + public bool DontRemindMe { get; private set; } public void Download() { this.RequestClose(true); } - public void Close() + public void RemindLater() + { + this.RequestClose(false); + } + + public void DontRemind() { + this.DontRemindMe = true; this.RequestClose(false); } } diff --git a/src/SyncTrayzor/Pages/SettingsView.xaml b/src/SyncTrayzor/Pages/SettingsView.xaml index f0d81260..b41cdb4f 100644 --- a/src/SyncTrayzor/Pages/SettingsView.xaml +++ b/src/SyncTrayzor/Pages/SettingsView.xaml @@ -7,7 +7,8 @@ xmlns:pages="clr-namespace:SyncTrayzor.Pages" mc:Ignorable="d" d:DataContext="{d:DesignInstance pages:SettingsViewModel}" - Height="500" Width="400" + Height="600" Width="400" + Title="Settings" ResizeMode="NoResize" SizeToContent="Height"> @@ -20,11 +21,13 @@ - + + Minimize to tray Close to tray Show Tray Icon only on close Show 'Synchronized' balloon messages + Alert if a new version of SyncTrayzor is available @@ -73,6 +76,24 @@ + + + + + + Use custom home directory for Syncthing. + + This will mean that SyncTrayzor will see a different set of configured folders to any + other Syncthing instances on your computer. + + + + + + + + + diff --git a/src/SyncTrayzor/Pages/SettingsViewModel.cs b/src/SyncTrayzor/Pages/SettingsViewModel.cs index 68955481..fb9d0d5d 100644 --- a/src/SyncTrayzor/Pages/SettingsViewModel.cs +++ b/src/SyncTrayzor/Pages/SettingsViewModel.cs @@ -18,10 +18,14 @@ public class WatchedFolder public class SettingsViewModel : Screen { private readonly IConfigurationProvider configurationProvider; + private readonly IAutostartProvider autostartProvider; public bool ShowTrayIconOnlyOnClose { get; set;} + public bool MinimizeToTray { get; set; } public bool CloseToTray { get; set; } public bool ShowSynchronizedBalloon { get; set; } + public bool NotifyOfNewVersions { get; set; } + public bool StartSyncThingAutomatically { get; set; } public string SyncThingAddress { get; set; } public string SyncThingApiKey { get; set; } @@ -45,30 +49,41 @@ public bool StartMinimizedEnabled public BindableCollection WatchedFolders { get; set; } + public bool SyncthingUseCustomHome { get; set; } + public string TraceVariables { get; set; } + public SettingsViewModel(IConfigurationProvider configurationProvider, IAutostartProvider autostartProvider) { - this.DisplayName = "Settings"; - this.configurationProvider = configurationProvider; + this.autostartProvider = autostartProvider; var configuration = this.configurationProvider.Load(); this.ShowTrayIconOnlyOnClose = configuration.ShowTrayIconOnlyOnClose; + this.MinimizeToTray = configuration.MinimizeToTray; this.CloseToTray = configuration.CloseToTray; this.ShowSynchronizedBalloon = configuration.ShowSynchronizedBalloon; + this.NotifyOfNewVersions = configuration.NotifyOfNewVersions; this.StartSyncThingAutomatically = configuration.StartSyncthingAutomatically; this.SyncThingAddress = configuration.SyncthingAddress; this.SyncThingApiKey = configuration.SyncthingApiKey; - this.StartOnLogon = configuration.StartOnLogon; - this.StartMinimized = configuration.StartMinimized; + + this.CanReadAutostart = this.autostartProvider.CanRead; + this.CanWriteAutostart = this.autostartProvider.CanWrite; + if (this.autostartProvider.CanRead) + { + var currentSetup = this.autostartProvider.GetCurrentSetup(); + this.StartOnLogon = currentSetup.AutoStart; + this.StartMinimized = currentSetup.StartMinimized; + } + this.WatchedFolders = new BindableCollection(configuration.Folders.Select(x => new WatchedFolder() { Folder = x.ID, IsSelected = x.IsWatched })); - - this.CanReadAutostart = autostartProvider.CanRead; - this.CanWriteAutostart = autostartProvider.CanWrite; + this.SyncthingUseCustomHome = configuration.SyncthingUseCustomHome; + this.TraceVariables = configuration.SyncthingTraceFacilities; } public void Save() @@ -76,14 +91,23 @@ public void Save() var configuration = this.configurationProvider.Load(); configuration.ShowTrayIconOnlyOnClose = this.ShowTrayIconOnlyOnClose; + configuration.MinimizeToTray = this.MinimizeToTray; configuration.CloseToTray = this.CloseToTray; configuration.ShowSynchronizedBalloon = this.ShowSynchronizedBalloon; + configuration.NotifyOfNewVersions = this.NotifyOfNewVersions; configuration.StartSyncthingAutomatically = this.StartSyncThingAutomatically; configuration.SyncthingAddress = this.SyncThingAddress; configuration.SyncthingApiKey = this.SyncThingApiKey; - configuration.StartOnLogon = this.StartOnLogon; - configuration.StartMinimized = this.StartMinimized; + + if (this.autostartProvider.CanWrite) + { + var autostartConfig = new AutostartConfiguration() { AutoStart = this.StartOnLogon, StartMinimized = this.StartMinimized }; + this.autostartProvider.SetAutoStart(autostartConfig); + } + configuration.Folders = this.WatchedFolders.Select(x => new FolderConfiguration(x.Folder, x.IsSelected)).ToList(); + configuration.SyncthingUseCustomHome = this.SyncthingUseCustomHome; + configuration.SyncthingTraceFacilities = String.IsNullOrWhiteSpace(this.TraceVariables) ? null : this.TraceVariables; this.configurationProvider.Save(configuration); this.RequestClose(true); diff --git a/src/SyncTrayzor/Pages/ShellView.xaml b/src/SyncTrayzor/Pages/ShellView.xaml index 5a4fb424..f7edd97f 100644 --- a/src/SyncTrayzor/Pages/ShellView.xaml +++ b/src/SyncTrayzor/Pages/ShellView.xaml @@ -5,6 +5,7 @@ xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:xaml="clr-namespace:SyncTrayzor.Xaml" Height="700" Width="1100" + Title="SyncTrayzor" Icon="..\Icons\default.ico"> diff --git a/src/SyncTrayzor/Pages/ShellViewModel.cs b/src/SyncTrayzor/Pages/ShellViewModel.cs index 6d3feb4a..9ecdf05e 100644 --- a/src/SyncTrayzor/Pages/ShellViewModel.cs +++ b/src/SyncTrayzor/Pages/ShellViewModel.cs @@ -37,8 +37,6 @@ public ShellViewModel( Func settingsViewModelFactory, Func aboutViewModelFactory) { - this.DisplayName = "SyncTrayzor"; - this.windowManager = windowManager; this.syncThingManager = syncThingManager; this.application = application; @@ -60,14 +58,7 @@ public bool CanStart } public void Start() { - try - { - this.syncThingManager.Start(); - } - catch (Exception e) - { - this.windowManager.ShowMessageBox(String.Format("Error starting SyncThing: {0}", e.Message), "Error starting SyncThing", MessageBoxButton.OK, MessageBoxImage.Error); - } + this.syncThingManager.Start(); } public bool CanStop @@ -127,7 +118,9 @@ public void ShowAbout() public void ShowExitedWithError() { var msg = "Failed to start Syncthing.\n\n" + - "Please close any other open instances of Syncthing. If SyncTrayzor crashed previously, there may still be zombine Syncthing " + + "Please read the log to determine the cause.\n\n" + + "If \"FATAL: Cannot open database appears\", please close any other open " + + "instances of Syncthing. If SyncTrayzor crashed previously, there may still be zombine Syncthing " + "processes alive. Please use the menu option \"Syncthing -> Kill all Syncthing processes\" to stop them, then use \"Syncthing -> Start\" to start Syncthing again."; this.windowManager.ShowMessageBox(msg, "Syncthing failed to start", icon: MessageBoxImage.Error); } @@ -141,8 +134,7 @@ public void EnsureInForeground() { if (!this.application.HasMainWindow) this.windowManager.ShowWindow(this); - else - this.WindowActivated = true; + this.WindowActivated = true; } public void Shutdown() diff --git a/src/SyncTrayzor/Pages/ThirdPartyComponentsView.xaml b/src/SyncTrayzor/Pages/ThirdPartyComponentsView.xaml new file mode 100644 index 00000000..45246a9c --- /dev/null +++ b/src/SyncTrayzor/Pages/ThirdPartyComponentsView.xaml @@ -0,0 +1,72 @@ + + + + SyncTrayzor is built using many open-source components, and would not exist without them. + Details on each component, and its license text, are shown below. + + + + + + + + + + + + + + + + + + + + + + + + + + Name: + + + Desription: + + + Homepage: + + + + + + + License: + + + Notes: + + + + License Text: + + + + + + + diff --git a/src/SyncTrayzor/Pages/ThirdPartyComponentsViewModel.cs b/src/SyncTrayzor/Pages/ThirdPartyComponentsViewModel.cs new file mode 100644 index 00000000..1f6dc1ff --- /dev/null +++ b/src/SyncTrayzor/Pages/ThirdPartyComponentsViewModel.cs @@ -0,0 +1,117 @@ +using Stylet; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; + +namespace SyncTrayzor.Pages +{ + public class ThirdPartyComponentsViewModel : Conductor.Collection.OneActive + { + public ThirdPartyComponentsViewModel() + { + this.Items.AddRange(new[] + { + new ThirdPartyComponent() + { + Name = "Syncthing", + Description = "Open Source Continuous File Synchronization", + Homepage = "http://syncthing.net", + License = "GPLv3", + Notes = "SyncTrayzor hosts Syncthing", + LicenseText = this.LoadLicense("Syncthing.txt"), + }, + new ThirdPartyComponent() + { + Name = "Stylet", + Description = "Minimal MVVM framework", + Homepage = "https://github.com/canton7/Stylet", + License = "MIT", + Notes = "Used to build the UI", + LicenseText = this.LoadLicense("Stylet.txt"), + }, + new ThirdPartyComponent() + { + Name = "CEF", + Description = "Simple framework for embedding Chromium-based browsers in other applications", + Homepage = "https://code.google.com/p/chromiumembedded", + License = "Modified BSD License", + Notes = "Browser component - used to display Syncthing UI", + LicenseText = this.LoadLicense("CEF.txt") + }, + new ThirdPartyComponent() + { + Name = "CefSharp", + Description = ".NET (WPF and Windows Forms) bindings for the Chromium Embedded Framework", + Homepage = "https://github.com/cefsharp/CefSharp", + License = "New BSD License", + Notes = "WPF adapter for CEF", + LicenseText = this.LoadLicense("CefSharp.txt") + }, + new ThirdPartyComponent() + { + Name = "Refit", + Description = "The automatic type-safe REST library for Xamarin and .NET", + Homepage = "http://paulcbetts.github.io/refit", + License = "MIT", + Notes = "Used for making REST API request to Syncthing and Github", + LicenseText = this.LoadLicense("Refit.txt") + }, + new ThirdPartyComponent() + { + Name = "Json.NET", + Description = "Popular high-performance JSON framework for .NET ", + Homepage = "http://www.newtonsoft.com/json", + License = "MIT", + Notes = "JSON deserializer, used in conjunction with Refit", + LicenseText = this.LoadLicense("Json.NET.txt") + }, + new ThirdPartyComponent() + { + Name = "NotifyIcon WPF", + Description = "An implementation of a NotifyIcon (aka system tray icon or taskbar icon) for the WPF platform", + Homepage = "http://www.hardcodet.net/wpf-notifyicon", + License = "The Code Project Open License (CPOL) 1.02", + Notes = "Provides the tray icon", + LicenseText = this.LoadLicense("NotifyIcon.txt") + }, + new ThirdPartyComponent() + { + Name = "PropertyChanged.Fody", + Description = "Injects INotifyPropertyChanged code into properties at compile time", + Homepage = "https://github.com/Fody/PropertyChanged", + License = "MIT", + Notes = "Not distributed with SyncTrayzor, but provides aweomse compile-time features", + LicenseText = this.LoadLicense("Fody.txt") + }, + }); + } + + private string LoadLicense(string licenseName) + { + using (var sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("SyncTrayzor.Resources.Licenses." + licenseName))) + { + return sr.ReadToEnd(); + } + } + + public void ViewHomepage() + { + Process.Start(this.ActiveItem.Homepage); + } + } + + public class ThirdPartyComponent + { + public string Name { get; set; } + public string Description { get; set; } + public string Homepage { get; set; } + public string Notes { get; set; } + public string License { get; set; } + public string LicenseText { get; set; } + } +} diff --git a/src/SyncTrayzor/Pages/UnhandledExceptionView.xaml b/src/SyncTrayzor/Pages/UnhandledExceptionView.xaml index 6d8e65ba..4ab59b5e 100644 --- a/src/SyncTrayzor/Pages/UnhandledExceptionView.xaml +++ b/src/SyncTrayzor/Pages/UnhandledExceptionView.xaml @@ -2,7 +2,8 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="https://github.com/canton7/Stylet" - Height="400" Width="600"> + Height="400" Width="600" + Title="Error!"> // This code was generated by a tool. -// Runtime Version:4.0.30319.18444 +// Runtime Version:4.0.30319.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. @@ -67,5 +67,14 @@ public string IssuesUrl { return ((string)(this["IssuesUrl"])); } } + + [global::System.Configuration.ApplicationScopedSettingAttribute()] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Configuration.DefaultSettingValueAttribute("False")] + public bool PortableMode { + get { + return ((bool)(this["PortableMode"])); + } + } } } diff --git a/src/SyncTrayzor/Properties/Settings.settings b/src/SyncTrayzor/Properties/Settings.settings index f8541fae..59b22784 100644 --- a/src/SyncTrayzor/Properties/Settings.settings +++ b/src/SyncTrayzor/Properties/Settings.settings @@ -17,5 +17,8 @@ http://github.com/canton7/SyncTrayzor/issues + + False + \ No newline at end of file diff --git a/src/SyncTrayzor/Resources/Licenses/CEF.txt b/src/SyncTrayzor/Resources/Licenses/CEF.txt new file mode 100644 index 00000000..543ed8d3 --- /dev/null +++ b/src/SyncTrayzor/Resources/Licenses/CEF.txt @@ -0,0 +1,29 @@ +// Copyright (c) 2008-2014 Marshall A. Greenblatt. Portions Copyright (c) +// 2006-2009 Google Inc. All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the names of its contributors may be used to endorse +// or promote products derived from this software without specific prior +// written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE \ No newline at end of file diff --git a/src/SyncTrayzor/Resources/Licenses/CefSharp.txt b/src/SyncTrayzor/Resources/Licenses/CefSharp.txt new file mode 100644 index 00000000..ffce4a53 --- /dev/null +++ b/src/SyncTrayzor/Resources/Licenses/CefSharp.txt @@ -0,0 +1,30 @@ +// Copyright © 2010-2014 The CefSharp Authors +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// * Neither the name of Google Inc. nor the name Chromium Embedded +// Framework nor the name CefSharp nor the names of its contributors +// may be used to endorse or promote products derived from this software +// without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/src/SyncTrayzor/Resources/Licenses/Fody.txt b/src/SyncTrayzor/Resources/Licenses/Fody.txt new file mode 100644 index 00000000..1a3677cc --- /dev/null +++ b/src/SyncTrayzor/Resources/Licenses/Fody.txt @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2012 Simon Cropp and contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/src/SyncTrayzor/Resources/Licenses/Json.NET.txt b/src/SyncTrayzor/Resources/Licenses/Json.NET.txt new file mode 100644 index 00000000..dfaadbe4 --- /dev/null +++ b/src/SyncTrayzor/Resources/Licenses/Json.NET.txt @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2007 James Newton-King + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/SyncTrayzor/Resources/Licenses/NLog.txt b/src/SyncTrayzor/Resources/Licenses/NLog.txt new file mode 100644 index 00000000..e20cd54c --- /dev/null +++ b/src/SyncTrayzor/Resources/Licenses/NLog.txt @@ -0,0 +1,32 @@ + +Copyright (c) 2004-2011 Jaroslaw Kowalski + +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + +* Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of Jaroslaw Kowalski nor the names of its + contributors may be used to endorse or promote products derived from this + software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/src/SyncTrayzor/Resources/Licenses/NotifyIcon.txt b/src/SyncTrayzor/Resources/Licenses/NotifyIcon.txt new file mode 100644 index 00000000..5a68734a --- /dev/null +++ b/src/SyncTrayzor/Resources/Licenses/NotifyIcon.txt @@ -0,0 +1,208 @@ +Preamble +-------- + +This License governs Your use of the Work. This License is intended to allow +developers to use the Source Code and Executable Files provided as part of the +Work in any application in any form. + +The main points subject to the terms of the License are: + + - Source Code and Executable Files can be used in commercial applications; + - Source Code and Executable Files can be redistributed; and + - Source Code can be modified to create derivative works. + - No claim of suitability, guarantee, or any warranty whatsoever is provided. + The software is provided "as-is". + - The Article(s) accompanying the Work may not be distributed or republished + without the Author's consent + +This License is entered between You, the individual or other entity reading or +otherwise making use of the Work licensed pursuant to this License and the +individual or other entity which offers the Work under the terms of this License +("Author"). + +License +------- + +THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CODE PROJECT +OPEN LICENSE ("LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER +APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE +OR COPYRIGHT LAW IS PROHIBITED. + +BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HEREIN, YOU ACCEPT AND AGREE TO BE +BOUND BY THE TERMS OF THIS LICENSE. THE AUTHOR GRANTS YOU THE RIGHTS CONTAINED +HEREIN IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. IF YOU +DO NOT AGREE TO ACCEPT AND BE BOUND BY THE TERMS OF THIS LICENSE, YOU CANNOT +MAKE ANY USE OF THE WORK. + + 1. Definitions. + + a. "Articles" means, collectively, all articles written by Author which + describes how the Source Code and Executable Files for the Work may be + used by a user. + b. "Author" means the individual or entity that offers the Work under the + terms of this License. + c. "Derivative Work" means a work based upon the Work or upon the Work and + other pre-existing works. + d. "Executable Files" refer to the executables, binary files, configuration + and any required data files included in the Work. + e. "Publisher" means the provider of the website, magazine, CD-ROM, DVD or + other medium from or by which the Work is obtained by You. + f. "Source Code" refers to the collection of source code and configuration + files used to create the Executable Files. + g. "Standard Version" refers to such a Work if it has not been modified, or + has been modified in accordance with the consent of the Author, such + consent being in the full discretion of the Author. + h. "Work" refers to the collection of files distributed by the Publisher, + including the Source Code, Executable Files, binaries, data files, + documentation, whitepapers and the Articles. + i. "You" is you, an individual or entity wishing to use the Work and + exercise your rights under this License. + + 2. Fair Use/Fair Use Rights. Nothing in this License is intended to reduce, + limit, or restrict any rights arising from fair use, fair dealing, first + sale or other limitations on the exclusive rights of the copyright owner + under copyright law or other applicable laws. + + 3. License Grant. Subject to the terms and conditions of this License, the + Author hereby grants You a worldwide, royalty-free, non-exclusive, perpetual + (for the duration of the applicable copyright) license to exercise the + rights in the Work as stated below: + + a. You may use the standard version of the Source Code or Executable Files + in Your own applications. + b. You may apply bug fixes, portability fixes and other modifications + obtained from the Public Domain or from the Author. A Work modified in + such a way shall still be considered the standard version and will be + subject to this License. + c. You may otherwise modify Your copy of this Work (excluding the Articles) + in any way to create a Derivative Work, provided that You insert a + prominent notice in each changed file stating how, when and where You + changed that file. + d. You may distribute the standard version of the Executable Files and + Source Code or Derivative Work in aggregate with other (possibly + commercial) programs as part of a larger (possibly commercial) software + distribution. + e. The Articles discussing the Work published in any form by the author may + not be distributed or republished without the Author's consent. The + author retains copyright to any such Articles. You may use the Executable + Files and Source Code pursuant to this License but you may not repost or + republish or otherwise distribute or make available the Articles, without + the prior written consent of the Author. + + Any subroutines or modules supplied by You and linked into the Source Code or + Executable Files of this Work shall not be considered part of this Work and + will not be subject to the terms of this License. + + 4. Patent License. Subject to the terms and conditions of this License, each + Author hereby grants to You a perpetual, worldwide, non-exclusive, + no-charge, royalty-free, irrevocable (except as stated in this section) + patent license to make, have made, use, import, and otherwise transfer the + Work. + + 5. Restrictions. The license granted in Section 3 above is expressly made + subject to and limited by the following restrictions: + + a. You agree not to remove any of the original copyright, patent, trademark, + and attribution notices and associated disclaimers that may appear in the + Source Code or Executable Files. + b. You agree not to advertise or in any way imply that this Work is a + product of Your own. + c. The name of the Author may not be used to endorse or promote products + derived from the Work without the prior written consent of the Author. + d. You agree not to sell, lease, or rent any part of the Work. This does not + restrict you from including the Work or any part of the Work inside a + larger software distribution that itself is being sold. The Work by + itself, though, cannot be sold, leased or rented. + e. You may distribute the Executable Files and Source Code only under the + terms of this License, and You must include a copy of, or the Uniform + Resource Identifier for, this License with every copy of the Executable + Files or Source Code You distribute and ensure that anyone receiving + such Executable Files and Source Code agrees that the terms of this + License apply to such Executable Files and/or Source Code. You may not + offer or impose any terms on the Work that alter or restrict the terms + of this License or the recipients' exercise of the rights granted + hereunder. You may not sublicense the Work. You must keep intact all + notices that refer to this License and to the disclaimer of warranties. + You may not distribute the Executable Files or Source Code with any + technological measures that control access or use of the Work in a + manner inconsistent with the terms of this License. + f. You agree not to use the Work for illegal, immoral or improper purposes, + or on pages containing illegal, immoral or improper material. The Work + is subject to applicable export laws. You agree to comply with all such + laws and regulations that may apply to the Work after Your receipt of + the Work. + + 6. Representations, Warranties and Disclaimer. THIS WORK IS PROVIDED "AS IS", + "WHERE IS" AND "AS AVAILABLE", WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES OR + CONDITIONS OR GUARANTEES. YOU, THE USER, ASSUME ALL RISK IN ITS USE, + INCLUDING COPYRIGHT INFRINGEMENT, PATENT INFRINGEMENT, SUITABILITY, ETC. + AUTHOR EXPRESSLY DISCLAIMS ALL EXPRESS, IMPLIED OR STATUTORY WARRANTIES OR + CONDITIONS, INCLUDING WITHOUT LIMITATION, WARRANTIES OR CONDITIONS OF + MERCHANTABILITY, MERCHANTABLE QUALITY OR FITNESS FOR A PARTICULAR PURPOSE, + OR ANY WARRANTY OF TITLE OR NON-INFRINGEMENT, OR THAT THE WORK (OR ANY + PORTION THEREOF) IS CORRECT, USEFUL, BUG-FREE OR FREE OF VIRUSES. YOU MUST + PASS THIS DISCLAIMER ON WHENEVER YOU DISTRIBUTE THE WORK OR DERIVATIVE + WORKS. + + 7. Indemnity. You agree to defend, indemnify and hold harmless the Author and + the Publisher from and against any claims, suits, losses, damages, + liabilities, costs, and expenses (including reasonable legal or attorneys’ + fees) resulting from or relating to any use of the Work by You. + + 8. Limitation on Liability. EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN + NO EVENT WILL THE AUTHOR OR THE PUBLISHER BE LIABLE TO YOU ON ANY LEGAL + THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY + DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK OR OTHERWISE + EVEN IF THE AUTHOR OR THE PUBLISHER HAS BEEN ADVISED OF THE POSSIBILITY OF + SUCH DAMAGES. + + 9. Termination. + + a. This License and the rights granted hereunder will terminate + automatically upon any breach by You of any term of this License. + Individuals or entities who have received Derivative Works from You under + this License, however, will not have their licenses terminated provided + such individuals or entities remain in full compliance with those + licenses. Sections 1, 2, 6, 7, 8, 9, 10 and 11 will survive any + termination of this License. + b. If You bring a copyright, trademark, patent or any other infringement + claim against any contributor over infringements You claim are made by + the Work, your License from such contributor to the Work ends + automatically. + c. Subject to the above terms and conditions, this License is perpetual (for + the duration of the applicable copyright in the Work). Notwithstanding + the above, the Author reserves the right to release the Work under + different license terms or to stop distributing the Work at any time; + provided, however that any such election will not serve to withdraw this + License (or any other license that has been, or is required to be, + granted under the terms of this License), and this License will continue + in full force and effect unless terminated as stated above. + +10. Publisher. The parties hereby confirm that the Publisher shall not, under + any circumstances, be responsible for and shall not have any liability in + respect of the subject matter of this License. The Publisher makes no + warranty whatsoever in connection with the Work and shall not be liable to + You or any party on any legal theory for any damages whatsoever, including + without limitation any general, special, incidental or consequential damages + arising in connection to this license. The Publisher reserves the right to + cease making the Work available to You at any time without notice + +11. Miscellaneous + + a. This License shall be governed by the laws of the location of the head + office of the Author or if the Author is an individual, the laws of + location of the principal place of residence of the Author. + b. If any provision of this License is invalid or unenforceable under + applicable law, it shall not affect the validity or enforceability of + the remainder of the terms of this License, and without further action + by the parties to this License, such provision shall be reformed to the + minimum extent necessary to make such provision valid and enforceable. + c. No term or provision of this License shall be deemed waived and no breach + consented to unless such waiver or consent shall be in writing and + signed by the party to be charged with such waiver or consent. + d. This License constitutes the entire agreement between the parties with + respect to the Work licensed herein. There are no understandings, + agreements or representations with respect to the Work not specified + herein. The Author shall not be bound by any additional provisions that + may appear in any communication from You. This License may not be + modified without the mutual written agreement of the Author and You. \ No newline at end of file diff --git a/src/SyncTrayzor/Resources/Licenses/Refit.txt b/src/SyncTrayzor/Resources/Licenses/Refit.txt new file mode 100644 index 00000000..b47bb1f0 --- /dev/null +++ b/src/SyncTrayzor/Resources/Licenses/Refit.txt @@ -0,0 +1,19 @@ +Copyright (c) 2012 GitHub + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/src/SyncTrayzor/Resources/Licenses/Stylet.txt b/src/SyncTrayzor/Resources/Licenses/Stylet.txt new file mode 100644 index 00000000..b2cf4e67 --- /dev/null +++ b/src/SyncTrayzor/Resources/Licenses/Stylet.txt @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2014 Antony Male + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/src/SyncTrayzor/Resources/Licenses/Syncthing.txt b/src/SyncTrayzor/Resources/Licenses/Syncthing.txt new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/src/SyncTrayzor/Resources/Licenses/Syncthing.txt @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/src/SyncTrayzor/Services/AutostartProvider.cs b/src/SyncTrayzor/Services/AutostartProvider.cs index 1dc4dfb1..c995c1f9 100644 --- a/src/SyncTrayzor/Services/AutostartProvider.cs +++ b/src/SyncTrayzor/Services/AutostartProvider.cs @@ -1,4 +1,5 @@ using Microsoft.Win32; +using NLog; using System; using System.Collections.Generic; using System.Linq; @@ -16,6 +17,7 @@ public interface IAutostartProvider bool CanRead { get; } bool CanWrite { get; } + void UpdatePathToSelf(); AutostartConfiguration GetCurrentSetup(); void SetAutoStart(AutostartConfiguration config); } @@ -24,11 +26,17 @@ public class AutostartConfiguration { public bool AutoStart { get; set; } public bool StartMinimized { get; set; } + + public override string ToString() + { + return String.Format("", this.AutoStart, this.StartMinimized); + } } public class AutostartProvider : IAutostartProvider { private const string applicationName = "SyncTrayzor"; + private readonly Logger logger = LogManager.GetCurrentClassLogger(); public bool IsEnabled { get; set; } @@ -46,7 +54,8 @@ public bool CanWrite public AutostartProvider() { - this.IsEnabled = true; // Default + // Default + this.IsEnabled = true; // Check our access try @@ -54,6 +63,7 @@ public AutostartProvider() this.OpenRegistryKey(true).Dispose(); this._canWrite = true; this._canRead = true; + logger.Info("Have read/write access to the registry"); return; } catch (SecurityException) { } @@ -62,8 +72,12 @@ public AutostartProvider() { this.OpenRegistryKey(false).Dispose(); this._canRead = true; + logger.Info("Have read-only access to the registry"); + return; } catch (SecurityException) { } + + logger.Info("Have no access to the registry"); } private RegistryKey OpenRegistryKey(bool writable) @@ -71,6 +85,15 @@ private RegistryKey OpenRegistryKey(bool writable) return Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", writable); } + public void UpdatePathToSelf() + { + if (!this.CanWrite) + throw new InvalidOperationException("Don't have permission to write to the registry"); + + var config = this.GetCurrentSetup(); + this.SetAutoStart(config); + } + public AutostartConfiguration GetCurrentSetup() { if (!this.CanRead) @@ -90,7 +113,9 @@ public AutostartConfiguration GetCurrentSetup() } } - return new AutostartConfiguration() { AutoStart = autoStart, StartMinimized = startMinimized }; + var config = new AutostartConfiguration() { AutoStart = autoStart, StartMinimized = startMinimized }; + logger.Info("GetCurrentSetup determined that the current configuration is: {0}", config); + return config; } public void SetAutoStart(AutostartConfiguration config) @@ -98,6 +123,8 @@ public void SetAutoStart(AutostartConfiguration config) if (!this.CanWrite) throw new InvalidOperationException("Don't have permission to write to the registry"); + logger.Info("Setting AutoStart to {0}", config); + using (var registryKey = this.OpenRegistryKey(true)) { var keyExists = registryKey.GetValue(applicationName) != null; @@ -105,10 +132,12 @@ public void SetAutoStart(AutostartConfiguration config) if (config.AutoStart) { var path = String.Format("\"{0}\"{1}", Assembly.GetExecutingAssembly().Location, config.StartMinimized ? " -minimized" : ""); + logger.Debug("Autostart path: {0}", path); registryKey.SetValue(applicationName, path); } else if (keyExists) { + logger.Debug("Removing pre-existing registry key"); registryKey.DeleteValue(applicationName); } } diff --git a/src/SyncTrayzor/Services/Configuration.cs b/src/SyncTrayzor/Services/Configuration.cs index 198070f6..29bcd98c 100644 --- a/src/SyncTrayzor/Services/Configuration.cs +++ b/src/SyncTrayzor/Services/Configuration.cs @@ -27,23 +27,29 @@ public FolderConfiguration(FolderConfiguration other) this.ID = other.ID; this.IsWatched = other.IsWatched; } + + public override string ToString() + { + return String.Format("", this.ID, this.IsWatched); + } } [XmlRoot("Configuration")] public class Configuration { - public string SyncthingPath { get; set; } public bool ShowTrayIconOnlyOnClose { get; set; } + public bool MinimizeToTray { get; set; } public bool CloseToTray { get; set; } public bool ShowSynchronizedBalloon { get; set; } public string SyncthingAddress { get; set; } - public bool StartOnLogon { get; set; } - public bool StartMinimized { get; set; } public bool StartSyncthingAutomatically { get; set; } public string SyncthingApiKey { get; set; } + public string SyncthingTraceFacilities { get; set; } + public bool SyncthingUseCustomHome { get; set; } [XmlArrayItem("Folder")] public List Folders { get; set; } + public bool NotifyOfNewVersions { get; set; } [XmlIgnore] public Version LatestNotifiedVersion { get; set; } @@ -55,37 +61,49 @@ public string LatestNotifiedVersionRaw } public Configuration() - : this(null, null) + : this(null, false) { } - public Configuration(string syncThingPath, string syncThingApiKey) + public Configuration(string syncThingApiKey, bool isPortableMode) { - this.SyncthingPath = syncThingPath; this.ShowTrayIconOnlyOnClose = false; + this.MinimizeToTray = false; this.CloseToTray = true; this.ShowSynchronizedBalloon = true; this.SyncthingAddress = "http://localhost:8384"; - this.StartOnLogon = true; - this.StartMinimized = true; this.StartSyncthingAutomatically = true; this.SyncthingApiKey = syncThingApiKey; + this.SyncthingTraceFacilities = null; + this.SyncthingUseCustomHome = isPortableMode; this.Folders = new List(); + this.NotifyOfNewVersions = true; this.LatestNotifiedVersion = null; } public Configuration(Configuration other) { - this.SyncthingPath = other.SyncthingPath; this.ShowTrayIconOnlyOnClose = other.ShowTrayIconOnlyOnClose; + this.MinimizeToTray = other.MinimizeToTray; this.CloseToTray = other.CloseToTray; this.ShowSynchronizedBalloon = other.ShowSynchronizedBalloon; this.SyncthingAddress = other.SyncthingAddress; - this.StartOnLogon = other.StartOnLogon; - this.StartMinimized = other.StartMinimized; this.StartSyncthingAutomatically = other.StartSyncthingAutomatically; this.SyncthingApiKey = other.SyncthingApiKey; + this.SyncthingTraceFacilities = other.SyncthingTraceFacilities; + this.SyncthingUseCustomHome = other.SyncthingUseCustomHome; this.Folders = other.Folders.Select(x => new FolderConfiguration(x)).ToList(); + this.NotifyOfNewVersions = other.NotifyOfNewVersions; this.LatestNotifiedVersion = other.LatestNotifiedVersion; } + + public override string ToString() + { + return String.Format("", + this.ShowTrayIconOnlyOnClose, this.MinimizeToTray, this.CloseToTray, this.ShowSynchronizedBalloon, this.SyncthingAddress, + this.StartSyncthingAutomatically, this.SyncthingApiKey, this.SyncthingTraceFacilities, this.SyncthingUseCustomHome, + String.Join(", ", this.Folders), this.NotifyOfNewVersions, this.LatestNotifiedVersion); + } } } diff --git a/src/SyncTrayzor/Services/ConfigurationApplicator.cs b/src/SyncTrayzor/Services/ConfigurationApplicator.cs index 8bc32250..df265887 100644 --- a/src/SyncTrayzor/Services/ConfigurationApplicator.cs +++ b/src/SyncTrayzor/Services/ConfigurationApplicator.cs @@ -40,9 +40,6 @@ public ConfigurationApplicator( this.githubApiClient = githubApiClient; this.updateChecker = updateChecker; - // Do this before signing up for DataLoaded, so any changes we make don't trigger us again - this.UpdateConfigOnInit(); - this.syncThingManager.DataLoaded += (o, e) => this.LoadFolders(); this.updateChecker.VersionIgnored += (o, e) => { @@ -52,53 +49,27 @@ public ConfigurationApplicator( }; } - private void UpdateConfigOnInit() - { - this.UpdateAutostart(); - } - - private void UpdateAutostart() - { - // Don't have permission? Meh - if (!this.autostartProvider.CanRead) - return; - - // If the user's manually updated the registry themselves, update our config to match - var config = this.configurationProvider.Load(); - var autostartConfig = this.autostartProvider.GetCurrentSetup(); - // We only know enough to change StartMinimized if autostartConfig.AutoStart is strue - if (config.StartOnLogon != autostartConfig.AutoStart || (autostartConfig.AutoStart && config.StartMinimized != autostartConfig.StartMinimized)) - { - if (autostartConfig.AutoStart) - config.StartMinimized = autostartConfig.StartMinimized; - config.StartOnLogon = autostartConfig.AutoStart; - this.configurationProvider.Save(config); - } - } - public void ApplyConfiguration() { this.githubApiClient.SetConnectionDetails(Settings.Default.GithubApiUrl); this.watchedFolderMonitor.BackoffInterval = TimeSpan.FromMilliseconds(Settings.Default.DirectoryWatcherBackoffMilliseconds); this.watchedFolderMonitor.FolderExistenceCheckingInterval = TimeSpan.FromMilliseconds(Settings.Default.DirectoryWatcherFolderExistenceCheckMilliseconds); + this.syncThingManager.ExecutablePath = this.configurationProvider.SyncThingPath; this.ApplyNewConfiguration(this.configurationProvider.Load()); } private void ApplyNewConfiguration(Configuration configuration) { + this.notifyIconManager.MinimizeToTray = configuration.MinimizeToTray; this.notifyIconManager.CloseToTray = configuration.CloseToTray; this.notifyIconManager.ShowOnlyOnClose = configuration.ShowTrayIconOnlyOnClose; this.notifyIconManager.ShowSynchronizedBalloon = configuration.ShowSynchronizedBalloon; this.syncThingManager.Address = new Uri(configuration.SyncthingAddress); - this.syncThingManager.ExecutablePath = configuration.SyncthingPath; this.syncThingManager.ApiKey = configuration.SyncthingApiKey; - - // Debug builds never set autostart - // Don't have permission? Meh - if (this.autostartProvider.CanWrite) - this.autostartProvider.SetAutoStart(new AutostartConfiguration() { AutoStart = configuration.StartOnLogon, StartMinimized = configuration.StartMinimized }); + this.syncThingManager.SyncthingTraceFacilities = configuration.SyncthingTraceFacilities; + this.syncThingManager.SyncthingCustomHomeDir = configuration.SyncthingUseCustomHome ? this.configurationProvider.SyncthingCustomHomePath : null; this.watchedFolderMonitor.WatchedFolderIDs = configuration.Folders.Where(x => x.IsWatched).Select(x => x.ID); @@ -108,13 +79,14 @@ private void ApplyNewConfiguration(Configuration configuration) private void LoadFolders() { var configuration = this.configurationProvider.Load(); + var folderIds = this.syncThingManager.FetchAllFolders().Select(x => x.FolderId).ToList(); - foreach (var newKey in this.syncThingManager.Folders.Keys.Except(configuration.Folders.Select(x => x.ID))) + foreach (var newKey in folderIds.Except(configuration.Folders.Select(x => x.ID))) { configuration.Folders.Add(new FolderConfiguration(newKey, true)); } - configuration.Folders = configuration.Folders.Where(x => this.syncThingManager.Folders.Keys.Contains(x.ID)).ToList(); + configuration.Folders = configuration.Folders.Where(x => folderIds.Contains(x.ID)).ToList(); this.configurationProvider.Save(configuration); } diff --git a/src/SyncTrayzor/Services/ConfigurationProvider.cs b/src/SyncTrayzor/Services/ConfigurationProvider.cs index 58970e1c..e1133b0b 100644 --- a/src/SyncTrayzor/Services/ConfigurationProvider.cs +++ b/src/SyncTrayzor/Services/ConfigurationProvider.cs @@ -1,4 +1,5 @@ -using SyncTrayzor.Utils; +using NLog; +using SyncTrayzor.Utils; using System; using System.Collections.Generic; using System.IO; @@ -24,8 +25,13 @@ public interface IConfigurationProvider { event EventHandler ConfigurationChanged; - string BasePath { get; } + bool HadToCreateConfiguration { get; } + bool IsPortableMode { get; set; } + string LogFilePath { get; } + string SyncThingPath { get; } + string SyncthingCustomHomePath { get; } + void EnsureEnvironmentConsistency(); Configuration Load(); void Save(Configuration config); } @@ -35,75 +41,136 @@ public class ConfigurationProvider : IConfigurationProvider private const string apiKeyChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private const int apiKeyLength = 40; + private readonly Logger logger = LogManager.GetCurrentClassLogger(); private readonly SynchronizedEventDispatcher eventDispatcher; private readonly XmlSerializer serializer = new XmlSerializer(typeof(Configuration)); + + private readonly object currentConfigLock = new object(); private Configuration currentConfig; public event EventHandler ConfigurationChanged; - public string BasePath + public bool HadToCreateConfiguration { get; private set; } + public bool IsPortableMode { get; set; } + + public string ExePath { -#if DEBUG get { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } -#else + } + + public string RoamingPath + { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "SyncTrayzor"); } -#endif + } + + public string LocalPath + { + get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SyncTrayzor"); } + } + + public string LogFilePath + { + get { return this.IsPortableMode ? Path.Combine(this.ExePath, "logs") : Path.Combine(this.RoamingPath); } + } + + public string SyncthingCustomHomePath + { + get { return this.IsPortableMode ? Path.Combine(this.ExePath, "data", "syncthing") : Path.Combine(this.LocalPath, "syncthing"); } + } + + public string SyncThingPath + { + get { return this.IsPortableMode ? Path.Combine(this.ExePath, "syncthing.exe") : Path.Combine(this.RoamingPath, "syncthing.exe"); } + } + + public string SyncThingBackupPath + { + get { return Path.Combine(this.ExePath, "syncthing.exe"); } } public string ConfigurationFilePath { - get { return Path.Combine(this.BasePath, "config.xml"); } + get { return this.IsPortableMode ? Path.Combine(this.ExePath, "data", "config.xml") : Path.Combine(this.RoamingPath, "config.xml"); } } public ConfigurationProvider() { this.eventDispatcher = new SynchronizedEventDispatcher(this); - if (!String.IsNullOrWhiteSpace(this.BasePath)) - Directory.CreateDirectory(this.BasePath); } - public Configuration Load() + public void EnsureEnvironmentConsistency() { - if (this.currentConfig == null) - this.currentConfig = this.LoadFromDisk(); + logger.Debug("IsPortableMode: {0}", this.IsPortableMode); + logger.Debug("ExePath: {0}", this.ExePath); + logger.Debug("LogFilePath: {0}", this.LogFilePath); + logger.Debug("SyncthingCustomHomePath: {0}", this.LogFilePath); + logger.Debug("SyncThingPath: {0}", this.SyncThingPath); + logger.Debug("SyncThingBackupPath: {0}", this.SyncThingBackupPath); + logger.Debug("ConfigurationFilePath: {0}", this.ConfigurationFilePath); + + if (!File.Exists(Path.GetDirectoryName(this.ConfigurationFilePath))) + Directory.CreateDirectory(Path.GetDirectoryName(this.ConfigurationFilePath)); + + if (!File.Exists(this.SyncThingPath)) + { + if (File.Exists(this.SyncThingBackupPath)) + { + logger.Info("Syncthing doesn't exist at {0}, so copying from {1}", this.SyncThingPath, this.SyncThingBackupPath); + File.Copy(this.SyncThingBackupPath, this.SyncThingPath); + } + else + throw new Exception(String.Format("Unable to find Syncthing at {0} or {1}", this.SyncThingPath, this.SyncThingBackupPath)); + } + else if (this.SyncThingPath != this.SyncThingBackupPath && File.Exists(this.SyncThingBackupPath) && + File.GetLastWriteTimeUtc(this.SyncThingPath) < File.GetLastWriteTimeUtc(this.SyncThingBackupPath)) + { + logger.Info("Syncthing at {0} is older ({1}) than at {2} ({3}, so overwriting from backup", + this.SyncThingPath, File.GetLastWriteTimeUtc(this.SyncThingPath), this.SyncThingBackupPath, File.GetLastWriteTimeUtc(this.SyncThingBackupPath)); + File.Copy(this.SyncThingBackupPath, this.SyncThingPath, true); + } - return new Configuration(this.currentConfig); + if (!File.Exists(this.ConfigurationFilePath)) + { + logger.Info("Configuration file {0} doesn't exist, so creating", this.ConfigurationFilePath); + this.HadToCreateConfiguration = true; + var configuration = new Configuration(this.GenerateApiKey(), this.IsPortableMode); + this.Save(configuration); + } } - public void Save(Configuration config) + public Configuration Load() { - this.EnsureConsistency(config); - this.currentConfig = config; - this.OnConfigurationChanged(config); - using (var stream = File.Open(this.ConfigurationFilePath, FileMode.Create)) + lock (this.currentConfigLock) { - this.serializer.Serialize(stream, config); + if (this.currentConfig == null) + this.currentConfig = this.LoadFromDisk(); + + return new Configuration(this.currentConfig); } } - private Configuration LoadFromDisk() + public void Save(Configuration config) { - Configuration configuration; - - if (!File.Exists(this.ConfigurationFilePath)) - { - configuration = new Configuration(Path.Combine(this.BasePath, "syncthing.exe"), this.GenerateApiKey()); - } - else + logger.Debug("Saving configuration: {0}", config); + lock (this.currentConfigLock) { - using (var stream = File.OpenRead(this.ConfigurationFilePath)) + this.currentConfig = config; + using (var stream = File.Open(this.ConfigurationFilePath, FileMode.Create)) { - configuration = (Configuration)this.serializer.Deserialize(stream); + this.serializer.Serialize(stream, config); } } - - return configuration; + this.OnConfigurationChanged(config); } - private void EnsureConsistency(Configuration configuration) + private Configuration LoadFromDisk() { - if (!File.Exists(configuration.SyncthingPath)) - throw new ConfigurationException(String.Format("Unable to find file {0}", configuration.SyncthingPath)); + using (var stream = File.OpenRead(this.ConfigurationFilePath)) + { + var config = (Configuration)this.serializer.Deserialize(stream); + logger.Info("Loaded configuration: {0}", config); + return config; + } } private string GenerateApiKey() diff --git a/src/SyncTrayzor/Services/DirectoryWatcher.cs b/src/SyncTrayzor/Services/DirectoryWatcher.cs index 4d05a0bf..55af5ad9 100644 --- a/src/SyncTrayzor/Services/DirectoryWatcher.cs +++ b/src/SyncTrayzor/Services/DirectoryWatcher.cs @@ -36,10 +36,10 @@ public class DirectoryWatcher : IDisposable private readonly string directory; - private readonly object currentNotifySubPathLock = new object(); private readonly Timer backoffTimer; private readonly Timer existenceCheckingTimer; + private readonly object currentNotifyingSubPathLock = new object(); private string currentNotifyingSubPath; private FileSystemWatcher watcher; @@ -63,7 +63,7 @@ public DirectoryWatcher(string directory, TimeSpan backoffInterval, TimeSpan exi this.backoffTimer.Elapsed += (o, e) => { string currentNotifyingSubPath; - lock (this.currentNotifySubPathLock) + lock (this.currentNotifyingSubPathLock) { currentNotifyingSubPath = this.currentNotifyingSubPath; this.currentNotifyingSubPath = null; @@ -131,7 +131,7 @@ private void PathChanged(string path) return; this.backoffTimer.Stop(); - lock (this.currentNotifySubPathLock) + lock (this.currentNotifyingSubPathLock) { if (this.currentNotifyingSubPath == null) this.currentNotifyingSubPath = subPath; diff --git a/src/SyncTrayzor/Services/UpdateChecker/GithubApiClient.cs b/src/SyncTrayzor/Services/UpdateChecker/GithubApiClient.cs index 8d86063f..7aa5c278 100644 --- a/src/SyncTrayzor/Services/UpdateChecker/GithubApiClient.cs +++ b/src/SyncTrayzor/Services/UpdateChecker/GithubApiClient.cs @@ -34,11 +34,10 @@ public async Task FetchLatestReleaseAsync() var latestRelease = (from release in releases where !release.IsDraft && !release.IsPrerelease - let asset = release.Assets.FirstOrDefault(asset => asset.ContentType == "application/octet-stream") - where asset != null + where release.Assets.Any(assert => assert.ContentType == "application/octet-stream") let version = new Version(release.TagName.TrimStart('v')) orderby version descending - select new Release(version, asset.DownloadUrl, release.Body)).FirstOrDefault(); + select new Release(version, release.Url, release.Body)).FirstOrDefault(); return latestRelease; } diff --git a/src/SyncTrayzor/Services/UpdateChecker/ReleaseResponse.cs b/src/SyncTrayzor/Services/UpdateChecker/ReleaseResponse.cs index 29e25cb4..1ece445b 100644 --- a/src/SyncTrayzor/Services/UpdateChecker/ReleaseResponse.cs +++ b/src/SyncTrayzor/Services/UpdateChecker/ReleaseResponse.cs @@ -9,9 +9,6 @@ namespace SyncTrayzor.Services.UpdateChecker { public class ReleaseAssetResponse { - [JsonProperty("browser_download_url")] - public string DownloadUrl { get; set; } - [JsonProperty("content_type")] public string ContentType { get; set; } } @@ -24,6 +21,9 @@ public class ReleaseResponse [JsonProperty("name")] public string Name { get; set; } + [JsonProperty("html_url")] + public string Url { get; set; } + [JsonProperty("draft")] public bool IsDraft { get; set; } diff --git a/src/SyncTrayzor/Services/UpdateChecker/UpdateChecker.cs b/src/SyncTrayzor/Services/UpdateChecker/UpdateChecker.cs index ee93601a..5b833ede 100644 --- a/src/SyncTrayzor/Services/UpdateChecker/UpdateChecker.cs +++ b/src/SyncTrayzor/Services/UpdateChecker/UpdateChecker.cs @@ -58,7 +58,7 @@ public class UpdateChecker : IUpdateChecker private readonly IWindowManager windowManager; private readonly IGithubApiClient apiClient; - private readonly Func newersionAlertViewModelFactory; + private readonly Func newVersionAlertViewModelFactory; public Version LatestIgnoredVersion { get; set; } public event EventHandler VersionIgnored; @@ -70,7 +70,7 @@ public UpdateChecker( { this.windowManager = windowManager; this.apiClient = apiClient; - this.newersionAlertViewModelFactory = newVersionAlertViewModelFactory; + this.newVersionAlertViewModelFactory = newVersionAlertViewModelFactory; } public async Task FetchUpdatesAsync() @@ -110,7 +110,7 @@ public async Task CheckForUpdatesAsync() if (results.LatestVersionIsNewer) { - var vm = this.newersionAlertViewModelFactory(); + var vm = this.newVersionAlertViewModelFactory(); vm.Changelog = results.LatestVersionChangelog; vm.Version = results.LatestVersion; var result = this.windowManager.ShowDialog(vm); @@ -119,11 +119,15 @@ public async Task CheckForUpdatesAsync() logger.Info("Proceeding to download URL {0}", results.LatestVersionDownloadUrl); Process.Start(results.LatestVersionDownloadUrl); } - else + else if (vm.DontRemindMe) { logger.Info("Ignoring version {0}", results.LatestVersion); this.OnVersionIgnored(results.LatestVersion); } + else + { + logger.Info("Not installing version {0}, but will remind on next start", results.LatestVersion); + } } } diff --git a/src/SyncTrayzor/Services/WatchedFolderMonitor.cs b/src/SyncTrayzor/Services/WatchedFolderMonitor.cs index 09185046..cbcc9f08 100644 --- a/src/SyncTrayzor/Services/WatchedFolderMonitor.cs +++ b/src/SyncTrayzor/Services/WatchedFolderMonitor.cs @@ -50,7 +50,7 @@ public WatchedFolderMonitor(ISyncThingManager syncThingManager) private void Reset() { // Has everything loaded yet? - if (this._watchedFolders == null || this.syncThingManager.Folders == null) + if (this._watchedFolders == null) return; foreach (var watcher in directoryWatchers) @@ -62,22 +62,21 @@ private void Reset() if (this.syncThingManager.State != SyncThingState.Running || !this.syncThingManager.IsDataLoaded) return; - foreach (var watchedFolder in this._watchedFolders) + foreach (var folder in this.syncThingManager.FetchAllFolders()) { - Folder folder; - if (!this.syncThingManager.Folders.TryGetValue(watchedFolder, out folder)) + if (!this._watchedFolders.Contains(folder.FolderId)) continue; var watcher = new DirectoryWatcher(folder.Path, this.BackoffInterval, this.FolderExistenceCheckingInterval); - watcher.PreviewDirectoryChanged += (o, e) => e.Cancel = this.PreviewDirectoryChanged(folder.FolderId, e.SubPath); - watcher.DirectoryChanged += (o, e) => this.DirectoryChanged(folder.FolderId, e.SubPath); + watcher.PreviewDirectoryChanged += (o, e) => e.Cancel = this.PreviewDirectoryChanged(folder, e.SubPath); + watcher.DirectoryChanged += (o, e) => this.DirectoryChanged(folder, e.SubPath); this.directoryWatchers.Add(watcher); } } // Returns true to cancel - private bool PreviewDirectoryChanged(string folderId, string subPath) + private bool PreviewDirectoryChanged(Folder folder, string subPath) { // Is it a syncthing temp/special path? if (specialPaths.Any(x => subPath.StartsWith(x))) @@ -86,16 +85,11 @@ private bool PreviewDirectoryChanged(string folderId, string subPath) if (subPath == ignoresFilePath) { // Extra: tell SyncThing to update its ignores list - this.syncThingManager.ReloadIgnoresAsync(folderId); + this.syncThingManager.ReloadIgnoresAsync(folder.FolderId); return true; } - // If that path was just written by Syncthing, abort! - Folder folder; - if (!this.syncThingManager.Folders.TryGetValue(folderId, out folder)) - return true; - - if (folder.SyncState == FolderSyncState.Syncing || folder.SyncthingPaths.Contains(subPath)) + if (folder.SyncState == FolderSyncState.Syncing || folder.IsSyncingPath(subPath)) return true; // Syncthing applies regex from the top down - if a parent is ignored, all of its children are by default @@ -112,14 +106,13 @@ private bool PreviewDirectoryChanged(string folderId, string subPath) return false; } - private void DirectoryChanged(string folderId, string subPath) + private void DirectoryChanged(Folder folder, string subPath) { - Folder folder; // If it's currently syncing, then don't refresh it - if (!this.syncThingManager.Folders.TryGetValue(folderId, out folder) || folder.SyncState == FolderSyncState.Syncing) + if (folder.SyncState == FolderSyncState.Syncing) return; - this.syncThingManager.ScanAsync(folderId, subPath.Replace(Path.DirectorySeparatorChar, '/')); + this.syncThingManager.ScanAsync(folder.FolderId, subPath.Replace(Path.DirectorySeparatorChar, '/')); } } } diff --git a/src/SyncTrayzor/SyncThing/Api/LocalIndexUpdatedEvent.cs b/src/SyncTrayzor/SyncThing/Api/LocalIndexUpdatedEvent.cs index 1a77bbbd..2685c7b6 100644 --- a/src/SyncTrayzor/SyncThing/Api/LocalIndexUpdatedEvent.cs +++ b/src/SyncTrayzor/SyncThing/Api/LocalIndexUpdatedEvent.cs @@ -37,7 +37,7 @@ public override void Visit(IEventVisitor visitor) public override string ToString() { - return String.Format("", this.Id, this.Time, this.Data.Flags, this.Data.Modified, this.Data.Name, this.Data.Folder, this.Data.Size); + return String.Format("", this.Id, this.Time, this.Data.Flags, this.Data.Modified, this.Data.Name, this.Data.Folder, this.Data.Size); } } } diff --git a/src/SyncTrayzor/SyncThing/Folder.cs b/src/SyncTrayzor/SyncThing/Folder.cs index f0e365c3..40fc1678 100644 --- a/src/SyncTrayzor/SyncThing/Folder.cs +++ b/src/SyncTrayzor/SyncThing/Folder.cs @@ -15,23 +15,26 @@ public enum FolderSyncState public class FolderIgnores { - public List IgnorePatterns { get; private set; } - public List IncludeRegex { get; private set; } - public List ExcludeRegex { get; private set; } + public IReadOnlyList IgnorePatterns { get; private set; } + public IReadOnlyList IncludeRegex { get; private set; } + public IReadOnlyList ExcludeRegex { get; private set; } public FolderIgnores(List ignores, List patterns) { this.IgnorePatterns = ignores; - this.IncludeRegex = new List(); - this.ExcludeRegex = new List(); + var includeRegex = new List(); + var excludeRegex = new List(); foreach (var pattern in patterns) { if (pattern.StartsWith("(?exclude)")) - this.ExcludeRegex.Add(new Regex(pattern.Substring("(?exclude)".Length))); + excludeRegex.Add(new Regex(pattern.Substring("(?exclude)".Length))); else - this.IncludeRegex.Add(new Regex(pattern)); + includeRegex.Add(new Regex(pattern)); } + + this.IncludeRegex = includeRegex.AsReadOnly(); + this.ExcludeRegex = excludeRegex.AsReadOnly(); } } @@ -39,17 +42,57 @@ public class Folder { public string FolderId { get; private set; } public string Path { get; private set; } - public FolderSyncState SyncState { get; set; } - public HashSet SyncthingPaths { get; private set; } - public FolderIgnores Ignores { get; set; } + + private readonly object syncStateLock = new object(); + private FolderSyncState _syncState; + public FolderSyncState SyncState + { + get { lock (this.syncStateLock) { return this._syncState; } } + set { lock (this.syncStateLock) { this._syncState = value; } } + } + + private readonly object syncingPathsLock = new object(); + private HashSet syncingPaths { get; set; } + + private readonly object ignoresLock = new object(); + private FolderIgnores _ignores; + public FolderIgnores Ignores + { + get { lock (this.ignoresLock) { return this._ignores; } } + set { lock (this.ignoresLock) { this._ignores = value; } } + } public Folder(string folderId, string path, FolderIgnores ignores) { this.FolderId = folderId; this.Path = path; this.SyncState = FolderSyncState.Idle; - this.SyncthingPaths = new HashSet(); - this.Ignores = ignores; + this.syncingPaths = new HashSet(); + this._ignores = ignores; + } + + public bool IsSyncingPath(string path) + { + lock (this.syncingPathsLock) + { + return this.syncingPaths.Contains(path); + } + } + + public void AddSyncingPath(string path) + { + lock (this.syncingPathsLock) + { + this.syncingPaths.Add(path); + } + } + + public void RemoveSyncingPath(string path) + { + lock (this.syncingPathsLock) + { + this.syncingPaths.Remove(path); + } } } } diff --git a/src/SyncTrayzor/SyncThing/SyncThingConnectionsWatcher.cs b/src/SyncTrayzor/SyncThing/SyncThingConnectionsWatcher.cs index 90d8e581..89f0e365 100644 --- a/src/SyncTrayzor/SyncThing/SyncThingConnectionsWatcher.cs +++ b/src/SyncTrayzor/SyncThing/SyncThingConnectionsWatcher.cs @@ -41,6 +41,10 @@ public SyncThingConnectionsWatcher(ISyncThingApiClient apiClient) protected override async Task PollAsync() { var connections = await this.apiClient.FetchConnectionsAsync(); + + // We can be stopped in the time it takes this to complete + if (!this.Running) + return; var elapsed = DateTime.UtcNow - this.lastPollCompletion; this.lastPollCompletion = DateTime.UtcNow; diff --git a/src/SyncTrayzor/SyncThing/SyncThingEventWatcher.cs b/src/SyncTrayzor/SyncThing/SyncThingEventWatcher.cs index 02e08659..e1cf6403 100644 --- a/src/SyncTrayzor/SyncThing/SyncThingEventWatcher.cs +++ b/src/SyncTrayzor/SyncThing/SyncThingEventWatcher.cs @@ -60,6 +60,10 @@ protected override async Task PollAsync() { var events = await this.apiClient.FetchEventsAsync(this.lastEventId); + // We can be aborted in the time it takes to fetch the events + if (!this.Running) + return; + foreach (var evt in events) { this.lastEventId = Math.Max(this.lastEventId, evt.Id); diff --git a/src/SyncTrayzor/SyncThing/SyncThingManager.cs b/src/SyncTrayzor/SyncThing/SyncThingManager.cs index 686677e8..8a009ff8 100644 --- a/src/SyncTrayzor/SyncThing/SyncThingManager.cs +++ b/src/SyncTrayzor/SyncThing/SyncThingManager.cs @@ -2,6 +2,7 @@ using SyncTrayzor.SyncThing.Api; using SyncTrayzor.Utils; using System; +using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; @@ -25,14 +26,19 @@ public interface ISyncThingManager : IDisposable string ExecutablePath { get; set; } string ApiKey { get; set; } Uri Address { get; set; } + string SyncthingTraceFacilities { get; set; } + string SyncthingCustomHomeDir { get; set; } DateTime? StartedAt { get; } - Dictionary Folders { get; } SyncthingVersion Version { get; } void Start(); Task StopAsync(); void Kill(); void KillAllSyncthingProcesses(); + + bool TryFetchFolderById(string folderId, out Folder folder); + IReadOnlyCollection FetchAllFolders(); + Task ScanAsync(string folderId, string subPath); Task ReloadIgnoresAsync(string folderId); } @@ -49,21 +55,44 @@ public class SyncThingManager : ISyncThingManager public DateTime? StartedAt { get; private set; } + private readonly object stateLock = new object(); public SyncThingState State { get; private set; } + public bool IsDataLoaded { get; private set; } public event EventHandler DataLoaded; public event EventHandler StateChanged; public event EventHandler MessageLogged; public event EventHandler FolderSyncStateChanged; - public SyncThingConnectionStats TotalConnectionStats { get; private set; } + + private readonly object totalConnectionStatsLock = new object(); + private SyncThingConnectionStats _totalConnectionStats; + public SyncThingConnectionStats TotalConnectionStats + { + get { lock (this.totalConnectionStatsLock) { return this._totalConnectionStats; } } + set { lock (this.totalConnectionStatsLock) { this._totalConnectionStats = value; } } + } public event EventHandler TotalConnectionStatsChanged; + public event EventHandler ProcessExitedWithError; public string ExecutablePath { get; set; } public string ApiKey { get; set; } public Uri Address { get; set; } + public string SyncthingCustomHomeDir { get; set; } + public string SyncthingTraceFacilities { get; set; } + + // Folders is a ConcurrentDictionary, which suffices for most access + // However, it is sometimes set outright (in the case of an initial load or refresh), so we need this lock + // to create a memory barrier. The lock is only used when setting/fetching the field, not when accessing the + // Folders dictionary itself. + private readonly object foldersLock = new object(); + private ConcurrentDictionary _folders; + private ConcurrentDictionary folders + { + get { lock (this.foldersLock) { return this._folders; } } + set { lock (this.foldersLock) { this._folders = value; } } + } - public Dictionary Folders { get; private set; } public SyncthingVersion Version { get; private set; } public SyncThingManager( @@ -72,7 +101,7 @@ public SyncThingManager( ISyncThingEventWatcher eventWatcher, ISyncThingConnectionsWatcher connectionsWatcher) { - this.Folders = new Dictionary(); + this.folders = new ConcurrentDictionary(); this.eventDispatcher = new SynchronizedEventDispatcher(this); this.processRunner = processRunner; @@ -99,6 +128,8 @@ public void Start() this.processRunner.ApiKey = this.ApiKey; this.processRunner.HostAddress = this.Address.ToString(); this.processRunner.ExecutablePath = this.ExecutablePath; + this.processRunner.CustomHomeDir = this.SyncthingCustomHomeDir; + this.processRunner.Traces = this.SyncthingTraceFacilities; this.processRunner.Start(); this.SetState(SyncThingState.Starting); @@ -127,6 +158,16 @@ public void KillAllSyncthingProcesses() this.processRunner.KillAllSyncthingProcesses(); } + public bool TryFetchFolderById(string folderId, out Folder folder) + { + return this.folders.TryGetValue(folderId, out folder); + } + + public IReadOnlyCollection FetchAllFolders() + { + return new List(this.folders.Values).AsReadOnly(); + } + public Task ScanAsync(string folderId, string subPath) { return this.apiClient.ScanAsync(folderId, subPath); @@ -135,7 +176,7 @@ public Task ScanAsync(string folderId, string subPath) public async Task ReloadIgnoresAsync(string folderId) { Folder folder; - if (!this.Folders.TryGetValue(folderId, out folder)) + if (!this.folders.TryGetValue(folderId, out folder)) return; var ignores = await this.apiClient.FetchIgnoresAsync(folderId); @@ -144,22 +185,24 @@ public async Task ReloadIgnoresAsync(string folderId) private void SetState(SyncThingState state) { - if (state == this.State) - return; - - // We really need a proper state machine here.... - // There's a race if Syncthing can't start because the database is locked by another process on the same port - // In this case, we see the process as having failed, but the event watcher chimes in a split-second later with the 'Started' event. - // This runs the risk of transitioning us from Stopped -> Starting -> Stopepd -> Running, which is bad news for everyone - // So, get around this by enforcing strict state transitions. - if (this.State == SyncThingState.Stopped && state == SyncThingState.Running) - return; - var oldState = this.State; - this.State = state; + lock (this.stateLock) + { + if (state == this.State) + return; + + // We really need a proper state machine here.... + // There's a race if Syncthing can't start because the database is locked by another process on the same port + // In this case, we see the process as having failed, but the event watcher chimes in a split-second later with the 'Started' event. + // This runs the risk of transitioning us from Stopped -> Starting -> Stopepd -> Running, which is bad news for everyone + // So, get around this by enforcing strict state transitions. + if (this.State == SyncThingState.Stopped && state == SyncThingState.Running) + return; + + this.State = state; + } this.UpdateWatchersState(state); - this.eventDispatcher.Raise(this.StateChanged, new SyncThingStateChangedEventArgs(oldState, state)); } @@ -196,7 +239,9 @@ private async Task StartupCompleteAsync() return new Folder(folder.ID, path, new FolderIgnores(ignores.IgnorePatterns, ignores.RegexPatterns)); }); - this.Folders = (await Task.WhenAll(folderConstructionTasks)).ToDictionary(x => x.FolderId, x => x); + var folders = await Task.WhenAll(folderConstructionTasks); + this.folders = new ConcurrentDictionary(folders.Select(x => new KeyValuePair(x.FolderId, x))); + this.Version = versionTask.Result; this.OnDataLoaded(); @@ -206,19 +251,19 @@ private async Task StartupCompleteAsync() private void ItemStarted(string folderId, string item) { Folder folder; - if (!this.Folders.TryGetValue(folderId, out folder)) + if (!this.folders.TryGetValue(folderId, out folder)) return; // Don't know about it - folder.SyncthingPaths.Add(item); + folder.AddSyncingPath(item); } private void ItemFinished(string folderId, string item) { Folder folder; - if (!this.Folders.TryGetValue(folderId, out folder)) + if (!this.folders.TryGetValue(folderId, out folder)) return; // Don't know about it - folder.SyncthingPaths.Remove(item); + folder.RemoveSyncingPath(item); } private void OnMessageLogged(string logMessage) @@ -229,7 +274,7 @@ private void OnMessageLogged(string logMessage) private void OnSyncStateChanged(SyncStateChangedEventArgs e) { Folder folder; - if (!this.Folders.TryGetValue(e.FolderId, out folder)) + if (!this.folders.TryGetValue(e.FolderId, out folder)) return; // We don't know about this folder folder.SyncState = e.SyncState; diff --git a/src/SyncTrayzor/SyncThing/SyncThingPoller.cs b/src/SyncTrayzor/SyncThing/SyncThingPoller.cs index 3aa3cf69..ddf4128e 100644 --- a/src/SyncTrayzor/SyncThing/SyncThingPoller.cs +++ b/src/SyncTrayzor/SyncThing/SyncThingPoller.cs @@ -18,19 +18,23 @@ public abstract class SyncThingPoller : ISyncThingPoller private readonly TimeSpan pollingInterval; private readonly TimeSpan erroredWaitInterval; + private readonly object runningLock = new object(); private bool _running; public bool Running { - get { return this._running; } + get { lock (this.runningLock) { return this._running; } } set { - if (this._running == value) - return; - - this._running = value; - if (value) + lock (this.runningLock) { - this.Start(); + if (this._running == value) + return; + + this._running = value; + if (value) + { + this.Start(); + } } } } @@ -49,7 +53,7 @@ protected virtual async void Start() { try { - while (this._running) + while (this.Running) { bool errored = false; @@ -68,6 +72,11 @@ protected virtual async void Start() // Socket forcibly closed. Could be a restart, could be a termination. We'll have to continue and quit if we're stopped errored = true; } + catch (OperationCanceledException) + { + // Not entirely sure why this can occur. Blame Refit + errored = true; + } if (errored) await Task.Delay(this.erroredWaitInterval); @@ -75,7 +84,7 @@ protected virtual async void Start() } finally { - this._running = false; + this.Running = false; } } diff --git a/src/SyncTrayzor/SyncThing/SyncThingProcessRunner.cs b/src/SyncTrayzor/SyncThing/SyncThingProcessRunner.cs index 18af81c8..b7f7f1f1 100644 --- a/src/SyncTrayzor/SyncThing/SyncThingProcessRunner.cs +++ b/src/SyncTrayzor/SyncThing/SyncThingProcessRunner.cs @@ -36,6 +36,8 @@ public interface ISyncThingProcessRunner : IDisposable string ExecutablePath { get; set; } string ApiKey { get; set; } string HostAddress { get; set; } + string CustomHomeDir { get; set; } + string Traces { get; set; } event EventHandler MessageLogged; event EventHandler ProcessStopped; @@ -55,6 +57,8 @@ public class SyncThingProcessRunner : ISyncThingProcessRunner public string ExecutablePath { get; set; } public string ApiKey { get; set; } public string HostAddress { get; set; } + public string CustomHomeDir { get; set; } + public string Traces { get; set; } public event EventHandler MessageLogged; public event EventHandler ProcessStopped; @@ -65,7 +69,7 @@ public SyncThingProcessRunner() public void Start() { - logger.Info("Starting syncthing: ", this.ExecutablePath); + logger.Info("Starting syncthing: {0}", this.ExecutablePath); if (!File.Exists(this.ExecutablePath)) throw new Exception(String.Format("Unable to find Syncthing at path {0}", this.ExecutablePath)); @@ -81,10 +85,16 @@ public void Start() RedirectStandardOutput = true, }; + if (!String.IsNullOrWhiteSpace(this.Traces)) + { + processStartInfo.EnvironmentVariables["STTRACE"] = this.Traces; + } + this.process = Process.Start(processStartInfo); this.process.EnableRaisingEvents = true; this.process.OutputDataReceived += (o, e) => this.DataReceived(e.Data); + this.process.ErrorDataReceived += (o, e) => this.DataReceived(e.Data); this.process.BeginOutputReadLine(); this.process.BeginErrorReadLine(); @@ -108,16 +118,22 @@ private void KillInternal() private IEnumerable GenerateArguments() { - return defaultArguments.Concat(new[] + var args = new List(defaultArguments) { String.Format("-gui-apikey=\"{0}\"", this.ApiKey), String.Format("-gui-address=\"{0}\"", this.HostAddress) - }); + }; + + if (!String.IsNullOrWhiteSpace(this.CustomHomeDir)) + args.Add(String.Format("-home=\"{0}\"", this.CustomHomeDir)); + + return args; } private void DataReceived(string data) { - this.OnMessageLogged(data); + if (!String.IsNullOrWhiteSpace(data)) + this.OnMessageLogged(data); } public void Dispose() @@ -127,7 +143,9 @@ public void Dispose() private void OnProcessStopped() { - SyncThingExitStatus exitStatus = this.process == null ? SyncThingExitStatus.Success : (SyncThingExitStatus)this.process.ExitCode; + SyncThingExitStatus exitStatus = this.process == null ? SyncThingExitStatus.Success : (SyncThingExitStatus)this.process.ExitCode; + this.process = null; + logger.Info("Syncthing process stopped with exit status {0}", exitStatus); if (exitStatus == SyncThingExitStatus.Restarting || exitStatus == SyncThingExitStatus.Upgrading) { diff --git a/src/SyncTrayzor/SyncTrayzor.csproj b/src/SyncTrayzor/SyncTrayzor.csproj index eea1fad4..d3b63731 100644 --- a/src/SyncTrayzor/SyncTrayzor.csproj +++ b/src/SyncTrayzor/SyncTrayzor.csproj @@ -129,6 +129,7 @@ + @@ -180,8 +181,10 @@ + + @@ -241,6 +244,10 @@ Designer MSBuild:Compile + + Designer + MSBuild:Compile + Designer MSBuild:Compile @@ -249,7 +256,7 @@ Designer MSBuild:Compile - + Designer MSBuild:Compile @@ -293,6 +300,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/SyncTrayzor/Utils/SemaphoreSlimExtensions.cs b/src/SyncTrayzor/Utils/SemaphoreSlimExtensions.cs new file mode 100644 index 00000000..f74f082f --- /dev/null +++ b/src/SyncTrayzor/Utils/SemaphoreSlimExtensions.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace SyncTrayzor.Utils +{ + public static class SemaphoreSlimExtensions + { + private class SemaphoreSlimLock : IDisposable + { + private readonly SemaphoreSlim semaphore; + public SemaphoreSlimLock(SemaphoreSlim semaphore) + { + this.semaphore = semaphore; + } + + public void Dispose() + { + this.semaphore.Release(); + } + } + + public static IDisposable WaitDisposable(this SemaphoreSlim semaphore) + { + semaphore.Wait(); + return new SemaphoreSlimLock(semaphore); + } + + public static async Task WaitAsyncDisposable(this SemaphoreSlim semaphore) + { + await semaphore.WaitAsync().ConfigureAwait(false); + return new SemaphoreSlimLock(semaphore); + } + } +} diff --git a/src/SyncTrayzor/Utils/SynchronizedEventSubscriber.cs b/src/SyncTrayzor/Utils/SynchronizedEventSubscriber.cs new file mode 100644 index 00000000..2565f656 --- /dev/null +++ b/src/SyncTrayzor/Utils/SynchronizedEventSubscriber.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace SyncTrayzor.Utils +{ + public class SynchronizedEventSubscriber + { + private readonly SynchronizationContext synchronizationContext; + + public SynchronizedEventSubscriber(bool allowNoSynchronization = false) + : this(SynchronizationContext.Current, allowNoSynchronization) + { } + + public SynchronizedEventSubscriber(SynchronizationContext synchronizationContext, bool allowNoSynchronization = false) + { + if (!allowNoSynchronization && synchronizationContext == null) + throw new ArgumentException("synchronizationContext must be non-null if allowNoSynchronizationContext is false"); + + this.synchronizationContext = synchronizationContext; + } + + public EventHandler Subscribe(EventHandler forwarder) + { + return (o, e) => this.Post(_ => forwarder(o, e), null); + } + + public EventHandler Subscribe(EventHandler forwarder) + { + return (o, e) => this.Post(_ => forwarder(o, e), null); + } + + private void Post(SendOrPostCallback callback, object state) + { + if (this.synchronizationContext != null) + this.synchronizationContext.Post(callback, state); + else + callback(state); + } + } +} diff --git a/src/SyncTrayzor/Xaml/ActivateBehaviour.cs b/src/SyncTrayzor/Xaml/ActivateBehaviour.cs index 118e5fdd..af82630f 100644 --- a/src/SyncTrayzor/Xaml/ActivateBehaviour.cs +++ b/src/SyncTrayzor/Xaml/ActivateBehaviour.cs @@ -9,9 +9,9 @@ namespace SyncTrayzor.Xaml { // From http://stackoverflow.com/a/12254217/1086121 - public class ActivateBehaviour : Behavior + public class ActivateBehaviour : DetachingBehaviour { - private bool isActivated; + private bool altering; public bool Activated { @@ -19,28 +19,27 @@ public bool Activated set { SetValue(ActivatedProperty, value); } } - // Using a DependencyProperty as the backing store for Activated. This enables animation, styling, binding, etc... public static readonly DependencyProperty ActivatedProperty = DependencyProperty.Register("Activated", typeof(bool), typeof(ActivateBehaviour), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, e) => { - var behavior = (ActivateBehaviour)d; - if (!behavior.Activated || behavior.isActivated) + var behaviour = (ActivateBehaviour)d; + if (behaviour.altering || !(bool)e.NewValue) return; - // The Activated property is set to true but the Activated event (tracked by the - // isActivated field) hasn't been fired. Go ahead and activate the window. - if (behavior.AssociatedObject.WindowState == WindowState.Minimized) - behavior.AssociatedObject.WindowState = WindowState.Normal; - behavior.AssociatedObject.Activate(); + + if (behaviour.AssociatedObject.WindowState == WindowState.Minimized) + behaviour.AssociatedObject.WindowState = WindowState.Normal; + + behaviour.AssociatedObject.Activate(); })); - protected override void OnAttached() + protected override void AttachHandlers() { AssociatedObject.Activated += OnActivated; AssociatedObject.Deactivated += OnDeactivated; } - protected override void OnDetaching() + protected override void DetachHandlers() { AssociatedObject.Activated -= OnActivated; AssociatedObject.Deactivated -= OnDeactivated; @@ -48,13 +47,13 @@ protected override void OnDetaching() private void OnActivated(object sender, EventArgs eventArgs) { - this.isActivated = true; + this.altering = true; Activated = true; + this.altering = false; } private void OnDeactivated(object sender, EventArgs eventArgs) { - this.isActivated = false; Activated = false; } } diff --git a/src/SyncTrayzor/Xaml/DetachingBehaviour.cs b/src/SyncTrayzor/Xaml/DetachingBehaviour.cs new file mode 100644 index 00000000..25748bdf --- /dev/null +++ b/src/SyncTrayzor/Xaml/DetachingBehaviour.cs @@ -0,0 +1,55 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Data; +using System.Windows.Interactivity; + +namespace SyncTrayzor.Xaml +{ + // Adapted from http://dotnetbyexample.blogspot.co.uk/2011/04/safe-event-detachment-pattern-for.html + public abstract class DetachingBehaviour : Behavior where T : FrameworkElement + { + protected override void OnAttached() + { + base.OnAttached(); + this.AssociatedObject.Loaded += AssociatedObjectLoaded; + this.AssociatedObject.Unloaded += AssociatedObjectUnloaded; + } + + protected override void OnDetaching() + { + base.OnDetaching(); + this.Cleanup(); + } + + private bool isCleanedUp; + private void Cleanup() + { + if (!this.isCleanedUp) + { + this.isCleanedUp = true; + + this.AssociatedObject.Loaded -= AssociatedObjectLoaded; + this.AssociatedObject.Unloaded -= AssociatedObjectUnloaded; + BindingOperations.ClearAllBindings(this); // This was a surprise... + this.DetachHandlers(); + } + } + + private void AssociatedObjectLoaded(object sender, RoutedEventArgs e) + { + this.AttachHandlers(); + } + + private void AssociatedObjectUnloaded(object sender, RoutedEventArgs e) + { + this.Cleanup(); + } + + protected virtual void AttachHandlers() { } + protected virtual void DetachHandlers() { } + } +} diff --git a/src/SyncTrayzor/Xaml/Styles.xaml b/src/SyncTrayzor/Xaml/Resources.xaml similarity index 100% rename from src/SyncTrayzor/Xaml/Styles.xaml rename to src/SyncTrayzor/Xaml/Resources.xaml