diff --git a/src/modules/launcher/Wox.Core/Updater.cs b/src/modules/launcher/Wox.Core/Updater.cs deleted file mode 100644 index 9262d78f4d..0000000000 --- a/src/modules/launcher/Wox.Core/Updater.cs +++ /dev/null @@ -1,146 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Net; -using System.Net.Http; -using System.Net.Sockets; -using System.Linq; -using System.Threading.Tasks; -using System.Windows; -using JetBrains.Annotations; -using Squirrel; -using Newtonsoft.Json; -using Wox.Core.Resource; -using Wox.Plugin.SharedCommands; -using Wox.Infrastructure; -using Wox.Infrastructure.Http; -using Wox.Infrastructure.Logger; -using System.IO; - -namespace Wox.Core -{ - public class Updater - { - public string GitHubRepository { get; } - - public Updater(string gitHubRepository) - { - GitHubRepository = gitHubRepository; - } - - public async Task UpdateApp(bool silentIfLatestVersion = true) - { - UpdateManager updateManager; - UpdateInfo newUpdateInfo; - - try - { - updateManager = await GitHubUpdateManager(GitHubRepository); - } - catch (Exception e) when (e is HttpRequestException || e is WebException || e is SocketException) - { - Log.Exception($"|Updater.UpdateApp|Please check your connection and proxy settings to api.github.com.", e); - return; - } - - try - { - // UpdateApp CheckForUpdate will return value only if the app is squirrel installed - newUpdateInfo = await updateManager.CheckForUpdate().NonNull(); - } - catch (Exception e) when (e is HttpRequestException || e is WebException || e is SocketException) - { - Log.Exception($"|Updater.UpdateApp|Check your connection and proxy settings to api.github.com.", e); - updateManager.Dispose(); - return; - } - - var newReleaseVersion = Version.Parse(newUpdateInfo.FutureReleaseEntry.Version.ToString()); - var currentVersion = Version.Parse(Constant.Version); - - Log.Info($"|Updater.UpdateApp|Future Release <{newUpdateInfo.FutureReleaseEntry.Formatted()}>"); - - if (newReleaseVersion <= currentVersion) - { - if (!silentIfLatestVersion) - MessageBox.Show("You already have the latest Wox version"); - updateManager.Dispose(); - return; - } - - try - { - await updateManager.DownloadReleases(newUpdateInfo.ReleasesToApply); - } - catch (Exception e) when (e is HttpRequestException || e is WebException || e is SocketException) - { - Log.Exception($"|Updater.UpdateApp|Check your connection and proxy settings to github-cloud.s3.amazonaws.com.", e); - updateManager.Dispose(); - return; - } - - await updateManager.ApplyReleases(newUpdateInfo); - - if (Constant.IsPortableMode) - { - var targetDestination = updateManager.RootAppDirectory + $"\\app-{newReleaseVersion.ToString()}\\{Constant.PortableFolderName}"; - FilesFolders.Copy(Constant.PortableDataPath, targetDestination); - if (!FilesFolders.VerifyBothFolderFilesEqual(Constant.PortableDataPath, targetDestination)) - MessageBox.Show(string.Format("Wox was not able to move your user profile data to the new update version. Please manually" + - "move your profile data folder from {0} to {1}", Constant.PortableDataPath, targetDestination)); - } - else - { - await updateManager.CreateUninstallerRegistryEntry(); - } - - var newVersionTips = NewVersinoTips(newReleaseVersion.ToString()); - - MessageBox.Show(newVersionTips); - Log.Info($"|Updater.UpdateApp|Update success:{newVersionTips}"); - - // always dispose UpdateManager - updateManager.Dispose(); - } - - [UsedImplicitly] - private class GithubRelease - { - [JsonProperty("prerelease")] - public bool Prerelease { get; [UsedImplicitly] set; } - - [JsonProperty("published_at")] - public DateTime PublishedAt { get; [UsedImplicitly] set; } - - [JsonProperty("html_url")] - public string HtmlUrl { get; [UsedImplicitly] set; } - } - - /// https://github.com/Squirrel/Squirrel.Windows/blob/master/src/Squirrel/UpdateManager.Factory.cs - private async Task GitHubUpdateManager(string repository) - { - var uri = new Uri(repository); - var api = $"https://api.github.com/repos{uri.AbsolutePath}/releases"; - - var json = await Http.Get(api); - - var releases = JsonConvert.DeserializeObject>(json); - var latest = releases.Where(r => !r.Prerelease).OrderByDescending(r => r.PublishedAt).First(); - var latestUrl = latest.HtmlUrl.Replace("/tag/", "/download/"); - - var client = new WebClient { Proxy = Http.WebProxy() }; - var downloader = new FileDownloader(client); - - var manager = new UpdateManager(latestUrl, urlDownloader: downloader); - - return manager; - } - - public string NewVersinoTips(string version) - { - var translater = InternationalizationManager.Instance; - var tips = string.Format(translater.GetTranslation("newVersionTips"), version); - return tips; - } - - } -} \ No newline at end of file diff --git a/src/modules/launcher/Wox.Core/Wox.Core.csproj b/src/modules/launcher/Wox.Core/Wox.Core.csproj index dee076e48c..081071d691 100644 --- a/src/modules/launcher/Wox.Core/Wox.Core.csproj +++ b/src/modules/launcher/Wox.Core/Wox.Core.csproj @@ -58,7 +58,6 @@ - diff --git a/src/modules/launcher/Wox/App.xaml.cs b/src/modules/launcher/Wox/App.xaml.cs index f6dcc8ee2f..01e35d2d67 100644 --- a/src/modules/launcher/Wox/App.xaml.cs +++ b/src/modules/launcher/Wox/App.xaml.cs @@ -25,7 +25,6 @@ namespace Wox private Settings _settings; private MainViewModel _mainVM; private SettingWindowViewModel _settingsVM; - private readonly Updater _updater = new Updater(Wox.Properties.Settings.Default.GithubRepo); private readonly Alphabet _alphabet = new Alphabet(); private StringMatcher _stringMatcher; @@ -53,7 +52,7 @@ namespace Wox ImageLoader.Initialize(); - _settingsVM = new SettingWindowViewModel(_updater); + _settingsVM = new SettingWindowViewModel(); _settings = _settingsVM.Settings; _alphabet.Initialize(_settings); @@ -83,40 +82,11 @@ namespace Wox RegisterExitEvents(); - AutoStartup(); - AutoUpdates(); - _mainVM.MainWindowVisibility = _settings.HideOnStartup ? Visibility.Hidden : Visibility.Visible; Log.Info("|App.OnStartup|End Wox startup ---------------------------------------------------- "); }); } - - private void AutoStartup() - { - } - - //[Conditional("RELEASE")] - private void AutoUpdates() - { - Task.Run(async () => - { - if (_settings.AutoUpdates) - { - // check udpate every 5 hours - var timer = new Timer(1000 * 60 * 60 * 5); - timer.Elapsed += async (s, e) => - { - await _updater.UpdateApp(); - }; - timer.Start(); - - // check updates on startup - await _updater.UpdateApp(); - } - }); - } - private void RegisterExitEvents() { AppDomain.CurrentDomain.ProcessExit += (s, e) => Dispose(); diff --git a/src/modules/launcher/Wox/PublicAPIInstance.cs b/src/modules/launcher/Wox/PublicAPIInstance.cs index 21057a78e9..a1b2e5119e 100644 --- a/src/modules/launcher/Wox/PublicAPIInstance.cs +++ b/src/modules/launcher/Wox/PublicAPIInstance.cs @@ -4,8 +4,7 @@ using System.Linq; using System.Net; using System.Threading.Tasks; using System.Windows; -using Squirrel; -using Wox.Core; + using Wox.Core.Plugin; using Wox.Core.Resource; using Wox.Helper; @@ -63,12 +62,12 @@ namespace Wox // which will cause ungraceful exit SaveAppAllSettings(); - UpdateManager.RestartApp(); + Squirrel.UpdateManager.RestartApp(); } public void CheckForNewUpdate() { - _settingsVM.UpdateApp(); + //_settingsVM.UpdateApp(); } public void SaveAppAllSettings() @@ -101,7 +100,7 @@ namespace Wox { Application.Current.Dispatcher.Invoke(() => { - var msg = useMainWindowAsOwner ? new Msg {Owner = Application.Current.MainWindow} : new Msg(); + var msg = useMainWindowAsOwner ? new Msg { Owner = Application.Current.MainWindow } : new Msg(); msg.Show(title, subTitle, iconPath); }); } diff --git a/src/modules/launcher/Wox/ResultListBox.xaml.cs b/src/modules/launcher/Wox/ResultListBox.xaml.cs index 6b46644900..1f8b1a1513 100644 --- a/src/modules/launcher/Wox/ResultListBox.xaml.cs +++ b/src/modules/launcher/Wox/ResultListBox.xaml.cs @@ -6,7 +6,6 @@ namespace Wox { public partial class ResultListBox { - protected object _lock = new object(); private Point _lastpos; private ListBoxItem curItem = null; public ResultListBox() @@ -24,34 +23,25 @@ namespace Wox private void OnMouseEnter(object sender, MouseEventArgs e) { - lock(_lock) - { - curItem = (ListBoxItem)sender; - var p = e.GetPosition((IInputElement)sender); - _lastpos = p; - } + curItem = (ListBoxItem)sender; + var p = e.GetPosition((IInputElement)sender); + _lastpos = p; } private void OnMouseMove(object sender, MouseEventArgs e) { - lock(_lock) + var p = e.GetPosition((IInputElement)sender); + if (_lastpos != p) { - var p = e.GetPosition((IInputElement)sender); - if (_lastpos != p) - { - ((ListBoxItem)sender).IsSelected = true; - } + ((ListBoxItem)sender).IsSelected = true; } } private void ListBox_PreviewMouseDown(object sender, MouseButtonEventArgs e) { - lock(_lock) + if (curItem != null) { - if (curItem != null) - { - curItem.IsSelected = true; - } + curItem.IsSelected = true; } } } diff --git a/src/modules/launcher/Wox/UpdateManager.cs b/src/modules/launcher/Wox/UpdateManager.cs new file mode 100644 index 0000000000..0dde3b8b2c --- /dev/null +++ b/src/modules/launcher/Wox/UpdateManager.cs @@ -0,0 +1,65 @@ +// code block is from +// unblocking https://github.com/Squirrel/Squirrel.Windows/blob/master/src/Squirrel/UpdateManager.cs +// https://github.com/Squirrel/Squirrel.Windows/blob/develop/COPYING +// license is MIT + +using System; +using System.Diagnostics; +using System.IO; +using System.Reflection; +using System.Threading; + +namespace Squirrel +{ + public sealed partial class UpdateManager + { + public static void RestartApp(string exeToStart = null, string arguments = null) + { + // NB: Here's how this method works: + // + // 1. We're going to pass the *name* of our EXE and the params to + // Update.exe + // 2. Update.exe is going to grab our PID (via getting its parent), + // then wait for us to exit. + // 3. We exit cleanly, dropping any single-instance mutexes or + // whatever. + // 4. Update.exe unblocks, then we launch the app again, possibly + // launching a different version than we started with (this is why + // we take the app's *name* rather than a full path) + + exeToStart = exeToStart ?? Path.GetFileName(Assembly.GetEntryAssembly().Location); + var argsArg = arguments != null ? + string.Format("-a \"{0}\"", arguments) : ""; + + Process.Start(getUpdateExe(), string.Format("--processStartAndWait {0} {1}", exeToStart, argsArg)); + + // NB: We have to give update.exe some time to grab our PID, but + // we can't use WaitForInputIdle because we probably don't have + // whatever WaitForInputIdle considers a message loop. + Thread.Sleep(500); + Environment.Exit(0); + } + + static string getUpdateExe() + { + var assembly = Assembly.GetEntryAssembly(); + + // Are we update.exe? + if (assembly != null && + Path.GetFileName(assembly.Location).Equals("update.exe", StringComparison.OrdinalIgnoreCase) && + assembly.Location.IndexOf("app-", StringComparison.OrdinalIgnoreCase) == -1 && + assembly.Location.IndexOf("SquirrelTemp", StringComparison.OrdinalIgnoreCase) == -1) + { + return Path.GetFullPath(assembly.Location); + } + + assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly(); + + var updateDotExe = Path.Combine(Path.GetDirectoryName(assembly.Location), "..\\Update.exe"); + var target = new FileInfo(updateDotExe); + + if (!target.Exists) throw new Exception("Update.exe not found, not a Squirrel-installed app?"); + return target.FullName; + } + } +} diff --git a/src/modules/launcher/Wox/ViewModel/SettingWindowViewModel.cs b/src/modules/launcher/Wox/ViewModel/SettingWindowViewModel.cs index f9160df9f0..f3b9e14b8e 100644 --- a/src/modules/launcher/Wox/ViewModel/SettingWindowViewModel.cs +++ b/src/modules/launcher/Wox/ViewModel/SettingWindowViewModel.cs @@ -21,12 +21,10 @@ namespace Wox.ViewModel { public class SettingWindowViewModel : BaseModel { - private readonly Updater _updater; private readonly WoxJsonStorage _storage; - public SettingWindowViewModel(Updater updater) + public SettingWindowViewModel() { - _updater = updater; _storage = new WoxJsonStorage(); Settings = _storage.Load(); Settings.PropertyChanged += (s, e) => @@ -42,11 +40,6 @@ namespace Wox.ViewModel public Settings Settings { get; set; } - public async void UpdateApp() - { - await _updater.UpdateApp(false); - } - public void Save() { _storage.Save(); @@ -122,50 +115,6 @@ namespace Wox.ViewModel public List Languages => _translater.LoadAvailableLanguages(); public IEnumerable MaxResultsRange => Enumerable.Range(2, 16); - public string TestProxy() - { - var proxyServer = Settings.Proxy.Server; - var proxyUserName = Settings.Proxy.UserName; - if (string.IsNullOrEmpty(proxyServer)) - { - return InternationalizationManager.Instance.GetTranslation("serverCantBeEmpty"); - } - if (Settings.Proxy.Port <= 0) - { - return InternationalizationManager.Instance.GetTranslation("portCantBeEmpty"); - } - - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_updater.GitHubRepository); - - if (string.IsNullOrEmpty(proxyUserName) || string.IsNullOrEmpty(Settings.Proxy.Password)) - { - request.Proxy = new WebProxy(proxyServer, Settings.Proxy.Port); - } - else - { - request.Proxy = new WebProxy(proxyServer, Settings.Proxy.Port) - { - Credentials = new NetworkCredential(proxyUserName, Settings.Proxy.Password) - }; - } - try - { - var response = (HttpWebResponse)request.GetResponse(); - if (response.StatusCode == HttpStatusCode.OK) - { - return InternationalizationManager.Instance.GetTranslation("proxyIsCorrect"); - } - else - { - return InternationalizationManager.Instance.GetTranslation("proxyConnectFailed"); - } - } - catch - { - return InternationalizationManager.Instance.GetTranslation("proxyConnectFailed"); - } - } - #endregion #region plugin @@ -281,11 +230,6 @@ namespace Wox.ViewModel Title = "Install plugins from: ", SubTitle = Plugin }, - new Result - { - Title = $"Open Source: {_updater.GitHubRepository}", - SubTitle = "Please star it!" - } }; var vm = new ResultsViewModel(); vm.AddResults(results, "PREVIEW"); @@ -392,9 +336,6 @@ namespace Wox.ViewModel #endregion #region about - - public string Github => _updater.GitHubRepository; - public string ReleaseNotes => _updater.GitHubRepository + @"/releases/latest"; public static string Version => Constant.Version; public string ActivatedTimes => string.Format(_translater.GetTranslation("about_activate_times"), Settings.ActivateTimes); #endregion