示例#1
0
        public EditProgWindow(ProgList progList, int id = -1)
        {
            InitializeComponent();
            this.AcceptButton = this.saveButton;
            this.CancelButton = this.cancelButton;
            _progList         = progList;

            if (!JumpListHelper.IsSupported())
            {
                jumpListLabel.Hide();
                jumpListLabelState.Hide();
                jumpListBox.Hide();
            }

            if (id < 0)
            {
                this.Text = Localization.Strings.AddProgram;
                _prog     = _progList.CreateProg();
                _isNew    = true;
            }
            else
            {
                this.Text                = Localization.Strings.EditProgram;
                _prog                    = progList.Get(id);
                _isNew                   = false;
                this.nameField.Text      = _prog.Name;
                this.pathField.Text      = _prog.Path;
                this.argsField.Text      = _prog.Args;
                this.diskImageField.Text = _prog.DiskImage;
                this.iconField.Text      = _prog.Icon;
                this.jumpListBox.Checked = _prog.InJumpList;

                updateIconPreview();
            }
        }
示例#2
0
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (!_alreadyLaunched)
            {
                await InitializeLogger();

                Task.Run(async() => await JumpListHelper.Update(_settingsService.GetShellProfiles()));

                var viewModel = _container.Resolve <MainViewModel>();
                if (args.Arguments.StartsWith(JumpListHelper.ShellProfileFlag))
                {
                    viewModel.AddTerminal(Guid.Parse(args.Arguments.Replace(JumpListHelper.ShellProfileFlag, string.Empty)));
                }
                else
                {
                    viewModel.AddTerminal();
                }
                await CreateMainView(typeof(MainPage), viewModel, true).ConfigureAwait(true);

                Window.Current.Activate();
            }
            else if (_mainViewModels.Count == 0)
            {
                await CreateSecondaryView <MainViewModel>(typeof(MainPage), true).ConfigureAwait(true);
            }
            else if (args.Arguments.StartsWith(JumpListHelper.ShellProfileFlag))
            {
                var location = _applicationSettings.NewTerminalLocation;
                var profile  = _settingsService.GetShellProfile(Guid.Parse(args.Arguments.Replace(JumpListHelper.ShellProfileFlag, string.Empty)));
                await CreateTerminal(profile, location).ConfigureAwait(true);
            }
        }
示例#3
0
 private void OnSettingsClosed(object sender, EventArgs e)
 {
     Task.Run(async() => await JumpListHelper.Update(_settingsService.GetShellProfiles()));
     _settingsViewModel.Closed -= OnSettingsClosed;
     _settingsViewModel         = null;
     _settingsWindowId          = null;
 }
示例#4
0
        private void addProg()
        {
            EditProgWindow editProg = new EditProgWindow(progList);

            editProg.ShowDialog(this);
            JumpListHelper.Update();
            refreshWindow();
        }
示例#5
0
 private void OnSettingsClosed(object sender, EventArgs e)
 {
     // ReSharper disable once AssignmentIsFullyDiscarded
     _ = JumpListHelper.UpdateAsync(_settingsService);
     _settingsViewModel.Closed -= OnSettingsClosed;
     _settingsViewModel         = null;
     _settingsWindowId          = null;
 }
示例#6
0
 private void editSelectedProg()
 {
     if (this.progsListView.SelectedItems.Count == 1)
     {
         EditProgWindow editGame = new EditProgWindow(progList, Int32.Parse(progsListView.SelectedItems[0].Name));
         editGame.ShowDialog(this);
     }
     JumpListHelper.Update();
     refreshWindow();
 }
示例#7
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                ApplicationView.GetForCurrentView().SetPreferredMinSize(LocalConfiguration.WindowMinSize);

                SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;

                // Update app constants from server
                AppConstants.Update();

                // Update assets from server
                AssetManager.UpdateAssets();

                // Play silent sound to avoid suspending the app when it's minimized.
                silentMediaPlayer.Play();

                // Media controls are necessary for the audio to continue when app is minimized.
                MediaControlsHelper.Init(Dispatcher);
                MediaControlsHelper.TrackChanged += (ss, trackChangedArgs) =>
                {
                    if (nowPlaying.IsOpen)
                    {
                        nowPlaying.PlayChangeTrackAnimation(
                            reverse: (trackChangedArgs.Direction == TrackChangeDirection.Backward));
                    }
                };

                // Show what's new if necessary
                if (WhatsNewHelper.ShouldShowWhatsNew())
                {
                    shouldShowWhatsNew = true;
                }

                LyricsViewerIntegrationHelper.InitIntegration();
                LiveTileHelper.InitLiveTileUpdates();
                JumpListHelper.DeleteRecentJumplistEntries();

                AnalyticsHelper.PageView("MainPage", setNewSession: true);
                AnalyticsHelper.Log("mainEvent", "appOpened", SystemInformation.OperatingSystemVersion.ToString());

                developerMessage = await DeveloperMessageHelper.GetNextDeveloperMessage();

                // Window.Current.CoreWindow.KeyDown does not capture Alt events, but AcceleratorKeyActivated does.
                // NOTE: This event captures all key events, even when WebView is focused.
                CoreWindow.GetForCurrentThread().Dispatcher.AcceleratorKeyActivated += Dispatcher_AcceleratorKeyActivated;
            }
            catch (Exception ex)
            {
                AnalyticsHelper.Log("mainPageLoadedException", ex.Message, ex.ToString());
                await new MessageDialog(ex.ToString(), "MainPage:Loaded unhandled exception").ShowAsync();
            }
        }
示例#8
0
#pragma warning disable 1998

        protected async override void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            if (e.PrelaunchActivated)
            {
                return;
            }
            var task = JumpListHelper.SetupJumpList();
            CreateFrameAndNavigate(e.Arguments);
        }
示例#9
0
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (!_alreadyLaunched)
            {
                var logDirectory = await ApplicationData.Current.LocalCacheFolder.CreateFolderAsync("Logs", CreationCollisionOption.OpenIfExists);

                var logFile    = Path.Combine(logDirectory.Path, "fluentterminal.app.log");
                var configFile = await logDirectory.CreateFileAsync("config.json", CreationCollisionOption.OpenIfExists);

                var configContent = await FileIO.ReadTextAsync(configFile);

                Task.Run(async() => await JumpListHelper.Update(_settingsService.GetShellProfiles()));

                if (string.IsNullOrWhiteSpace(configContent))
                {
                    configContent = JsonConvert.SerializeObject(new Logger.Configuration());
                    await FileIO.WriteTextAsync(configFile, configContent);
                }

                var config = JsonConvert.DeserializeObject <Logger.Configuration>(configContent) ?? new Logger.Configuration();

                Logger.Instance.Initialize(logFile, config);

                var viewModel = _container.Resolve <MainViewModel>();
                if (args.Arguments.StartsWith(JumpListHelper.ShellProfileFlag))
                {
                    viewModel.AddTerminal(Guid.Parse(args.Arguments.Replace(JumpListHelper.ShellProfileFlag, "")));
                }
                else
                {
                    viewModel.AddTerminal();
                }
                await CreateMainView(typeof(MainPage), viewModel, true).ConfigureAwait(true);

                Window.Current.Activate();
            }
            else if (_mainViewModels.Count == 0)
            {
                await CreateSecondaryView <MainViewModel>(typeof(MainPage), true).ConfigureAwait(true);
            }
            else if (args.Arguments.StartsWith(JumpListHelper.ShellProfileFlag))
            {
                var location = _applicationSettings.NewTerminalLocation;
                var profile  = _settingsService.GetShellProfile(Guid.Parse(args.Arguments.Replace(JumpListHelper.ShellProfileFlag, "")));
                await CreateTerminal(profile, location).ConfigureAwait(true);
            }
        }
示例#10
0
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (_isLaunching)
            {
                return;
            }

            _isLaunching = true;

            if (!_alreadyLaunched)
            {
                await InitializeLoggerAsync();

                // ReSharper disable once AssignmentIsFullyDiscarded
                _ = JumpListHelper.UpdateAsync(_settingsService);

                var viewModel = _container.Resolve <MainViewModel>();
                if (args.Arguments.StartsWith(JumpListHelper.ShellProfileFlag))
                {
                    await viewModel.AddProfileByGuidAsync(Guid.Parse(args.Arguments.Replace(JumpListHelper.ShellProfileFlag, string.Empty)));
                }
                else
                {
                    await viewModel.AddDefaultProfileAsync(NewTerminalLocation.Tab);
                }
                await CreateMainViewAsync(typeof(MainPage), viewModel, true);

                Window.Current.Activate();
            }
            else if (args.Arguments.StartsWith(JumpListHelper.ShellProfileFlag))
            {
                var location = _applicationSettings.NewTerminalLocation;
                var profile  = _settingsService.GetShellProfile(Guid.Parse(args.Arguments.Replace(JumpListHelper.ShellProfileFlag, string.Empty)));
                await CreateTerminalAsync(profile, location, args.ViewSwitcher);
            }
            else
            {
                var viewModel = await CreateNewTerminalWindowAsync();

                await viewModel.AddDefaultProfileAsync(NewTerminalLocation.Tab);
                await ShowAsStandaloneAsync(viewModel, args.ViewSwitcher);
            }

            _isLaunching = false;
        }
示例#11
0
#pragma warning disable 1998

        protected async override void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                this.DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            if (e.PrelaunchActivated)
            {
                return;
            }

            CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

            var task = JumpListHelper.SetupJumpList();
            CreateFrameAndNavigate(e.Arguments);
        }
示例#12
0
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            if (_isLaunching)
            {
                return;
            }

            _isLaunching = true;
            if (!_alreadyLaunched)
            {
                await InitializeLogger();

                // TODO: Check the reason for such strange using of tasks!
                Task.Run(async() => await JumpListHelper.Update(_settingsService.GetShellProfiles()));

                var viewModel = _container.Resolve <MainViewModel>();
                if (args.Arguments.StartsWith(JumpListHelper.ShellProfileFlag))
                {
                    await viewModel.AddLocalTabOrWindowAsync(Guid.Parse(args.Arguments.Replace(JumpListHelper.ShellProfileFlag, string.Empty)));
                }
                else
                {
                    await viewModel.AddLocalTabAsync();
                }
                await CreateMainView(typeof(MainPage), viewModel, true).ConfigureAwait(true);

                Window.Current.Activate();
            }
            else if (args.Arguments.StartsWith(JumpListHelper.ShellProfileFlag))
            {
                var location = _applicationSettings.NewTerminalLocation;
                var profile  = _settingsService.GetShellProfile(Guid.Parse(args.Arguments.Replace(JumpListHelper.ShellProfileFlag, string.Empty)));
                await CreateTerminal(profile, location, args.ViewSwitcher).ConfigureAwait(true);
            }
            else
            {
                var viewModel = await CreateNewTerminalWindow().ConfigureAwait(true);

                await viewModel.AddLocalTabAsync();
                await ShowAsStandaloneAsync(viewModel, args.ViewSwitcher);
            }

            _isLaunching = false;
        }
示例#13
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            ApplicationView.GetForCurrentView().SetPreferredMinSize(LocalConfiguration.WindowMinSize);

            SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;

            // Update app constants from server
            AppConstants.Update();

            // Update assets from server
            AssetManager.UpdateAssets();

            // Play silent sound to avoid suspending the app when it's minimized.
            silentMediaPlayer.Play();

            // Media controls are necessary for the audio to continue when app is minimized.
            MediaControlsHelper.Init(Dispatcher);
            MediaControlsHelper.TrackChanged += (ss, trackChangedArgs) =>
            {
                if (nowPlaying.IsOpen)
                {
                    nowPlaying.PlayChangeTrackAnimation(
                        reverse: (trackChangedArgs.Direction == TrackChangeDirection.Backward));
                }
            };

            // Show what's new if necessary
            if (WhatsNewHelper.ShouldShowWhatsNew())
            {
                shouldShowWhatsNew = true;
            }

            AnalyticsHelper.PageView("MainPage");
            AnalyticsHelper.Log("mainEvent", "appOpened", SystemInformation.OperatingSystemVersion.ToString());

            developerMessage = await DeveloperMessageHelper.GetNextDeveloperMessage();

            LyricsViewerIntegrationHelper.InitIntegration();
            LiveTileHelper.InitLiveTileUpdates();
            JumpListHelper.DeleteRecentJumplistEntries();
        }
示例#14
0
#pragma warning disable 1998

        protected async override void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            if (System.Diagnostics.Debugger.IsAttached)
            {
                DebugSettings.EnableFrameRateCounter = true;
            }
#endif
            if (e.PrelaunchActivated)
            {
                return;
            }

            CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

            var task = JumpListHelper.SetupJumpList();
            CreateFrameAndNavigate(e.Arguments);

            _uiSettings = new UISettings();
            _uiSettings.ColorValuesChanged += Settings_ColorValuesChanged;
            UpdateThemeAndNotify();
            TitleBarHelper.SetupTitleBarColor(IsLight ?? false);
        }
示例#15
0
 private void deleteSelectedProg()
 {
     if (this.progsListView.SelectedItems.Count == 1)
     {
         Prog prog = progList.Get(Int32.Parse(progsListView.SelectedItems[0].Name));
         if (prog == null)
         {
             LogHelper.RaiseError(this, Localization.Strings.ProgNotFound);
         }
         else if (MessageBox.Show(this, String.Format(Localization.Strings.ProgAskDelete, prog.Name), Localization.Strings.ProgDelete, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
         {
             if (progList.Del(prog))
             {
                 LogHelper.RaiseSuccess(this, String.Format(Localization.Strings.ProgDeleted, prog.Name));
             }
             else
             {
                 LogHelper.RaiseError(this, String.Format(Localization.Strings.ProgNotDeleted, prog.Name));
             }
         }
     }
     JumpListHelper.Update();
     refreshWindow();
 }
示例#16
0
 void MainWindow_Shown(object sender, EventArgs e)
 {
     JumpListHelper.Update();
 }
示例#17
0
        public ConnectionInfoManagementViewModel()
        {
            AddNewItemCommand = IsItemEditing.Inverse().ToReactiveCommand();
            AddNewItemCommand.Subscribe(() =>
            {
                SelectedItem.Value = null;
                EditingItem.Value  = new T();
                if (IsGroupSelected?.Value == true)
                {
                    EditingItem.Value.GroupName = SelectedGroup.Value?.Name;
                }
                IsItemEditing.Value = true;
            }).AddTo(Disposable);

            ConnectCommand.Subscribe(async item => await ConfirmConnect(item)).AddTo(Disposable);

            IsItemSelected = SelectedItem.Select(x => x != null).ToReadOnlyReactiveProperty();

            IsNotItemEditing = IsItemEditing.Inverse().ToReadOnlyReactiveProperty();

            SelectedItem.Subscribe(x =>
            {
                EditingItem.Value   = SelectedItem.Value;
                IsItemEditing.Value = false;
            }).AddTo(Disposable);

            StartEditCommand = IsItemSelected
                               .CombineLatest(IsItemEditing.Inverse(), (a, b) => a && b)
                               .ToReactiveCommand();
            StartEditCommand.Subscribe(() =>
            {
                EditingItem.Value   = SelectedItem.Value.CloneDeep();
                IsItemEditing.Value = true;
            }).AddTo(Disposable);

            ReplicateCommand = IsItemSelected
                               .CombineLatest(IsItemEditing.Inverse(), (a, b) => a && b)
                               .ToReactiveCommand();
            ReplicateCommand.Subscribe(() =>
            {
                var replicated      = SelectedItem.Value.CloneDeep();
                replicated.Id       = -1;
                SelectedItem.Value  = null;
                EditingItem.Value   = replicated;
                IsItemEditing.Value = true;
            }).AddTo(Disposable);

            RemoveCommand = IsItemSelected
                            .CombineLatest(IsItemEditing.Inverse(), (a, b) => a && b)
                            .ToAsyncReactiveCommand();
            RemoveCommand.Subscribe(async() =>
            {
                if (await Remove(SelectedItem.Value))
                {
                    Items.Remove(SelectedItem.Value);
                    // Renew Windows JumpList
                    JumpListHelper.RenewJumpList(await MainWindow.DbContext.EnumerateAllConnectionInfos());
                }
            }).AddTo(Disposable);

            DiscardChangesCommand = IsItemEditing.ToReactiveCommand();
            DiscardChangesCommand.Subscribe(() =>
            {
                EditingItem.Value   = SelectedItem.Value ?? new T();
                IsItemEditing.Value = false;
            }).AddTo(Disposable);

            SaveChangesCommand = IsItemEditing.ToReactiveCommand();
            SaveChangesCommand.Subscribe(async() =>
            {
                var selectedItem = SelectedItem.Value;
                var item         = EditingItem.Value;
                try
                {
                    var(result, resultItem) = await Save(item);
                    if (resultItem == null)
                    {
                        return;        // FAILED
                    }
                    item = resultItem; // Replace with the saved item
                    if (result)        // ADDED
                    {
                        Items.Add(item);
                    }
                    else // UPDATED
                    {
                        var oldItem = Items.FirstOrDefault(x => x.Id == item.Id);
                        if (oldItem != null)
                        {
                            var index = Items.IndexOf(oldItem);
                            if (index >= 0)
                            {
                                Items.RemoveAt(index);
                                Items.Insert(index, item);
                            }
                        }
                    }
                    // Renew Windows JumpList
                    JumpListHelper.RenewJumpList(await MainWindow.DbContext.EnumerateAllConnectionInfos());
                }
                catch (OperationCanceledException) // User manually canceled
                {
                    return;
                }
                SelectedItem.Value  = item;
                IsItemEditing.Value = false;
            }).AddTo(Disposable);

            // Connection info filterings
            FilterText
            .Throttle(TimeSpan.FromMilliseconds(500))
            .ObserveOnDispatcher()
            .Subscribe(_ => RefreshCollectionView())
            .AddTo(Disposable);
            SelectedGroup
            .ObserveOnDispatcher()
            .Subscribe(_ => RefreshCollectionView())
            .AddTo(Disposable);

            // If any group is selected or not (except for "All")
            IsGroupSelected = SelectedGroup
                              .Select(x => x?.Name != AllGroupName)
                              .ToReadOnlyReactivePropertySlim()
                              .AddTo(Disposable);

            // Group list extraction on connection info events
            Observable.CombineLatest(
                // When Add, Remove or Update
                Items.CollectionChangedAsObservable()
                .Select(_ => Unit.Default)
                .StartWith(Unit.Default),
                // When GroupName property in each element changed
                Items.ObserveElementPropertyChanged()
                .Where(x => x.EventArgs.PropertyName == nameof(ConnectionInfoBase.GroupName))
                .Select(_ => Unit.Default)
                .StartWith(Unit.Default)
                )
            .Throttle(TimeSpan.FromMilliseconds(500))     // Once 500 ms
            .ObserveOnDispatcher()
            .Subscribe(_ =>
            {
                var selectedGroup = SelectedGroup.Value;
                // Reload group list
                Groups.Clear();
                EnumerateGroups().ToList().ForEach(Groups.Add);
                // Reset selected group
                SelectedGroup.Value = (selectedGroup is null) ? Groups.FirstOrDefault() : selectedGroup;
            })
            .AddTo(Disposable);
        }
示例#18
0
        public async Task OnLaunchOrActivate(IActivatedEventArgs args)
        {
            if (args is LaunchActivatedEventArgs launchActivated)
            {
                if (_isLaunching)
                {
                    return;
                }

                _isLaunching = true;

                if (!_alreadyLaunched)
                {
                    await InitializeLoggerAsync();

                    // ReSharper disable once AssignmentIsFullyDiscarded
                    _ = JumpListHelper.UpdateAsync(_settingsService);

                    var viewModel = _container.Resolve <MainViewModel>();
                    if (launchActivated.Arguments.StartsWith(JumpListHelper.ShellProfileFlag))
                    {
                        await viewModel.AddProfileByGuidAsync(Guid.Parse(launchActivated.Arguments.Replace(JumpListHelper.ShellProfileFlag, string.Empty)));
                    }
                    else
                    {
                        await viewModel.AddDefaultProfileAsync(NewTerminalLocation.Tab);
                    }
                    await CreateMainViewAsync(typeof(MainPage), viewModel, true);

                    Window.Current.Activate();
                }
                else if (launchActivated.Arguments.StartsWith(JumpListHelper.ShellProfileFlag))
                {
                    var location = _applicationSettings.NewTerminalLocation;
                    var profile  = _settingsService.GetShellProfile(Guid.Parse(launchActivated.Arguments.Replace(JumpListHelper.ShellProfileFlag, string.Empty)));
                    await CreateTerminalAsync(profile, location, launchActivated.ViewSwitcher);
                }
                else
                {
                    var viewModel = await CreateNewTerminalWindowAsync();

                    await viewModel.AddDefaultProfileAsync(NewTerminalLocation.Tab);
                    await ShowAsStandaloneAsync(viewModel, launchActivated.ViewSwitcher);
                }

                _isLaunching = false;
            }
            else if (args is ProtocolActivatedEventArgs protocolActivated)
            {
                if (protocolActivated.Uri == new Uri("ftcmd://fluent.terminal?focus"))
                {
                    await ShowOrCreateWindowAsync(protocolActivated.ViewSwitcher);

                    return;
                }

                MainViewModel mainViewModel = null;
                // IApplicationView to use for creating view models
                IApplicationView applicationView;

                if (_alreadyLaunched)
                {
                    applicationView =
                        (_mainViewModels.FirstOrDefault(o => o.ApplicationView.Id == _activeWindowId) ??
                         _mainViewModels.Last()).ApplicationView;
                }
                else
                {
                    // App wasn't launched before double clicking a shortcut, so we have to create a window
                    // in order to be able to communicate with user.
                    mainViewModel = _container.Resolve <MainViewModel>();

                    await CreateMainViewAsync(typeof(MainPage), mainViewModel, true);

                    applicationView = mainViewModel.ApplicationView;
                }

                bool isSsh;

                try
                {
                    isSsh = SshConnectViewModel.CheckScheme(protocolActivated.Uri);
                }
                catch (Exception ex)
                {
                    await new MessageDialog(
                        $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {ex.Message}",
                        "Invalid Link")
                    .ShowAsync();

                    mainViewModel?.ApplicationView.TryCloseAsync();

                    return;
                }

                if (isSsh)
                {
                    SshConnectViewModel vm;

                    try
                    {
                        vm = SshConnectViewModel.ParseUri(protocolActivated.Uri, _settingsService, applicationView,
                                                          _trayProcessCommunicationService, _container.Resolve <IFileSystemService>(),
                                                          _container.Resolve <ApplicationDataContainers>().HistoryContainer);
                    }
                    catch (Exception ex)
                    {
                        await new MessageDialog(
                            $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {ex.Message}",
                            "Invalid Link")
                        .ShowAsync();

                        mainViewModel?.ApplicationView.TryCloseAsync();

                        return;
                    }

                    if (_applicationSettings.AutoFallbackToWindowsUsernameInLinks && string.IsNullOrEmpty(vm.Username))
                    {
                        vm.Username = await _trayProcessCommunicationService.GetUserNameAsync();
                    }

                    var error = await vm.AcceptChangesAsync(true);

                    var profile = (SshProfile)vm.Model;

                    if (!string.IsNullOrEmpty(error))
                    {
                        // Link is valid, but incomplete (i.e. username missing), so we need to show dialog.
                        profile = await _dialogService.ShowSshConnectionInfoDialogAsync(profile);

                        if (profile == null)
                        {
                            // User clicked "Cancel" in the dialog.
                            mainViewModel?.ApplicationView.TryCloseAsync();

                            return;
                        }
                    }

                    if (mainViewModel == null)
                    {
                        await CreateTerminalAsync(profile, _applicationSettings.NewTerminalLocation, protocolActivated.ViewSwitcher);
                    }
                    else
                    {
                        await mainViewModel.AddTabAsync(profile);
                    }

                    return;
                }

                if (CommandProfileProviderViewModel.CheckScheme(protocolActivated.Uri))
                {
                    CommandProfileProviderViewModel vm;

                    try
                    {
                        vm = CommandProfileProviderViewModel.ParseUri(protocolActivated.Uri, _settingsService,
                                                                      applicationView, _trayProcessCommunicationService,
                                                                      _container.Resolve <ICommandHistoryService>());
                    }
                    catch (Exception ex)
                    {
                        await new MessageDialog(
                            $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {ex.Message}",
                            "Invalid Link")
                        .ShowAsync();

                        mainViewModel?.ApplicationView.TryCloseAsync();

                        return;
                    }

                    var error = await vm.AcceptChangesAsync(true);

                    var profile = vm.Model;

                    if (!string.IsNullOrEmpty(error))
                    {
                        // Link is valid, but incomplete, so we need to show dialog.
                        profile = await _dialogService.ShowCustomCommandDialogAsync(profile);

                        if (profile == null)
                        {
                            // User clicked "Cancel" in the dialog.
                            mainViewModel?.ApplicationView.TryCloseAsync();

                            return;
                        }
                    }

                    if (mainViewModel == null)
                    {
                        await CreateTerminalAsync(profile, _applicationSettings.NewTerminalLocation, protocolActivated.ViewSwitcher);
                    }
                    else
                    {
                        await mainViewModel.AddTabAsync(profile);
                    }
                    return;
                }

                await new MessageDialog(
                    $"{I18N.TranslateWithFallback("InvalidLink", "Invalid link.")} {protocolActivated.Uri}",
                    "Invalid Link")
                .ShowAsync();

                // ReSharper disable once AssignmentIsFullyDiscarded
                _ = mainViewModel?.ApplicationView.TryCloseAsync();

                return;
            }
            else if (args is CommandLineActivatedEventArgs commandLineActivated)
            {
                var arguments = commandLineActivated.Operation.Arguments;
                if (string.IsNullOrWhiteSpace(arguments))
                {
                    arguments = "new";
                }

                _commandLineParser
                .ParseArguments(SplitArguments(arguments), typeof(NewVerb), typeof(RunVerb), typeof(SettingsVerb))
                .WithParsed(async verb => await ParseCommandLineArgumentsAsync(verb, commandLineActivated));
            }
        }
示例#19
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            InitTitleBar();
            ApplicationView.GetForCurrentView().SetPreferredMinSize(LocalConfiguration.WindowMinSize);
            Window.Current.CoreWindow.Activated += Window_Activated;

            SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;

            // Update app constants from server
            AppConstants.Update();

            // Update assets from server
            AssetManager.UpdateAssets();

            // Play silent sound to avoid suspending the app when it's minimized.
            silentMediaPlayer.Play();

            // Media controls are necessary for the audio to continue when app is minimized.
            var mediaControls = SystemMediaTransportControls.GetForCurrentView();

            mediaControls.IsEnabled         = true;
            mediaControls.IsPreviousEnabled = true;
            mediaControls.IsNextEnabled     = true;
            mediaControls.IsPlayEnabled     = true;
            mediaControls.IsPauseEnabled    = true;
            mediaControls.PlaybackStatus    = MediaPlaybackStatus.Paused;
            mediaControls.ButtonPressed    += SystemControls_ButtonPressed;
            await mediaControls.DisplayUpdater.CopyFromFileAsync(MediaPlaybackType.Music,
                                                                 await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Media/silent.wav")));

            PlayStatusTracker.MediaControls = mediaControls;
            PlayStatusTracker.StartRegularRefresh();

            // Show what's new if necessary
            if (WhatsNewHelper.ShouldShowWhatsNew())
            {
                shouldShowWhatsNew = true;
            }

            webViewCheckTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1),
            };
            webViewCheckTimer.Tick += WebViewCheckTimer_Tick;
            webViewCheckTimer.Start();

            clipboardCheckTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(3),
            };
            clipboardCheckTimer.Tick += ClipboardCheckTimer_Tick;
            clipboardCheckTimer.Start();

            stuckDetectTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(4),
            };
            stuckDetectTimer.Tick += StuckDetectTimer_Tick;
            stuckDetectTimer.Start();

            AnalyticsHelper.PageView("MainPage");
            AnalyticsHelper.Log("mainEvent", "appOpened", SystemInformation.OperatingSystemVersion.ToString());

            if (ThemeHelper.GetCurrentTheme() == Theme.Light)
            {
                splashScreenToLightStoryboard.Begin();
            }

            developerMessage = await DeveloperMessageHelper.GetNextDeveloperMessage();

            LyricsViewerIntegrationHelper.InitIntegration();
            LiveTileHelper.InitLiveTileUpdates();
            JumpListHelper.DeleteRecentJumplistEntries();
        }
示例#20
0
        /// <summary>
        /// 清空VS TaskBar上右键中的最近打开
        /// </summary>
        public bool ClearRecentJumpList(bool pinned, out string msg)
        {
            string fileName = GetJumpListFileName();

            return(JumpListHelper.ClearJumpList(fileName, pinned, out msg));
        }
示例#21
0
 public List <JumpListModel> GetJumListItems()
 {
     return(JumpListHelper.GetJumpListItems(GetJumpListFileName()));
 }
示例#22
0
        public MainPageViewModel()
        {
            Current = this;
            player  = PlaybackEngine.PlaybackEngine.Current;
            if (Settings.Current.LastUpdateBuild < SystemInfoHelper.GetPackageVersionNum())
            {
                if (Consts.UpdateNote == null)
                {
                    Settings.Current.LastUpdateBuild = SystemInfoHelper.GetPackageVersionNum();
                    Settings.Current.Save();
                }
                else
                {
                    var i = new UpdateInfo();
#pragma warning disable CS4014 // 由于此调用不会等待,因此在调用完成前将继续执行当前方法
                    i.ShowAsync();
#pragma warning restore CS4014 // 由于此调用不会等待,因此在调用完成前将继续执行当前方法
                    Settings.Current.LastUpdateBuild = SystemInfoHelper.GetPackageVersionNum();
                    Settings.Current.Save();
                }
            }
            Task.Run(() =>
            {
                AttachVisualizerSource();
            });
            Task.Run(() =>
            {
                player.DownloadProgressChanged       += Player_DownloadProgressChanged;
                player.ItemsChanged                  += Player_StatusChanged;
                player.PlaybackStatusChanged         += Player_PlaybackStatusChanged;
                player.PositionUpdated               += Player_PositionUpdated;
                Downloader.Current.ProgressChanged   += Current_ProgressChanged;
                Downloader.Current.ProgressCancelled += Current_ProgressChanged;
                Downloader.Current.ItemCompleted     += Current_ProgressChanged;
                FileReader.ProgressUpdated           += Reader_ProgressUpdated;
                FileReader.Completed                 += Reader_Completed;
            });
            Task.Run(async() =>
            {
                await ReloadExtensionsAsync();
            });
            Task.Run(async() =>
            {
                await FindFileChangesAsync();
            });
            if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.Shell.AdaptiveCardBuilder"))
            {
                Task.Run(async() =>
                {
                    await CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, async() =>
                    {
                        activity = UserActivityChannel.GetDefault();

                        var id = Guid.NewGuid().ToString();

                        act = await activity.GetOrCreateUserActivityAsync(id);

                        if (act.State == UserActivityState.Published)
                        {
                            await activity.DeleteActivityAsync(id);
                            act = await activity.GetOrCreateUserActivityAsync(id);
                        }
                    });
                });
            }
            if (JumpList.IsSupported())
            {
                Task.Run(async() =>
                {
                    var jumpList = await JumpListHelper.LoadJumpListAsync();
                    await jumpList.SaveAsync();
                });
            }
        }