示例#1
0
        /// <summary>
        /// Raises the <see cref="E:System.Windows.Application.Startup"/> event.
        /// </summary>
        /// <param name="e">
        /// A <see cref="T:System.Windows.StartupEventArgs"/> that contains the event data.
        /// </param>
        protected override void OnStartup(StartupEventArgs e)
        {
            this.DispatcherUnhandledException += this.ApplicationDispatcherUnhandledException;

            var splashWindow = new SplashScreenWindow(this.applicationResources);

            try
            {
                // show the splash screen
                splashWindow.Show();

                // initialize bootstarpper
                var bootstrapper = new CustomBootstrapper(this.applicationResources);

                // initialize application view model
                var applicationViewModel = new CustomApplicationViewModel(bootstrapper, this.applicationResources);

                // create and show application window
                this.applicationWindow = ApplicationWindowFactory.CreateApplicationWindow(applicationViewModel, this.applicationResources);
                this.applicationWindow.OnStartup(splashWindow);
                this.applicationWindow.Show();

                // once applicationWindow is in place, close splash screen
                splashWindow.Close();

                TraceUI.Log.Info("Application successfully started");
            }
            catch (Exception ex)
            {
                splashWindow.Close();
                TraceUI.Log.Exception(ex);
                throw;
            }
        }
        /// <summary>The application main stopping point</summary>
        /// <param name="e"></param>
        protected override void OnExit(ExitEventArgs e)
        {
            _taskbarIcon?.Dispose();
            _splashScreen?.Close();
            _splashScreen = null;

            SMA.Core.Logger?.Shutdown();
#pragma warning disable CS0436 // Type conflicts with imported type
            ModuleInitializer.SentryInstance?.Dispose();
#pragma warning restore CS0436 // Type conflicts with imported type

            base.OnExit(e);
        }
 public static void CloseActualSplashScreen()
 {
     splashScreen.Dispatcher.Invoke(() =>
     {
         splashScreen.Close();
     });
 }
示例#4
0
        static void Main()
        {
            Logging.Info("+static Main()");

            try
            {
                splashscreen_window.UpdateMessage("Logging in");

                LoginWindow login_window = new LoginWindow();
                login_window.ChooseLogin(splashscreen_window);

                splashscreen_window.Close();
                WPFDoEvents.DoEvents();

                try
                {
                    application.Run();
                }
                catch (Exception ex)
                {
                    Logging.Error(ex, "Exception caught at Main() application.Run().  Disaster.");
                }


                DoShutdown();
            }

            catch (Exception ex)
            {
                Logging.Error(ex, "Exception caught at Main().  Disaster.");
            }

            Logging.Info("-static Main()");
        }
示例#5
0
        protected override void InitializeShell()
        {
            SetGlobalAppProperties();

            if (Container.Resolve <IAllowStartService>().AllowStart() == false)
            {
                Application.Current.Shutdown();
            }

            #region IEventServiceClient

            //старт клиентской части сервиса синхронизации
            #if DEBUG
            if (true)
            #endif
            Container.Resolve <IEventServiceClient>().Start();
            Container.Resolve <EventServiceUnitWatcher>().Start();
            #endregion

            Container.Resolve <IEventAggregator>().GetEvent <ModuleIsInitializedEvent>().Subscribe(moduleType =>
            {
                _initializedModules.Add(moduleType);

                ModuleIsInitialized?.Invoke((double)_initializedModules.Count / _modules.Count);

                if (_modules.Select(moduleInfo => moduleInfo.ModuleName).AllContainsIn(_initializedModules.Select(type => type.Name)))
                {
                    AllModulesAreInitialized?.Invoke();
                    Application.Current.MainWindow.Show();
                    _splashScreenWindow.Close();
                }
            });
        }
示例#6
0
        protected override void OnStartup(StartupEventArgs e)
        {
            _splashScreen.Show();

            Thread.Sleep(3000);

            this.MainWindow.Show();

            _splashScreen.Close();
            _splashScreen = null;
        }
示例#7
0
        protected override async void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            //Initialize the splash screen and set it as the application main window
            var splashScreen = new SplashScreenWindow();

            this.MainWindow = splashScreen;
            splashScreen.Show();
            splashScreen.SplashScreenInfoLabel.Content = "Loading Application...";
            await InitializeIOFolders();

            InitializeStyleAsync();

            //In order to ensure the UI stays responsive, we need to
            //Do the work on a different thread
            await Task.Factory.StartNew(() =>
            {
                try
                {
                    //we need to do the work in batches so that we can report progress
                    for (int i = 1; i <= 100; i++)
                    {
                        //Simulate a part of work being done
                        Thread.Sleep(10);

                        //Because we're not on the UI thread, we need to use the Dispatcher
                        //Associated with the splash screen to update the progress bar
                        splashScreen.SplashScreenProgressBar.Dispatcher.Invoke(() => splashScreen.SplashScreenProgressBar.IsIndeterminate = true);
                    }

                    //Once we're done we need to use the Dispatcher
                    //to create and show the MainWindow
                    this.Dispatcher.Invoke(() =>
                    {
                        //Initialize the main window, set it as the application main window
                        //and close the splash screen
                        var mainWindow  = new MainWindow();
                        this.MainWindow = mainWindow;
                        mainWindow.Show();
                        mainWindow.Activate();
                        splashScreen.Close();
                    });
                }
                catch (Exception ex)
                {
                    GlobalVars.Loggi.Error(ex, ex.Message);
                }
            });
        }
示例#8
0
        private async void Application_Startup(object sender, StartupEventArgs e)
        {
            _mainWindow   = new MainWindow();
            _splashWindow = new SplashScreenWindow();


            _splashWindow.Show();

            await Task.Run(() =>
            {
                _mainWindow.LoadNetworkItems();
            });

            _splashWindow.Close();
            _mainWindow.Show();
        }
示例#9
0
        protected override DependencyObject CreateShell()
        {
            SplashScreenWindow splashscreenwindow = new SplashScreenWindow();

            splashscreenwindow.Show();
            ApplicationService.CreateFolder();
            ApplicationService.LoadFiles();
            MainView shell = new MainView();


            this.Container.RegisterInstance <IShell>(shell);
            this.Container.RegisterType <IPlayFile, PlayFile>();
            shell.Dispatcher.BeginInvoke((Action) delegate
            {
                shell.Show();
                splashscreenwindow.Close();
            });
            return(shell);
        }
示例#10
0
        protected override DependencyObject CreateShell()
        {
            SplashScreenWindow splashscreenwindow = new SplashScreenWindow();

            splashscreenwindow.Show();

            IModule thememodule = Container.Resolve <ThemeModule>();

            thememodule.Initialize();
            base.InitializeModules();

            var shell = this.Container.Resolve <IShell>() as MainView;

            shell.Dispatcher.BeginInvoke((Action) delegate
            {
                //shell.Show();
                splashscreenwindow.Close();
            });
            return(shell);
        }
示例#11
0
        //
        // Переопределенный метод OnStartup выполняет здесь две задачи:
        //
        //    1. Splash Screen.
        //         Показывает splash screen, а только затем показывает главное окно приложения.
        //         Про реализацию splash screen:
        //         https://wpf.programmingpedia.net/en/tutorial/3948/creating-splash-screen-in-wpf
        //
        //    2. Является Application Root нашего приложения.
        //         Создает экземпляр модели — единственный на всё приложение.
        //
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // Создаем окно splash screen, временно делаем его главным
            // окном приложения и показываем его пользователю
            var splashScreen = new SplashScreenWindow();

            MainWindow = splashScreen;
            splashScreen.Show();

            // Чтобы UI оставался отзывчивым, асинхронно делаем паузу
            // и потом переходим к показу настоящего главного окна
            Task.Factory.StartNew(() =>
            {
                // Делаем паузу
                System.Threading.Thread.Sleep(5000);

                // Создаем настоящее главное окно типа PuzzleWindow, делаем его главным окном
                // приложения и показываем его пользователю. Поскольку мы сейчас вне основного
                // UI-потока, то обращение к тому, что имеет отношение UI-потоку, должно быть
                // вызвано потокобезопасно. В WPF это делается при помощи методов Invoke или
                // BeginInvoke объекта Dispatcher, который как раз и дает доступ к UI-потоку.
                Dispatcher.Invoke(() =>
                {
                    // Создаем модель
                    Model = new PuzzleDomainModel();

                    // Создаем настоящее главное окно типа PuzzleWindow, делаем его
                    // главным окном приложения и показываем его пользователю
                    MainWindow = new PuzzleWindow {
                        DataContext = new PuzzleViewModel()
                    };
                    MainWindow.Show();

                    // Закрываем splash screen
                    splashScreen.Close();
                });
            });
        }
示例#12
0
        protected override void OnStartup(StartupEventArgs e)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
            DispatcherUnhandledException += ApplicationDispatcherUnhandledException;
            string softwareRenderMode = ConfigurationManager.AppSettings["SoftwareRenderMode"];

            if (string.Compare(softwareRenderMode, "TRUE", true) == 0)
            {
                Lib.SoftwareRenderMode = true;
            }

            base.OnStartup(e);

            MainWindow mainWindow;

#if !DEBUG
            SplashScreenViewModel splashScreen = SplashScreenFactory.CreateOrGetSplashScreen();
            splashScreen.SourceUri    = new Uri("pack://application:,,,/Resources/Splash.jpg");
            splashScreen.ShowProgress = false;
            splashScreen.Info         = "Loading ...";
            SplashScreenWindow splashScreenWindow = new SplashScreenWindow(splashScreen);

            try
            {
                splashScreenWindow.Show();
#endif
            MagicDatabaseManager.Initialise(MultiPartCardManager.Instance);
            mainWindow = new MainWindow();
#if !DEBUG
        }

        finally
        {
            splashScreenWindow.Close();
        }
#endif
            _started = true;
            mainWindow.Show();
        }
示例#13
0
        internal Window SplashScreenWindowShow(bool isSplashScreenWindowShow)
        {
            if (isSplashScreenWindowShow)
            {
                var splashScreenWindow = new SplashScreenWindow();
                splashScreenWindow.Show();

                Thread.Sleep(3000);

                var mainWindow = new MainWindow();
                mainWindow.Dispatcher.BeginInvoke((Action) delegate
                {
                    mainWindow.Show();
                    splashScreenWindow.Close();
                });
                return(mainWindow);
            }
            else
            {
                return(Container.Resolve <MainWindow>());
            }
        }
示例#14
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            // Inicializa el Splash Screen como pantalla principal
            var splashScreen = new SplashScreenWindow();

            this.MainWindow = splashScreen;
            splashScreen.Show();

            Task.Factory.StartNew(() =>
            {
                System.Threading.Thread.Sleep(3000);

                this.Dispatcher.Invoke(() =>
                {
                    var mainWindow  = new LoginWindow();
                    this.MainWindow = mainWindow;
                    mainWindow.Show();
                    splashScreen.Close();
                });
            });
        }
示例#15
0
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        public static async void Initialize()
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
#if !DEBUG
            var splashScreenWindow = new SplashScreenWindow();
            splashScreenWindow.Show();
            var updateCheck = Update.Updater.StartupUpdateCheck(splashScreenWindow);
            while (!updateCheck.IsCompleted)
            {
                await Task.Delay(TimeSpan.FromSeconds(0.5));
            }
#endif

            MainWindow = new MainWindow();
            MainWindow.LoadConfigSettings();
            MainWindow.Show();

#if !DEBUG
            // Only close it after opening MainWindow!
            splashScreenWindow.Close();
            UpdateOverlayAsync();
#endif
        }
示例#16
0
        public static void Initialize()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            Config.Load();
            ConfigManager.Run();
            Logger.Initialzie();
            Helper.UpdateAppTheme();
            var splashScreenWindow = new SplashScreenWindow();

            splashScreenWindow.Show();
            Game = new GameV2();
            if (!HearthStatsAPI.LoadCredentials() && Config.Instance.ShowLoginDialog)
            {
                var loginWindow = new LoginWindow();
                splashScreenWindow.Close();
                loginWindow.ShowDialog();
                if (!loginWindow.LoginResult)
                {
                    Application.Current.Shutdown();
                    return;
                }
                splashScreenWindow = new SplashScreenWindow();
                splashScreenWindow.Show();
            }
            MainWindow = new MainWindow();
            MainWindow.LoadConfigSettings();
            MainWindow.Show();
            splashScreenWindow.Close();

            if (ConfigManager.UpdatedVersion != null)
            {
                Updater.Cleanup();
                MainWindow.FlyoutUpdateNotes.IsOpen = true;
                MainWindow.UpdateNotesControl.LoadUpdateNotes();
            }
            NetDeck.CheckForChromeExtention();
            DataIssueResolver.Run();

            if (Helper.HearthstoneDirExists)
            {
                if (Helper.UpdateLogConfig && Game.IsRunning)
                {
                    MainWindow.ShowMessageAsync("Restart Hearthstone",
                                                "This is either your first time starting HDT or the log.config file has been updated. Please restart Hearthstone, for HDT to work properly.");
                }
                LogReaderManager.Start(Game);
            }
            else
            {
                MainWindow.ShowHsNotInstalledMessage();
            }

            Helper.CopyReplayFiles();
            BackupManager.Run();

            if (Config.Instance.PlayerWindowOnStart)
            {
                Windows.PlayerWindow.Show();
            }
            if (Config.Instance.OpponentWindowOnStart)
            {
                Windows.OpponentWindow.Show();
            }
            if (Config.Instance.TimerWindowOnStartup)
            {
                Windows.TimerWindow.Show();
            }

            if (Config.Instance.HearthStatsSyncOnStart && HearthStatsAPI.IsLoggedIn)
            {
                HearthStatsManager.SyncAsync(background: true);
            }

            PluginManager.Instance.LoadPlugins();
            MainWindow.Options.OptionsTrackerPlugins.Load();
            PluginManager.Instance.StartUpdateAsync();

            UpdateOverlayAsync();
            NewsUpdater.UpdateAsync();
            Initialized = true;
        }
示例#17
0
        public static async void Initialize()
        {
            Log.Info($"Operating System: {Helper.GetWindowsVersion()}, .NET Framework: {Helper.GetInstalledDotNetVersion()}");
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            Config.Load();
            var splashScreenWindow = new SplashScreenWindow();

#if (SQUIRREL)
            if (Config.Instance.CheckForUpdates)
            {
                var updateCheck = Updater.StartupUpdateCheck(splashScreenWindow);
                while (!updateCheck.IsCompleted)
                {
                    await Task.Delay(500);

                    if (splashScreenWindow.SkipUpdate)
                    {
                        break;
                    }
                }
            }
#endif
            splashScreenWindow.ShowConditional();
            Log.Initialize();
            ConfigManager.Run();
            var newUser = ConfigManager.PreviousVersion == null;
            LogConfigUpdater.Run().Forget();
            LogConfigWatcher.Start();
            Helper.UpdateAppTheme();
            ThemeManager.Run();
            ResourceMonitor.Run();
            Game = new GameV2();
            LoginType loginType;
            var       loggedIn = HearthStatsAPI.LoadCredentials();
            if (!loggedIn && Config.Instance.ShowLoginDialog)
            {
                var loginWindow = new LoginWindow();
                splashScreenWindow.Close();
                loginWindow.ShowDialog();
                if (loginWindow.LoginResult == LoginType.None)
                {
                    Application.Current.Shutdown();
                    return;
                }
                loginType          = loginWindow.LoginResult;
                splashScreenWindow = new SplashScreenWindow();
                splashScreenWindow.ShowConditional();
            }
            else
            {
                loginType = loggedIn ? LoginType.AutoLogin : LoginType.AutoGuest;
            }
            MainWindow = new MainWindow();
            MainWindow.LoadConfigSettings();
            if (Config.Instance.ReselectLastDeckUsed)
            {
                MainWindow.SelectLastUsedDeck();
                Config.Instance.ReselectLastDeckUsed = false;
                Config.Save();
            }
            MainWindow.Show();
            splashScreenWindow.Close();

            if (ConfigManager.UpdatedVersion != null)
            {
#if (!SQUIRREL)
                Updater.Cleanup();
#endif
                MainWindow.FlyoutUpdateNotes.IsOpen = true;
                MainWindow.UpdateNotesControl.SetHighlight(ConfigManager.PreviousVersion);
            }
            NetDeck.CheckForChromeExtention();
            DataIssueResolver.Run();

#if (!SQUIRREL)
            Helper.CopyReplayFiles();
#endif
            BackupManager.Run();

            if (Config.Instance.PlayerWindowOnStart)
            {
                Windows.PlayerWindow.Show();
            }
            if (Config.Instance.OpponentWindowOnStart)
            {
                Windows.OpponentWindow.Show();
            }
            if (Config.Instance.TimerWindowOnStartup)
            {
                Windows.TimerWindow.Show();
            }

            if (Config.Instance.HearthStatsSyncOnStart && HearthStatsAPI.IsLoggedIn)
            {
                HearthStatsManager.SyncAsync(background: true);
            }

            PluginManager.Instance.LoadPlugins();
            MainWindow.Options.OptionsTrackerPlugins.Load();
            PluginManager.Instance.StartUpdateAsync();

            UpdateOverlayAsync();

            if (Config.Instance.ShowCapturableOverlay)
            {
                Windows.CapturableOverlay = new CapturableOverlayWindow();
                Windows.CapturableOverlay.Show();
            }

            if (LogConfigUpdater.LogConfigUpdateFailed)
            {
                MainWindow.ShowLogConfigUpdateFailedMessage().Forget();
            }
            else if (LogConfigUpdater.LogConfigUpdated && Game.IsRunning)
            {
                MainWindow.ShowMessageAsync("Hearthstone restart required", "The log.config file has been updated. HDT may not work properly until Hearthstone has been restarted.");
                Overlay.ShowRestartRequiredWarning();
            }
            LogReaderManager.Start(Game).Forget();

            NewsUpdater.UpdateAsync();
            HotKeyManager.Load();

            if (Helper.HearthstoneDirExists && Config.Instance.StartHearthstoneWithHDT && !Game.IsRunning)
            {
                Helper.StartHearthstoneAsync().Forget();
            }

            Initialized = true;

            Influx.OnAppStart(Helper.GetCurrentVersion(), loginType, newUser);
        }
示例#18
0
        public static void Initialize()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            var newUser = !Directory.Exists(Config.AppDataPath);

            Config.Load();
            Log.Initialize();
            ConfigManager.Run();
            LogConfigUpdater.Run().Forget();
            LogConfigWatcher.Start();
            Helper.UpdateAppTheme();
            ThemeManager.Run();
            var splashScreenWindow = new SplashScreenWindow();

            splashScreenWindow.ShowConditional();
            Game = new GameV2();
            LoginType loginType;
            var       loggedIn = HearthStatsAPI.LoadCredentials();

            if (!loggedIn && Config.Instance.ShowLoginDialog)
            {
                var loginWindow = new LoginWindow();
                splashScreenWindow.Close();
                loginWindow.ShowDialog();
                if (loginWindow.LoginResult == LoginType.None)
                {
                    Application.Current.Shutdown();
                    return;
                }
                loginType          = loginWindow.LoginResult;
                splashScreenWindow = new SplashScreenWindow();
                splashScreenWindow.ShowConditional();
            }
            else
            {
                loginType = loggedIn ? LoginType.AutoLogin : LoginType.AutoGuest;
            }
            MainWindow = new MainWindow();
            MainWindow.LoadConfigSettings();
            if (Config.Instance.ReselectLastDeckUsed)
            {
                MainWindow.SelectLastUsedDeck();
                Config.Instance.ReselectLastDeckUsed = false;
                Config.Save();
            }
            MainWindow.Show();
            splashScreenWindow.Close();

            if (ConfigManager.UpdatedVersion != null)
            {
                Updater.Cleanup();
                MainWindow.FlyoutUpdateNotes.IsOpen = true;
                MainWindow.UpdateNotesControl.SetHighlight(ConfigManager.PreviousVersion);
                MainWindow.UpdateNotesControl.LoadUpdateNotes();
            }
            NetDeck.CheckForChromeExtention();
            DataIssueResolver.Run();

            Helper.CopyReplayFiles();
            BackupManager.Run();

            if (Config.Instance.PlayerWindowOnStart)
            {
                Windows.PlayerWindow.Show();
            }
            if (Config.Instance.OpponentWindowOnStart)
            {
                Windows.OpponentWindow.Show();
            }
            if (Config.Instance.TimerWindowOnStartup)
            {
                Windows.TimerWindow.Show();
            }

            if (Config.Instance.HearthStatsSyncOnStart && HearthStatsAPI.IsLoggedIn)
            {
                HearthStatsManager.SyncAsync(background: true);
            }

            PluginManager.Instance.LoadPlugins();
            MainWindow.Options.OptionsTrackerPlugins.Load();
            PluginManager.Instance.StartUpdateAsync();

            UpdateOverlayAsync();

            if (Config.Instance.ShowCapturableOverlay)
            {
                Windows.CapturableOverlay = new CapturableOverlayWindow();
                Windows.CapturableOverlay.Show();
            }

            if (LogConfigUpdater.LogConfigUpdateFailed)
            {
                MainWindow.ShowLogConfigUpdateFailedMessage().Forget();
            }
            else if (LogConfigUpdater.LogConfigUpdated && Game.IsRunning)
            {
                MainWindow.ShowMessageAsync("Hearthstone restart required", "The log.config file has been updated. HDT may not work properly until Hearthstone has been restarted.");
                Overlay.ShowRestartRequiredWarning();
            }
            LogReaderManager.Start(Game).Forget();

            NewsUpdater.UpdateAsync();
            HotKeyManager.Load();

            if (Helper.HearthstoneDirExists && Config.Instance.StartHearthstoneWithHDT && !Game.IsRunning)
            {
                Helper.StartHearthstoneAsync();
            }

            Initialized = true;

            Analytics.Analytics.TrackPageView($"/app/v{Helper.GetCurrentVersion().ToVersionString()}/{loginType.ToString().ToLower()}{(newUser ? "/new" : "")}", "");
        }
示例#19
0
#pragma warning disable 1998
        public static async void Initialize()
#pragma warning restore 1998
        {
            LocalizeDictionary.Instance.Culture = CultureInfo.GetCultureInfo("en-US");
            _startUpTime = DateTime.UtcNow;
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            Config.Load();
            Log.Info($"HDT: {Helper.GetCurrentVersion()}, Operating System: {Helper.GetWindowsVersion()}, .NET Framework: {Helper.GetInstalledDotNetVersion()}");
            var splashScreenWindow = new SplashScreenWindow();

#if (SQUIRREL)
            if (Config.Instance.CheckForUpdates)
            {
                var updateCheck = Updater.StartupUpdateCheck(splashScreenWindow);
                while (!updateCheck.IsCompleted)
                {
                    await Task.Delay(500);

                    if (splashScreenWindow.SkipUpdate)
                    {
                        break;
                    }
                }
            }
#endif
            splashScreenWindow.ShowConditional();
            Log.Initialize();
            ConfigManager.Run();
            LocUtil.UpdateCultureInfo();
            var newUser = ConfigManager.PreviousVersion == null;
            LogConfigUpdater.Run().Forget();
            LogConfigWatcher.Start();
            UITheme.InitializeTheme();
            ThemeManager.Run();
            ResourceMonitor.Run();
            Game = new GameV2();
            Game.SecretsManager.OnSecretsChanged += cards => Overlay.ShowSecrets(cards);
            MainWindow = new MainWindow();
            MainWindow.LoadConfigSettings();
            MainWindow.Show();
            splashScreenWindow.Close();

            if (Config.Instance.DisplayHsReplayNoteLive && ConfigManager.PreviousVersion != null && ConfigManager.PreviousVersion < new Version(1, 1, 0))
            {
                MainWindow.FlyoutHsReplayNote.IsOpen = true;
            }

            if (ConfigManager.UpdatedVersion != null)
            {
#if (!SQUIRREL)
                Updater.Cleanup();
#endif
                MainWindow.FlyoutUpdateNotes.IsOpen = true;
                MainWindow.UpdateNotesControl.SetHighlight(ConfigManager.PreviousVersion);
#if (SQUIRREL && !DEV)
                if (Config.Instance.CheckForDevUpdates && !Config.Instance.AllowDevUpdates.HasValue)
                {
                    MainWindow.ShowDevUpdatesMessage();
                }
#endif
            }
            NetDeck.CheckForChromeExtention();
            DataIssueResolver.Run();

#if (!SQUIRREL)
            Helper.CopyReplayFiles();
#endif
            BackupManager.Run();

            if (Config.Instance.PlayerWindowOnStart)
            {
                Windows.PlayerWindow.Show();
            }
            if (Config.Instance.OpponentWindowOnStart)
            {
                Windows.OpponentWindow.Show();
            }
            if (Config.Instance.TimerWindowOnStartup)
            {
                Windows.TimerWindow.Show();
            }

            PluginManager.Instance.LoadPluginsFromDefaultPath();
            MainWindow.Options.OptionsTrackerPlugins.Load();
            PluginManager.Instance.StartUpdateAsync();

            UpdateOverlayAsync();

            if (Config.Instance.ShowCapturableOverlay)
            {
                Windows.CapturableOverlay = new CapturableOverlayWindow();
                Windows.CapturableOverlay.Show();
            }

            if (LogConfigUpdater.LogConfigUpdateFailed)
            {
                MainWindow.ShowLogConfigUpdateFailedMessage().Forget();
            }
            else if (LogConfigUpdater.LogConfigUpdated && Game.IsRunning)
            {
                MainWindow.ShowMessageAsync("Hearthstone restart required", "The log.config file has been updated. HDT may not work properly until Hearthstone has been restarted.").Forget();
                Overlay.ShowRestartRequiredWarning();
            }
            LogWatcherManger.Start(Game).Forget();

            NewsManager.LoadNews();
            HotKeyManager.Load();

            if (Helper.HearthstoneDirExists && Config.Instance.StartHearthstoneWithHDT && !Game.IsRunning)
            {
                Helper.StartHearthstoneAsync().Forget();
            }

            ApiWrapper.UpdateAccountStatus().Forget();

            Initialized = true;

            Influx.OnAppStart(
                Helper.GetCurrentVersion(),
                newUser,
                (int)(DateTime.UtcNow - _startUpTime).TotalSeconds,
                PluginManager.Instance.Plugins.Count
                );
        }
示例#20
0
        public static void Initialize()
        {
            Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
            var newUser = !Directory.Exists(Config.AppDataPath);

            Config.Load();
            ConfigManager.Run();
            Logger.Initialize();
            Helper.UpdateAppTheme();
            var splashScreenWindow = new SplashScreenWindow();

            splashScreenWindow.ShowConditional();
            Game = new GameV2();
            LoginType loginType;
            var       loggedIn = HearthStatsAPI.LoadCredentials();

            if (!loggedIn && Config.Instance.ShowLoginDialog)
            {
                var loginWindow = new LoginWindow();
                splashScreenWindow.Close();
                loginWindow.ShowDialog();
                if (loginWindow.LoginResult == LoginType.None)
                {
                    Application.Current.Shutdown();
                    return;
                }
                loginType          = loginWindow.LoginResult;
                splashScreenWindow = new SplashScreenWindow();
                splashScreenWindow.ShowConditional();
            }
            else
            {
                loginType = loggedIn ? LoginType.AutoLogin : LoginType.AutoGuest;
            }
            MainWindow = new MainWindow();
            MainWindow.LoadConfigSettings();
            MainWindow.Show();
            splashScreenWindow.Close();

            if (ConfigManager.UpdatedVersion != null)
            {
                Updater.Cleanup();
                MainWindow.FlyoutUpdateNotes.IsOpen = true;
                MainWindow.UpdateNotesControl.LoadUpdateNotes();
            }
            NetDeck.CheckForChromeExtention();
            DataIssueResolver.Run();

            if (Helper.HearthstoneDirExists)
            {
                if (Helper.UpdateLogConfig && Game.IsRunning)
                {
                    MainWindow.ShowMessageAsync("Restart Hearthstone",
                                                "This is either your first time starting HDT or the log.config file has been updated. Please restart Hearthstone, for HDT to work properly.");
                }
                LogReaderManager.Start(Game);
            }
            else
            {
                MainWindow.ShowHsNotInstalledMessage();
            }

            Helper.CopyReplayFiles();
            BackupManager.Run();

            if (Config.Instance.PlayerWindowOnStart)
            {
                Windows.PlayerWindow.Show();
            }
            if (Config.Instance.OpponentWindowOnStart)
            {
                Windows.OpponentWindow.Show();
            }
            if (Config.Instance.TimerWindowOnStartup)
            {
                Windows.TimerWindow.Show();
            }

            if (Config.Instance.HearthStatsSyncOnStart && HearthStatsAPI.IsLoggedIn)
            {
                HearthStatsManager.SyncAsync(background: true);
            }

            PluginManager.Instance.LoadPlugins();
            MainWindow.Options.OptionsTrackerPlugins.Load();
            PluginManager.Instance.StartUpdateAsync();

            UpdateOverlayAsync();
            NewsUpdater.UpdateAsync();
            HotKeyManager.Load();
            Initialized = true;

            Analytics.Analytics.TrackPageView(
                string.Format("/app/v{0}/{1}{2}", Helper.GetCurrentVersion().ToVersionString(),
                              loginType.ToString().ToLower(), newUser ? "/new" : ""), "");
        }
示例#21
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var args = e.Args;

            ThemeManager.Current.ThemeSyncMode = ThemeSyncMode.SyncAll;
            ThemeManager.Current.SyncTheme();
            // needs to be the first call in the program to prevent weird bugs
            if (Settings.PersistentSettings.debugConsole)
            {
                AllocConsole();
            }

            var uriStart = IPCadapter.getInstance().HandleURIStart(e.Args);

            switch (uriStart)
            {
            case URIStartResult.CLOSE:
                Environment.Exit(0);
                break;

            case URIStartResult.PARSE:
                Console.WriteLine($"Starting with args : {e.Args[0]}");
                break;

            case URIStartResult.CONTINUE:
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var splashScreen = new SplashScreenWindow();

            this.MainWindow = splashScreen;
            splashScreen.Show();
            Task.Factory.StartNew(() =>
            {
                //simulate some work being done
                //System.Threading.Thread.Sleep(3000);

                //since we're not on the UI thread
                //once we're done we need to use the Dispatcher
                //to create and show the main window
                this.Dispatcher.Invoke(() =>
                {
                    //initialize the main window, set it as the application main window
                    //and close the splash screen
                    var mainWindow  = new MainWindow();
                    this.MainWindow = mainWindow;
                    AmongUsCapture.Settings.form         = mainWindow;
                    AmongUsCapture.Settings.conInterface = new FormConsole(mainWindow);
                    Program.Main();
                    mainWindow.Loaded += (sender, args2) =>
                    {
                        if (uriStart == URIStartResult.PARSE)
                        {
                            IPCadapter.getInstance().SendToken(args[0]);
                        }
                    };
                    mainWindow.Closing += (sender, args2) =>
                    {
                        Environment.Exit(0);
                    };
                    mainWindow.Show();
                    splashScreen.Close();
                });
            });
        }
示例#22
0
        private async Task LoadAppAsync(SMAParameters args)
        {
            //
            // Installer events https://github.com/Squirrel/Squirrel.Windows/blob/master/docs/using/custom-squirrel-events.md
            if (SMAInstaller.HandleEvent(args, out var firstRun))
            {
                if (firstRun)
                {
                    MessageBox.Show("SuperMemo Assistant has been successfully installed.", "Installation success");
                }

                Shutdown();
                return;
            }

            //
            // Make sure assemblies are available, and SMA is installed in "%LocalAppData%\SuperMemoAssistant"
            if (AssemblyCheck.CheckRequired(out var errMsg) == false || CheckSMALocation(out errMsg) == false)
            {
                LogTo.Warning(errMsg);
                await errMsg.ErrorMsgBox().ConfigureAwait(false);

                Shutdown(SMAExitCodes.ExitCodeDependencyError);
                return;
            }

            //
            // Load main configuration files
            var(success, nativeDataCfg, coreCfg) = await LoadConfigs().ConfigureAwait(true);

            if (success == false)
            {
                errMsg =
                    $"At least one essential config file could not be loaded: nativeDataCfg ? {nativeDataCfg == null} ; startupCfg ? {coreCfg == null}";
                LogTo.Warning(errMsg);
                await errMsg.ErrorMsgBox().ConfigureAwait(false);

                Shutdown(SMAExitCodes.ExitCodeConfigError);
                return;
            }

            SMA.Core.CoreConfig = coreCfg;

            //
            // Setup Windows Toast notifications
            DesktopNotificationManager.RegisterAumidAndComServer <SMANotificationActivator>(SMANotificationActivator.AppUserModelId);
            DesktopNotificationManager.RegisterActivator <SMANotificationActivator>();

            //
            // Initialize the plugin manager
            await SMAPluginManager.Instance.InitializeAsync().ConfigureAwait(true);

            //
            // Check if SMA is setup, and run the setup wizard if it isn't
            if (SMASetup.Run(nativeDataCfg, coreCfg) == false)
            {
                LogTo.Warning("SMA Setup canceled. Exiting.");

                Shutdown(SMAExitCodes.ExitCodeSMASetupError);
                return;
            }

            //
            // Start plugins
            var pluginStartTask = SMAPluginManager.Instance.StartPlugins().ConfigureAwait(true);

            //
            // (Optional) Start the debugging tool Key logger (logs key strokes with modifiers, e.g. ctrl, alt, ..)
            if (args.KeyLogger)
            {
                SMA.Core.KeyboardHotKey.MainCallback = hk => LogTo.Debug("Key pressed: {Hk}", hk);
            }

            //
            // Show the change logs if necessary
            ChangeLogWindow.ShowIfUpdated(coreCfg);

            //
            // Determine which collection to open
            SMCollection smCollection = null;
            var          selectionWdw = new CollectionSelectionWindow(coreCfg);

            // Try to open command line collection, if one was passed
            if (args.CollectionKnoPath != null && selectionWdw.ValidateSuperMemoPath())
            {
                smCollection = new SMCollection(args.CollectionKnoPath, DateTime.Now);

                if (selectionWdw.ValidateCollection(smCollection) == false)
                {
                    smCollection = null;
                }
            }

            // No valid collection passed, show selection window
            if (smCollection == null)
            {
                selectionWdw.ShowDialog();

                smCollection = selectionWdw.Collection;
            }

            //
            // If a collection was selected, start SMA
            if (smCollection != null)
            {
                _splashScreen = new SplashScreenWindow();
                _splashScreen.Show();

                SMA.Core.SMA.OnSMStartingInternalEvent += OnSMStartingEventAsync;
                SMA.Core.SMA.OnSMStoppedInternalEvent  += OnSMStoppedEvent;

                // Wait for plugins to start
                await pluginStartTask;

                Exception ex;

                if ((ex = await SMA.Core.SMA.StartAsync(nativeDataCfg, smCollection).ConfigureAwait(true)) != null)
                {
                    _splashScreen?.Close();
                    _splashScreen = null;

                    await $"SMA failed to start: {ex.Message}".ErrorMsgBox().ConfigureAwait(false);

                    Shutdown(SMAExitCodes.ExitCodeSMAStartupError);

                    return;
                }

                if (SMAExecutableInfo.Instance.IsDev == false)
                {
                    await SMAInstaller.Instance.Update().ConfigureAwait(false);
                }
            }
            else
            {
                Shutdown();
            }
        }