terminal/src/cascadia/TerminalApp/AppLogic.cpp

1491 lines
58 KiB
C++
Raw Normal View History

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include "pch.h"
#include "AppLogic.h"
#include "../inc/WindowingBehavior.h"
#include "AppLogic.g.cpp"
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
#include "FindTargetWindowResult.g.cpp"
#include <winrt/Microsoft.UI.Xaml.XamlTypeInfo.h>
#include <LibraryResources.h>
Add startup task, setting to launch application on login (#4908) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR adds a new boolean global setting, startOnUserLogin, along with associated AppLogic to request enabling or disabling of the StartupTask. Added UAP5 extensions to AppX manifests. <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References #2189 <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #2189 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [x] Tests added/passed * [x] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #2189 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments Please note, I'm a non-practicing C++ developer, there are a number of things I wasn't sure how to handle in the appropriate fashion, mostly around error handling and what probably looks like an incredibly naive (and messy) way to implement the async co_await behavior. Error handling-wise, I found (don't ask me how!) that if you somehow mismatch the startup task's ID between the manifest and the call to `StartupTask::GetAsync(hstring taskId)`, you'll get a very opaque WinRT exception that boils down to a generic invalid argument message. This isn't likely to happen in the wild, but worth mentioning... I had enough trouble getting myself familiarized with the project, environment, and C++/WinRT in general didn't want to try to tackle adding tests for this quite yet since (as I mentioned) I don't really know what I'm doing. I'm happy to give it a try with perhaps a bit of assistance in getting started 😃 Further work in this area of the application outside of this immediate PR might need to include adding an additional setting to contain launch args that the startup task can pass to the app so that users can specify a non-default profile to launch on start, window position (e.g., #653). <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed ✔️ Default settings: Given the user does not have the `startOnUserLogin` setting in their profile.json, When the default settings are opened (via alt+click on Settings), Then the global settings should contain the `"startOnUserLogin": false` token ✔️ Applying setting on application launch Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `disabled` and the application is not running When the application is launched Then the `Windows Terminal` entry in the user's Startup list should be `enabled` ✔️ Applying setting on settings change Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `enabled` and the application is running When the `startOnUserLogin` setting is changed to `false` and the settings file is saved to disk Then the `Windows Terminal` startup task entry should be `disabled` ✔️ Setting is ignored when user has manually disabled startup Given the `startOnUserLogin` is `true` and the application is not running and the `Windows Terminal` startup task has been set to `disabled` via user action When the application is launched Then the startup task should remain disabled and the application should not throw an exception #### note: Task Manager does not seem to re-scan startup task states after launch; the Settings -> Apps -> Startup page also requires closing or moving away to refresh the status of entries
2020-06-01 22:24:43 +02:00
using namespace winrt::Windows::ApplicationModel;
using namespace winrt::Windows::ApplicationModel::DataTransfer;
using namespace winrt::Windows::UI::Xaml;
using namespace winrt::Windows::UI::Xaml::Controls;
using namespace winrt::Windows::UI::Core;
using namespace winrt::Windows::System;
using namespace winrt::Microsoft::Terminal;
Rename `Microsoft.Terminal.TerminalControl` to `.Control`; Split into dll & lib (#9472) **BE NOT AFRAID**. I know that there's 107 files in this PR, but almost all of it is just find/replacing `TerminalControl` with `Control`. This is the start of the work to move TermControl into multiple pieces, for #5000. The PR starts this work by: * Splits `TerminalControl` into separate lib and dll projects. We'll want control tests in the future, and for that, we'll need a lib. * Moves `ICoreSettings` back into the `Microsoft.Terminal.Core` namespace. We'll have other types in there soon too. * I could not tell you why this works suddenly. New VS versions? New cppwinrt version? Maybe we're just better at dealing with mdmerge bugs these days. * RENAMES `Microsoft.Terminal.TerminalControl` to `Microsoft.Terminal.Control`. This touches pretty much every file in the sln. Sorry about that (not sorry). An upcoming PR will move much of the logic in TermControl into a new `ControlCore` class that we'll add in `Microsoft.Terminal.Core`. `ControlCore` will then be unittest-able in the `UnitTests_TerminalCore`, which will help prevent regressions like #9455 ## Detailed Description of the Pull Request / Additional comments You're really gonna want to clean the sln first, then merge this into your branch, then rebuild. It's very likely that old winmds will get left behind. If you see something like ``` Error MDM2007 Cannot create type Microsoft.Terminal.TerminalControl.KeyModifiers in read-only metadata file Microsoft.Terminal.TerminalControl. ``` then that's what happened to you.
2021-03-17 21:47:24 +01:00
using namespace winrt::Microsoft::Terminal::Control;
Introduce TerminalSettingsModel project (#7667) Introduces a new TerminalSettingsModel (TSM) project. This project is responsible for (de)serializing and exposing Windows Terminal's settings as WinRT objects. ## References #885: TSM epic #1564: Settings UI is dependent on this for data binding and settings access #6904: TSM Spec In the process of ripping out TSM from TerminalApp, a few other changes were made to make this possible: 1. AppLogic's `ApplicationDisplayName` and `ApplicationVersion` was moved to `CascadiaSettings` - These are defined as static functions. They also no longer check if `AppLogic::Current()` is nullptr. 2. `enum LaunchMode` was moved from TerminalApp to TSM 3. `AzureConnectionType` and `TelnetConnectionType` were moved from the profile generators to their respective TerminalConnections 4. CascadiaSettings' `SettingsPath` and `DefaultSettingsPath` are exposed as `hstring` instead of `std::filesystem::path` 5. `Command::ExpandCommands()` was exposed via the IDL - This required some of the warnings to be saved to an `IVector` instead of `std::vector`, among some other small changes. 6. The localization resources had to be split into two halves. - Resource file linked in init.cpp. Verified at runtime thanks to the StaticResourceLoader. 7. Added constructors to some `ActionArgs` 8. Utils.h/cpp were moved to `cascadia/inc`. `JsonKey()` was moved to `JsonUtils`. Both TermApp and TSM need access to Utils.h/cpp. A large amount of work includes moving to the new namespace (`TerminalApp` --> `Microsoft::Terminal::Settings::Model`). Fixing the tests had its own complications. Testing required us to split up TSM into a DLL and LIB, similar to TermApp. Discussion on creating a non-local test variant can be found in #7743. Closes #885
2020-10-06 18:56:59 +02:00
using namespace winrt::Microsoft::Terminal::Settings::Model;
using namespace ::TerminalApp;
namespace winrt
{
namespace MUX = Microsoft::UI::Xaml;
using IInspectable = Windows::Foundation::IInspectable;
}
Add startup task, setting to launch application on login (#4908) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR adds a new boolean global setting, startOnUserLogin, along with associated AppLogic to request enabling or disabling of the StartupTask. Added UAP5 extensions to AppX manifests. <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References #2189 <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #2189 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [x] Tests added/passed * [x] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #2189 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments Please note, I'm a non-practicing C++ developer, there are a number of things I wasn't sure how to handle in the appropriate fashion, mostly around error handling and what probably looks like an incredibly naive (and messy) way to implement the async co_await behavior. Error handling-wise, I found (don't ask me how!) that if you somehow mismatch the startup task's ID between the manifest and the call to `StartupTask::GetAsync(hstring taskId)`, you'll get a very opaque WinRT exception that boils down to a generic invalid argument message. This isn't likely to happen in the wild, but worth mentioning... I had enough trouble getting myself familiarized with the project, environment, and C++/WinRT in general didn't want to try to tackle adding tests for this quite yet since (as I mentioned) I don't really know what I'm doing. I'm happy to give it a try with perhaps a bit of assistance in getting started 😃 Further work in this area of the application outside of this immediate PR might need to include adding an additional setting to contain launch args that the startup task can pass to the app so that users can specify a non-default profile to launch on start, window position (e.g., #653). <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed ✔️ Default settings: Given the user does not have the `startOnUserLogin` setting in their profile.json, When the default settings are opened (via alt+click on Settings), Then the global settings should contain the `"startOnUserLogin": false` token ✔️ Applying setting on application launch Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `disabled` and the application is not running When the application is launched Then the `Windows Terminal` entry in the user's Startup list should be `enabled` ✔️ Applying setting on settings change Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `enabled` and the application is running When the `startOnUserLogin` setting is changed to `false` and the settings file is saved to disk Then the `Windows Terminal` startup task entry should be `disabled` ✔️ Setting is ignored when user has manually disabled startup Given the `startOnUserLogin` is `true` and the application is not running and the `Windows Terminal` startup task has been set to `disabled` via user action When the application is launched Then the startup task should remain disabled and the application should not throw an exception #### note: Task Manager does not seem to re-scan startup task states after launch; the Settings -> Apps -> Startup page also requires closing or moving away to refresh the status of entries
2020-06-01 22:24:43 +02:00
static const winrt::hstring StartupTaskName = L"StartTerminalOnLoginTask";
// clang-format off
// !!! IMPORTANT !!!
// Make sure that these keys are in the same order as the
// SettingsLoadWarnings/Errors enum is!
Introduce TerminalSettingsModel project (#7667) Introduces a new TerminalSettingsModel (TSM) project. This project is responsible for (de)serializing and exposing Windows Terminal's settings as WinRT objects. ## References #885: TSM epic #1564: Settings UI is dependent on this for data binding and settings access #6904: TSM Spec In the process of ripping out TSM from TerminalApp, a few other changes were made to make this possible: 1. AppLogic's `ApplicationDisplayName` and `ApplicationVersion` was moved to `CascadiaSettings` - These are defined as static functions. They also no longer check if `AppLogic::Current()` is nullptr. 2. `enum LaunchMode` was moved from TerminalApp to TSM 3. `AzureConnectionType` and `TelnetConnectionType` were moved from the profile generators to their respective TerminalConnections 4. CascadiaSettings' `SettingsPath` and `DefaultSettingsPath` are exposed as `hstring` instead of `std::filesystem::path` 5. `Command::ExpandCommands()` was exposed via the IDL - This required some of the warnings to be saved to an `IVector` instead of `std::vector`, among some other small changes. 6. The localization resources had to be split into two halves. - Resource file linked in init.cpp. Verified at runtime thanks to the StaticResourceLoader. 7. Added constructors to some `ActionArgs` 8. Utils.h/cpp were moved to `cascadia/inc`. `JsonKey()` was moved to `JsonUtils`. Both TermApp and TSM need access to Utils.h/cpp. A large amount of work includes moving to the new namespace (`TerminalApp` --> `Microsoft::Terminal::Settings::Model`). Fixing the tests had its own complications. Testing required us to split up TSM into a DLL and LIB, similar to TermApp. Discussion on creating a non-local test variant can be found in #7743. Closes #885
2020-10-06 18:56:59 +02:00
static const std::array<std::wstring_view, static_cast<uint32_t>(SettingsLoadWarnings::WARNINGS_SIZE)> settingsLoadWarningsLabels {
USES_RESOURCE(L"MissingDefaultProfileText"),
USES_RESOURCE(L"DuplicateProfileText"),
Fix crash related to unparseable/invalid media resource paths (#4194) WT crashes when an unparseable/invalid `backgroundImage` or `icon` resource path is provided in `profiles.json`. This PR averts the crash by the validating and correcting resource paths as a part of the `_ValidateSettings()` function in `CascadiaSettings`. `_ValidateSettings()` is run on start up and any time `profiles.json` is changed, so a user can not change a file path and avoid the validation step. When a bad `backgroundImage` or `icon` resource path is detected, a warning screen will be presented. References #4002, which identified a consistent repro for the crash. To validate the resource, a `Windows::Foundation::Uri` object is constructed with the path. The ctor will throw if the resource path is invalid. Whether or not this validation method is robust enough is a subject worth review. The correction method for when a bad resource path is detected is to reset the `std::optional<winrt::hstring>` holding the file path. The text in the warning display was cribbed from the text used when an invalid `colorScheme` is used. Whether or not the case of a bad background image file path warrants a warning display is a subject worth review. Ensured the repro steps in #4002 did not trigger a crash. Additionally, some potential backdoor paths to a crash were tested: - Deleting the file of a validated background image file path - Changing the actual file name of a validated background image file path - Replacing the file of a validated background image file path with a non-image file (of the same name) - Using a non-image file as a background image In all the above cases WT does not crash, and instead defaults to the background color specified in the profile's `colorScheme`. This PR does not implement this recovery behavior (existing error catching code does). Closes #2329
2020-01-17 02:48:37 +01:00
USES_RESOURCE(L"UnknownColorSchemeText"),
USES_RESOURCE(L"InvalidBackgroundImage"),
USES_RESOURCE(L"InvalidIcon"),
USES_RESOURCE(L"AtLeastOneKeybindingWarning"),
USES_RESOURCE(L"TooManyKeysForChord"),
USES_RESOURCE(L"MissingRequiredParameter"),
Add support for iterable, nested commands (#6856) ## Summary of the Pull Request This PR adds support for both _nested_ and _iterable_ commands in the Command palette. ![nested-commands-000](https://user-images.githubusercontent.com/18356694/87072916-2d991c00-c1e2-11ea-8917-a70e8b8b9803.gif) * **Nested commands**: These are commands that include additional sub-commands. When the user selects on of these, the palette will update to only show the nested commands. * **Iterable commands**: These are commands what allow the user to define only a single command, which is repeated once for every profile. (in the future, also repeated for color schemes, themes, etc.) The above gif uses the following json: ```json { "name": "Split Pane...", "commands": [ { "iterateOn": "profiles", "name": "Split with ${profile.name}...", "commands": [ { "command": { "action": "splitPane", "profile": "${profile.name}", "split": "automatic" } }, { "command": { "action": "splitPane", "profile": "${profile.name}", "split": "vertical" } }, { "command": { "action": "splitPane", "profile": "${profile.name}", "split": "horizontal" } } ] } ] }, ``` ## References ## PR Checklist * [x] Closes #3994 * [x] I work here * [x] Tests added/passed * [ ] Requires documentation to be updated - Sure does, but we'll finish polishing this first. ## Detailed Description of the Pull Request / Additional comments We've now gotta keep the original json for a command around, so that once we know what all the profiles will be, we can expand the commands that need it. We've also got to parse commands recursively, because they might have any number of child commands. These together made the command parsing a _lot_ more complicated, but it feels good so far. ## Validation Steps Performed * wrote a bunch of tests * Played with it a bunch
2020-08-13 23:22:46 +02:00
USES_RESOURCE(L"LegacyGlobalsProperty"),
USES_RESOURCE(L"FailedToParseCommandJson"),
USES_RESOURCE(L"FailedToWriteToSettings"),
USES_RESOURCE(L"InvalidColorSchemeInCmd"),
USES_RESOURCE(L"InvalidSplitSize"),
USES_RESOURCE(L"FailedToParseStartupActions"),
USES_RESOURCE(L"FailedToParseSubCommands"),
};
Introduce TerminalSettingsModel project (#7667) Introduces a new TerminalSettingsModel (TSM) project. This project is responsible for (de)serializing and exposing Windows Terminal's settings as WinRT objects. ## References #885: TSM epic #1564: Settings UI is dependent on this for data binding and settings access #6904: TSM Spec In the process of ripping out TSM from TerminalApp, a few other changes were made to make this possible: 1. AppLogic's `ApplicationDisplayName` and `ApplicationVersion` was moved to `CascadiaSettings` - These are defined as static functions. They also no longer check if `AppLogic::Current()` is nullptr. 2. `enum LaunchMode` was moved from TerminalApp to TSM 3. `AzureConnectionType` and `TelnetConnectionType` were moved from the profile generators to their respective TerminalConnections 4. CascadiaSettings' `SettingsPath` and `DefaultSettingsPath` are exposed as `hstring` instead of `std::filesystem::path` 5. `Command::ExpandCommands()` was exposed via the IDL - This required some of the warnings to be saved to an `IVector` instead of `std::vector`, among some other small changes. 6. The localization resources had to be split into two halves. - Resource file linked in init.cpp. Verified at runtime thanks to the StaticResourceLoader. 7. Added constructors to some `ActionArgs` 8. Utils.h/cpp were moved to `cascadia/inc`. `JsonKey()` was moved to `JsonUtils`. Both TermApp and TSM need access to Utils.h/cpp. A large amount of work includes moving to the new namespace (`TerminalApp` --> `Microsoft::Terminal::Settings::Model`). Fixing the tests had its own complications. Testing required us to split up TSM into a DLL and LIB, similar to TermApp. Discussion on creating a non-local test variant can be found in #7743. Closes #885
2020-10-06 18:56:59 +02:00
static const std::array<std::wstring_view, static_cast<uint32_t>(SettingsLoadErrors::ERRORS_SIZE)> settingsLoadErrorsLabels {
USES_RESOURCE(L"NoProfilesText"),
USES_RESOURCE(L"AllProfilesHiddenText")
};
// clang-format on
// Function Description:
// - General-purpose helper for looking up a localized string for a
// warning/error. First will look for the given key in the provided map of
// keys->strings, where the values in the map are ResourceKeys. If it finds
// one, it will lookup the localized string from that ResourceKey.
// - If it does not find a key, it'll return an empty string
// Arguments:
// - key: the value to use to look for a resource key in the given map
// - map: A map of keys->Resource keys.
// Return Value:
// - the localized string for the given type, if it exists.
template<std::size_t N>
static winrt::hstring _GetMessageText(uint32_t index, std::array<std::wstring_view, N> keys)
{
if (index < keys.size())
{
return GetLibraryResourceString(keys.at(index));
}
return {};
}
// Function Description:
// - Gets the text from our ResourceDictionary for the given
// SettingsLoadWarning. If there is no such text, we'll return nullptr.
// - The warning should have an entry in settingsLoadWarningsLabels.
// Arguments:
// - warning: the SettingsLoadWarnings value to get the localized text for.
// Return Value:
// - localized text for the given warning
Introduce TerminalSettingsModel project (#7667) Introduces a new TerminalSettingsModel (TSM) project. This project is responsible for (de)serializing and exposing Windows Terminal's settings as WinRT objects. ## References #885: TSM epic #1564: Settings UI is dependent on this for data binding and settings access #6904: TSM Spec In the process of ripping out TSM from TerminalApp, a few other changes were made to make this possible: 1. AppLogic's `ApplicationDisplayName` and `ApplicationVersion` was moved to `CascadiaSettings` - These are defined as static functions. They also no longer check if `AppLogic::Current()` is nullptr. 2. `enum LaunchMode` was moved from TerminalApp to TSM 3. `AzureConnectionType` and `TelnetConnectionType` were moved from the profile generators to their respective TerminalConnections 4. CascadiaSettings' `SettingsPath` and `DefaultSettingsPath` are exposed as `hstring` instead of `std::filesystem::path` 5. `Command::ExpandCommands()` was exposed via the IDL - This required some of the warnings to be saved to an `IVector` instead of `std::vector`, among some other small changes. 6. The localization resources had to be split into two halves. - Resource file linked in init.cpp. Verified at runtime thanks to the StaticResourceLoader. 7. Added constructors to some `ActionArgs` 8. Utils.h/cpp were moved to `cascadia/inc`. `JsonKey()` was moved to `JsonUtils`. Both TermApp and TSM need access to Utils.h/cpp. A large amount of work includes moving to the new namespace (`TerminalApp` --> `Microsoft::Terminal::Settings::Model`). Fixing the tests had its own complications. Testing required us to split up TSM into a DLL and LIB, similar to TermApp. Discussion on creating a non-local test variant can be found in #7743. Closes #885
2020-10-06 18:56:59 +02:00
static winrt::hstring _GetWarningText(SettingsLoadWarnings warning)
{
return _GetMessageText(static_cast<uint32_t>(warning), settingsLoadWarningsLabels);
}
// Function Description:
// - Gets the text from our ResourceDictionary for the given
// SettingsLoadError. If there is no such text, we'll return nullptr.
// - The warning should have an entry in settingsLoadErrorsLabels.
// Arguments:
// - error: the SettingsLoadErrors value to get the localized text for.
// Return Value:
// - localized text for the given error
Introduce TerminalSettingsModel project (#7667) Introduces a new TerminalSettingsModel (TSM) project. This project is responsible for (de)serializing and exposing Windows Terminal's settings as WinRT objects. ## References #885: TSM epic #1564: Settings UI is dependent on this for data binding and settings access #6904: TSM Spec In the process of ripping out TSM from TerminalApp, a few other changes were made to make this possible: 1. AppLogic's `ApplicationDisplayName` and `ApplicationVersion` was moved to `CascadiaSettings` - These are defined as static functions. They also no longer check if `AppLogic::Current()` is nullptr. 2. `enum LaunchMode` was moved from TerminalApp to TSM 3. `AzureConnectionType` and `TelnetConnectionType` were moved from the profile generators to their respective TerminalConnections 4. CascadiaSettings' `SettingsPath` and `DefaultSettingsPath` are exposed as `hstring` instead of `std::filesystem::path` 5. `Command::ExpandCommands()` was exposed via the IDL - This required some of the warnings to be saved to an `IVector` instead of `std::vector`, among some other small changes. 6. The localization resources had to be split into two halves. - Resource file linked in init.cpp. Verified at runtime thanks to the StaticResourceLoader. 7. Added constructors to some `ActionArgs` 8. Utils.h/cpp were moved to `cascadia/inc`. `JsonKey()` was moved to `JsonUtils`. Both TermApp and TSM need access to Utils.h/cpp. A large amount of work includes moving to the new namespace (`TerminalApp` --> `Microsoft::Terminal::Settings::Model`). Fixing the tests had its own complications. Testing required us to split up TSM into a DLL and LIB, similar to TermApp. Discussion on creating a non-local test variant can be found in #7743. Closes #885
2020-10-06 18:56:59 +02:00
static winrt::hstring _GetErrorText(SettingsLoadErrors error)
{
return _GetMessageText(static_cast<uint32_t>(error), settingsLoadErrorsLabels);
}
// Function Description:
// - Creates a Run of text to display an error message. The text is yellow or
// red for dark/light theme, respectively.
// Arguments:
// - text: The text of the error message.
// - resources: The application's resource loader.
// Return Value:
// - The fully styled text run.
static Documents::Run _BuildErrorRun(const winrt::hstring& text, const ResourceDictionary& resources)
{
Documents::Run textRun;
textRun.Text(text);
// Color the text red (light theme) or yellow (dark theme) based on the system theme
winrt::IInspectable key = winrt::box_value(L"ErrorTextBrush");
if (resources.HasKey(key))
{
winrt::IInspectable g = resources.Lookup(key);
auto brush = g.try_as<winrt::Windows::UI::Xaml::Media::Brush>();
textRun.Foreground(brush);
}
return textRun;
}
// Method Description:
// - Returns whether the user is either a member of the Administrators group or
// is currently elevated.
// Return Value:
// - true if the user is an administrator
static bool _isUserAdmin() noexcept
try
{
SID_IDENTIFIER_AUTHORITY ntAuthority{ SECURITY_NT_AUTHORITY };
wil::unique_sid adminGroupSid{};
THROW_IF_WIN32_BOOL_FALSE(AllocateAndInitializeSid(&ntAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &adminGroupSid));
BOOL b;
THROW_IF_WIN32_BOOL_FALSE(CheckTokenMembership(NULL, adminGroupSid.get(), &b));
return !!b;
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
return false;
}
namespace winrt::TerminalApp::implementation
{
// Function Description:
// - Get the AppLogic for the current active Xaml application, or null if there isn't one.
// Return value:
// - A pointer (bare) to the AppLogic, or nullptr. The app logic outlives all other objects,
// unless the application is in a terrible way, so this is "safe."
AppLogic* AppLogic::Current() noexcept
try
{
if (auto currentXamlApp{ winrt::Windows::UI::Xaml::Application::Current().try_as<winrt::TerminalApp::App>() })
{
if (auto appLogicPointer{ winrt::get_self<AppLogic>(currentXamlApp.Logic()) })
{
return appLogicPointer;
}
}
return nullptr;
}
catch (...)
{
LOG_CAUGHT_EXCEPTION();
return nullptr;
}
// Method Description:
// - Returns the settings currently in use by the entire Terminal application.
// - IMPORTANT! This can throw! Make sure to try/catch this, so that the
// LocalTests don't crash (because their Application::Current() won't be a
// AppLogic)
// Throws:
// - HR E_INVALIDARG if the app isn't up and running.
Introduce TerminalSettingsModel project (#7667) Introduces a new TerminalSettingsModel (TSM) project. This project is responsible for (de)serializing and exposing Windows Terminal's settings as WinRT objects. ## References #885: TSM epic #1564: Settings UI is dependent on this for data binding and settings access #6904: TSM Spec In the process of ripping out TSM from TerminalApp, a few other changes were made to make this possible: 1. AppLogic's `ApplicationDisplayName` and `ApplicationVersion` was moved to `CascadiaSettings` - These are defined as static functions. They also no longer check if `AppLogic::Current()` is nullptr. 2. `enum LaunchMode` was moved from TerminalApp to TSM 3. `AzureConnectionType` and `TelnetConnectionType` were moved from the profile generators to their respective TerminalConnections 4. CascadiaSettings' `SettingsPath` and `DefaultSettingsPath` are exposed as `hstring` instead of `std::filesystem::path` 5. `Command::ExpandCommands()` was exposed via the IDL - This required some of the warnings to be saved to an `IVector` instead of `std::vector`, among some other small changes. 6. The localization resources had to be split into two halves. - Resource file linked in init.cpp. Verified at runtime thanks to the StaticResourceLoader. 7. Added constructors to some `ActionArgs` 8. Utils.h/cpp were moved to `cascadia/inc`. `JsonKey()` was moved to `JsonUtils`. Both TermApp and TSM need access to Utils.h/cpp. A large amount of work includes moving to the new namespace (`TerminalApp` --> `Microsoft::Terminal::Settings::Model`). Fixing the tests had its own complications. Testing required us to split up TSM into a DLL and LIB, similar to TermApp. Discussion on creating a non-local test variant can be found in #7743. Closes #885
2020-10-06 18:56:59 +02:00
const CascadiaSettings AppLogic::CurrentAppSettings()
{
auto appLogic{ ::winrt::TerminalApp::implementation::AppLogic::Current() };
THROW_HR_IF_NULL(E_INVALIDARG, appLogic);
return appLogic->GetSettings();
}
AppLogic::AppLogic() :
_dialogLock{},
_loadedInitialSettings{ false },
_settingsLoadedResult{ S_OK }
{
// For your own sanity, it's better to do setup outside the ctor.
// If you do any setup in the ctor that ends up throwing an exception,
// then it might look like App just failed to activate, which will
// cause you to chase down the rabbit hole of "why is App not
// registered?" when it definitely is.
// The TerminalPage has to be constructed during our construction, to
// make sure that there's a terminal page for callers of
// SetTitleBarContent
_isElevated = _isUserAdmin();
_root = winrt::make_self<TerminalPage>();
}
Propagate IslandWindow's HWND into any component that needs it (#8391) This fixes the issue with the settings UI where clicking the browse buttons would cause an exception to be thrown when we tried to display a picker without an originating HWND. It turns out that pickers need a hosting/parent window, and Xaml Islands doesn't furnish us with a CoreWindow that's set up for that use case. Alas! Raymond Chen's [blog post on the matter] suggests that we should hand the HWND off through some classic COM interface. To do that properly, Terminal's various components need to implement that interface and propagate the HWND down where it's needed. Thanks to a [Xaml compiler issue], we can't actually do that. To work around that, we've begged and borrowed different methods for pushing HWNDs around: 1. Using IInitializeWithWindow in secret 2. A member that takes a uint64 3. An interface that offers a function that will "wire up" the HWND. I chose (1) because AppHost can implement IInitializeWithWindow, but TerminalPage cannot. We're just pretending that TerminalPage _can_. I chose (2) because none of the Xaml types in TerminalSettingsEditor can implement the interface thanks to the aforementioned compiler issue, but we don't have an escape hatch like AppHost that lives in the same module and can help us do the propagation. I chose (3) because I didn't want to commit the same sin as (2) _seven times_ for every different type of settings page that exists. (3) is backed by "IHostedInWindow", and anybody who knows they have to use IInitializeWithWindow to tie an HWND to an object can call IHostedInWindow.TryPropagateHostingWindow() on that object. House of cards. [Xaml compiler issue]: https://github.com/microsoft/microsoft-ui-xaml/issues/3331 [blog post on the matter]: https://devblogs.microsoft.com/oldnewthing/20190412-00/?p=102413 (cherry picked from commit f9fc9861a111925347f0362ba0fd9a14fb0765c9)
2020-11-30 20:51:42 +01:00
// Method Description:
// - Implements the IInitializeWithWindow interface from shobjidl_core.
HRESULT AppLogic::Initialize(HWND hwnd)
{
return _root->Initialize(hwnd);
}
// Method Description:
// - Called around the codebase to discover if this is a UWP where we need to turn off specific settings.
// Arguments:
// - <none> - reports internal state
// Return Value:
// - True if UWP, false otherwise.
bool AppLogic::IsUwp() const noexcept
{
return _isUwp;
}
// Method Description:
// - Called around the codebase to discover if Terminal is running elevated
// Arguments:
// - <none> - reports internal state
// Return Value:
// - True if elevated, false otherwise.
bool AppLogic::IsElevated() const noexcept
{
return _isElevated;
}
Introduce a Universal package for Windows Terminal (#3236) This PR creates a Universal entrypoint for the Windows Terminal solution in search of our goals to run everywhere, on all Windows platforms. The Universal entrypoint is relatively straightforward and mostly just invokes the App without any of the other islands and win32 boilerplate required for the centennial route. The Universal project is also its own packaging project all in one and will emit a relevant APPX. A few things were required to make this work correctly: * Vcxitems reuse of resources (and link instructions on all of them for proper pkg layout) * Move all Terminal project CRT usages to the app ones (and ensure forwarders are only Nugetted to the Centennial package to not pollute the Universal one) * Fix/delay dependencies in `TerminalApp` that are not available in the core platform (or don't have an appropriate existing platform forwarder... do a loader snaps check) * vcpkg needs updating for the Azure connection parser * font fallbacks because Consolas isn't necessarily there * fallbacks because there are environments without a window handle Some of those happened in other small PRs in the past week or two. They were relevant to this. Note, this isn't *useful* as such yet. You can run the Terminal in this context and even get some of the shells to work. But they don't do a whole lot yet. Scoping which shells appear in the profiles list and only offering those that contextually make sense is future work. * Break everything out of App except the base initialization for XAML. AppLogic is the new home. * deduplicate logics by always using the app one (since it has to be there to support universal launch). * apparently that was too many cross-boundary calls and we can cache it because winrt objects are magic. * Put UWP project into solution. * tabs in titlebar needs disabling from uwp context as the non-client is way different. This adds a method to signal that to logic and apply the setting override. * Change to use App CRT in preparation for universal. * Try to make project build again by setting winconpty to static lib so it'll use the CRT inside TerminalConnection (or its other consumers) instead of linking its own. * Remove test for conpty dll, it's a lib now. Add additional commentary on how CRT linking works for future reference. I'm sure this will come up again. * This fixes the build error. * use the _apiset variant until proven otherwise to match the existing one. * Merge branch 'master' into dev/miniksa/uwp3 * recorrect spacing in cppwinrt.build.pre.props * Add multiple additional fonts to fallback to. Also, guard for invalid window handle on title update. * Remove ARMs from solution. * Share items resources between centennial and universal project. * cleanup resources and split manifest for dev/release builds. * Rev entire solution to latest Toolkit (6.0.0 stable release). * shorten the items file using include patterns * cleanup this filters file a bit. * Fix C26445 by using string_view as value, not ref. Don't build Universal in Audit because we're not auditing app yet. * some PR feedback. document losing the pointer. get rid of 16.3.9 workarounds. improve consistency of variable decl in applogic.h * Make dev phone product ID not match prod phone ID. Fix universal package identity to match proposed license information.
2019-11-26 01:30:45 +01:00
// Method Description:
// - Called by UWP context invoker to let us know that we may have to change some of our behaviors
// for being a UWP
// Arguments:
// - <none> (sets to UWP = true, one way change)
// Return Value:
// - <none>
Introduce a Universal package for Windows Terminal (#3236) This PR creates a Universal entrypoint for the Windows Terminal solution in search of our goals to run everywhere, on all Windows platforms. The Universal entrypoint is relatively straightforward and mostly just invokes the App without any of the other islands and win32 boilerplate required for the centennial route. The Universal project is also its own packaging project all in one and will emit a relevant APPX. A few things were required to make this work correctly: * Vcxitems reuse of resources (and link instructions on all of them for proper pkg layout) * Move all Terminal project CRT usages to the app ones (and ensure forwarders are only Nugetted to the Centennial package to not pollute the Universal one) * Fix/delay dependencies in `TerminalApp` that are not available in the core platform (or don't have an appropriate existing platform forwarder... do a loader snaps check) * vcpkg needs updating for the Azure connection parser * font fallbacks because Consolas isn't necessarily there * fallbacks because there are environments without a window handle Some of those happened in other small PRs in the past week or two. They were relevant to this. Note, this isn't *useful* as such yet. You can run the Terminal in this context and even get some of the shells to work. But they don't do a whole lot yet. Scoping which shells appear in the profiles list and only offering those that contextually make sense is future work. * Break everything out of App except the base initialization for XAML. AppLogic is the new home. * deduplicate logics by always using the app one (since it has to be there to support universal launch). * apparently that was too many cross-boundary calls and we can cache it because winrt objects are magic. * Put UWP project into solution. * tabs in titlebar needs disabling from uwp context as the non-client is way different. This adds a method to signal that to logic and apply the setting override. * Change to use App CRT in preparation for universal. * Try to make project build again by setting winconpty to static lib so it'll use the CRT inside TerminalConnection (or its other consumers) instead of linking its own. * Remove test for conpty dll, it's a lib now. Add additional commentary on how CRT linking works for future reference. I'm sure this will come up again. * This fixes the build error. * use the _apiset variant until proven otherwise to match the existing one. * Merge branch 'master' into dev/miniksa/uwp3 * recorrect spacing in cppwinrt.build.pre.props * Add multiple additional fonts to fallback to. Also, guard for invalid window handle on title update. * Remove ARMs from solution. * Share items resources between centennial and universal project. * cleanup resources and split manifest for dev/release builds. * Rev entire solution to latest Toolkit (6.0.0 stable release). * shorten the items file using include patterns * cleanup this filters file a bit. * Fix C26445 by using string_view as value, not ref. Don't build Universal in Audit because we're not auditing app yet. * some PR feedback. document losing the pointer. get rid of 16.3.9 workarounds. improve consistency of variable decl in applogic.h * Make dev phone product ID not match prod phone ID. Fix universal package identity to match proposed license information.
2019-11-26 01:30:45 +01:00
void AppLogic::RunAsUwp()
{
_isUwp = true;
}
// Method Description:
// - Build the UI for the terminal app. Before this method is called, it
// should not be assumed that the TerminalApp is usable. The Settings
// should be loaded before this is called, either with LoadSettings or
// GetLaunchDimensions (which will call LoadSettings)
// Arguments:
// - <none>
// Return Value:
// - <none>
void AppLogic::Create()
{
// Assert that we've already loaded our settings. We have to do
// this as a MTA, before the app is Create()'d
WINRT_ASSERT(_loadedInitialSettings);
_root->DialogPresenter(*this);
Introduce a Universal package for Windows Terminal (#3236) This PR creates a Universal entrypoint for the Windows Terminal solution in search of our goals to run everywhere, on all Windows platforms. The Universal entrypoint is relatively straightforward and mostly just invokes the App without any of the other islands and win32 boilerplate required for the centennial route. The Universal project is also its own packaging project all in one and will emit a relevant APPX. A few things were required to make this work correctly: * Vcxitems reuse of resources (and link instructions on all of them for proper pkg layout) * Move all Terminal project CRT usages to the app ones (and ensure forwarders are only Nugetted to the Centennial package to not pollute the Universal one) * Fix/delay dependencies in `TerminalApp` that are not available in the core platform (or don't have an appropriate existing platform forwarder... do a loader snaps check) * vcpkg needs updating for the Azure connection parser * font fallbacks because Consolas isn't necessarily there * fallbacks because there are environments without a window handle Some of those happened in other small PRs in the past week or two. They were relevant to this. Note, this isn't *useful* as such yet. You can run the Terminal in this context and even get some of the shells to work. But they don't do a whole lot yet. Scoping which shells appear in the profiles list and only offering those that contextually make sense is future work. * Break everything out of App except the base initialization for XAML. AppLogic is the new home. * deduplicate logics by always using the app one (since it has to be there to support universal launch). * apparently that was too many cross-boundary calls and we can cache it because winrt objects are magic. * Put UWP project into solution. * tabs in titlebar needs disabling from uwp context as the non-client is way different. This adds a method to signal that to logic and apply the setting override. * Change to use App CRT in preparation for universal. * Try to make project build again by setting winconpty to static lib so it'll use the CRT inside TerminalConnection (or its other consumers) instead of linking its own. * Remove test for conpty dll, it's a lib now. Add additional commentary on how CRT linking works for future reference. I'm sure this will come up again. * This fixes the build error. * use the _apiset variant until proven otherwise to match the existing one. * Merge branch 'master' into dev/miniksa/uwp3 * recorrect spacing in cppwinrt.build.pre.props * Add multiple additional fonts to fallback to. Also, guard for invalid window handle on title update. * Remove ARMs from solution. * Share items resources between centennial and universal project. * cleanup resources and split manifest for dev/release builds. * Rev entire solution to latest Toolkit (6.0.0 stable release). * shorten the items file using include patterns * cleanup this filters file a bit. * Fix C26445 by using string_view as value, not ref. Don't build Universal in Audit because we're not auditing app yet. * some PR feedback. document losing the pointer. get rid of 16.3.9 workarounds. improve consistency of variable decl in applogic.h * Make dev phone product ID not match prod phone ID. Fix universal package identity to match proposed license information.
2019-11-26 01:30:45 +01:00
// In UWP mode, we cannot handle taking over the title bar for tabs,
// so this setting is overridden to false no matter what the preference is.
Introduce a Universal package for Windows Terminal (#3236) This PR creates a Universal entrypoint for the Windows Terminal solution in search of our goals to run everywhere, on all Windows platforms. The Universal entrypoint is relatively straightforward and mostly just invokes the App without any of the other islands and win32 boilerplate required for the centennial route. The Universal project is also its own packaging project all in one and will emit a relevant APPX. A few things were required to make this work correctly: * Vcxitems reuse of resources (and link instructions on all of them for proper pkg layout) * Move all Terminal project CRT usages to the app ones (and ensure forwarders are only Nugetted to the Centennial package to not pollute the Universal one) * Fix/delay dependencies in `TerminalApp` that are not available in the core platform (or don't have an appropriate existing platform forwarder... do a loader snaps check) * vcpkg needs updating for the Azure connection parser * font fallbacks because Consolas isn't necessarily there * fallbacks because there are environments without a window handle Some of those happened in other small PRs in the past week or two. They were relevant to this. Note, this isn't *useful* as such yet. You can run the Terminal in this context and even get some of the shells to work. But they don't do a whole lot yet. Scoping which shells appear in the profiles list and only offering those that contextually make sense is future work. * Break everything out of App except the base initialization for XAML. AppLogic is the new home. * deduplicate logics by always using the app one (since it has to be there to support universal launch). * apparently that was too many cross-boundary calls and we can cache it because winrt objects are magic. * Put UWP project into solution. * tabs in titlebar needs disabling from uwp context as the non-client is way different. This adds a method to signal that to logic and apply the setting override. * Change to use App CRT in preparation for universal. * Try to make project build again by setting winconpty to static lib so it'll use the CRT inside TerminalConnection (or its other consumers) instead of linking its own. * Remove test for conpty dll, it's a lib now. Add additional commentary on how CRT linking works for future reference. I'm sure this will come up again. * This fixes the build error. * use the _apiset variant until proven otherwise to match the existing one. * Merge branch 'master' into dev/miniksa/uwp3 * recorrect spacing in cppwinrt.build.pre.props * Add multiple additional fonts to fallback to. Also, guard for invalid window handle on title update. * Remove ARMs from solution. * Share items resources between centennial and universal project. * cleanup resources and split manifest for dev/release builds. * Rev entire solution to latest Toolkit (6.0.0 stable release). * shorten the items file using include patterns * cleanup this filters file a bit. * Fix C26445 by using string_view as value, not ref. Don't build Universal in Audit because we're not auditing app yet. * some PR feedback. document losing the pointer. get rid of 16.3.9 workarounds. improve consistency of variable decl in applogic.h * Make dev phone product ID not match prod phone ID. Fix universal package identity to match proposed license information.
2019-11-26 01:30:45 +01:00
if (_isUwp)
{
_settings.GlobalSettings().ShowTabsInTitlebar(false);
Introduce a Universal package for Windows Terminal (#3236) This PR creates a Universal entrypoint for the Windows Terminal solution in search of our goals to run everywhere, on all Windows platforms. The Universal entrypoint is relatively straightforward and mostly just invokes the App without any of the other islands and win32 boilerplate required for the centennial route. The Universal project is also its own packaging project all in one and will emit a relevant APPX. A few things were required to make this work correctly: * Vcxitems reuse of resources (and link instructions on all of them for proper pkg layout) * Move all Terminal project CRT usages to the app ones (and ensure forwarders are only Nugetted to the Centennial package to not pollute the Universal one) * Fix/delay dependencies in `TerminalApp` that are not available in the core platform (or don't have an appropriate existing platform forwarder... do a loader snaps check) * vcpkg needs updating for the Azure connection parser * font fallbacks because Consolas isn't necessarily there * fallbacks because there are environments without a window handle Some of those happened in other small PRs in the past week or two. They were relevant to this. Note, this isn't *useful* as such yet. You can run the Terminal in this context and even get some of the shells to work. But they don't do a whole lot yet. Scoping which shells appear in the profiles list and only offering those that contextually make sense is future work. * Break everything out of App except the base initialization for XAML. AppLogic is the new home. * deduplicate logics by always using the app one (since it has to be there to support universal launch). * apparently that was too many cross-boundary calls and we can cache it because winrt objects are magic. * Put UWP project into solution. * tabs in titlebar needs disabling from uwp context as the non-client is way different. This adds a method to signal that to logic and apply the setting override. * Change to use App CRT in preparation for universal. * Try to make project build again by setting winconpty to static lib so it'll use the CRT inside TerminalConnection (or its other consumers) instead of linking its own. * Remove test for conpty dll, it's a lib now. Add additional commentary on how CRT linking works for future reference. I'm sure this will come up again. * This fixes the build error. * use the _apiset variant until proven otherwise to match the existing one. * Merge branch 'master' into dev/miniksa/uwp3 * recorrect spacing in cppwinrt.build.pre.props * Add multiple additional fonts to fallback to. Also, guard for invalid window handle on title update. * Remove ARMs from solution. * Share items resources between centennial and universal project. * cleanup resources and split manifest for dev/release builds. * Rev entire solution to latest Toolkit (6.0.0 stable release). * shorten the items file using include patterns * cleanup this filters file a bit. * Fix C26445 by using string_view as value, not ref. Don't build Universal in Audit because we're not auditing app yet. * some PR feedback. document losing the pointer. get rid of 16.3.9 workarounds. improve consistency of variable decl in applogic.h * Make dev phone product ID not match prod phone ID. Fix universal package identity to match proposed license information.
2019-11-26 01:30:45 +01:00
}
// Pay attention, that even if some command line arguments were parsed (like launch mode),
// we will not use the startup actions from settings.
// While this simplifies the logic, we might want to reconsider this behavior in the future.
if (!_hasCommandLineArguments && _hasSettingsStartupActions)
{
_root->SetStartupActions(_settingsAppArgs.GetStartupActions());
}
_root->SetSettings(_settings, false);
_root->Loaded({ this, &AppLogic::_OnLoaded });
_root->Initialized([this](auto&&, auto&&) {
// GH#288 - When we finish initialization, if the user wanted us
// launched _fullscreen_, toggle fullscreen mode. This will make sure
// that the window size is _first_ set up as something sensible, so
// leaving fullscreen returns to a reasonable size.
Make the window name `_quake` special (#9785) ## Summary of the Pull Request This PR adds some special behavior to the window named "\_quake". * When creating the quake window, it ignores "initialRows" and "initialCols" and opens on the top half of the monitor. - It uses `initialPosition` to determine which monitor this is * It cannot be moved * It can only be vertically resized on the bottom border. * It's always in focus mode. - We should probably have an issue tracking "Allow showing tabs in focus mode"? Maybe? - This one element is maybe the one I'm least attached to When renaming a window to "\_quake", it adopts all those behaviors as well. It does not exit focus mode when leaving QM, nor does it resize back. That seemed unnecessary. ## References * As spec'ed in #9274 * See also #8888 ## PR Checklist * [x] In the pursuit of #653 * [x] I work here * [ ] Tests added/passed * [ ] Requires documentation to be updated, but I'm not gonna do any of that till quake mode is totally done. ## Detailed Description of the Pull Request / Additional comments Note that this doesn't do things like: * dropdown * global hotkey summon * summon to the current monitor * summon to the current desktop I'm doing #653 _very_ piecemeal, to try and make the PRs less egregious. ## Validation Steps Performed * validated that center on launch still works * validated that QM works on different monitors based on `initialPosition` * validated entering/exiting QM behaves as expected ## TODO! * [ ] When snapping the quake window between desktops with <kbd>win+shift+arrow</kbd>, the window doesn't horizontally re-size to the new monitor dimensions. It should.
2021-04-26 21:36:23 +02:00
//
// We know at the start, that the root TerminalPage definitely isn't
// in focus nor fullscreen mode. So "Toggle" here will always work
// to "enable".
const auto launchMode = this->GetLaunchMode();
Make the window name `_quake` special (#9785) ## Summary of the Pull Request This PR adds some special behavior to the window named "\_quake". * When creating the quake window, it ignores "initialRows" and "initialCols" and opens on the top half of the monitor. - It uses `initialPosition` to determine which monitor this is * It cannot be moved * It can only be vertically resized on the bottom border. * It's always in focus mode. - We should probably have an issue tracking "Allow showing tabs in focus mode"? Maybe? - This one element is maybe the one I'm least attached to When renaming a window to "\_quake", it adopts all those behaviors as well. It does not exit focus mode when leaving QM, nor does it resize back. That seemed unnecessary. ## References * As spec'ed in #9274 * See also #8888 ## PR Checklist * [x] In the pursuit of #653 * [x] I work here * [ ] Tests added/passed * [ ] Requires documentation to be updated, but I'm not gonna do any of that till quake mode is totally done. ## Detailed Description of the Pull Request / Additional comments Note that this doesn't do things like: * dropdown * global hotkey summon * summon to the current monitor * summon to the current desktop I'm doing #653 _very_ piecemeal, to try and make the PRs less egregious. ## Validation Steps Performed * validated that center on launch still works * validated that QM works on different monitors based on `initialPosition` * validated entering/exiting QM behaves as expected ## TODO! * [ ] When snapping the quake window between desktops with <kbd>win+shift+arrow</kbd>, the window doesn't horizontally re-size to the new monitor dimensions. It should.
2021-04-26 21:36:23 +02:00
if (IsQuakeWindow())
{
_root->ToggleFocusMode();
}
else if (launchMode == LaunchMode::FullscreenMode)
{
_root->ToggleFullscreen();
}
Make the window name `_quake` special (#9785) ## Summary of the Pull Request This PR adds some special behavior to the window named "\_quake". * When creating the quake window, it ignores "initialRows" and "initialCols" and opens on the top half of the monitor. - It uses `initialPosition` to determine which monitor this is * It cannot be moved * It can only be vertically resized on the bottom border. * It's always in focus mode. - We should probably have an issue tracking "Allow showing tabs in focus mode"? Maybe? - This one element is maybe the one I'm least attached to When renaming a window to "\_quake", it adopts all those behaviors as well. It does not exit focus mode when leaving QM, nor does it resize back. That seemed unnecessary. ## References * As spec'ed in #9274 * See also #8888 ## PR Checklist * [x] In the pursuit of #653 * [x] I work here * [ ] Tests added/passed * [ ] Requires documentation to be updated, but I'm not gonna do any of that till quake mode is totally done. ## Detailed Description of the Pull Request / Additional comments Note that this doesn't do things like: * dropdown * global hotkey summon * summon to the current monitor * summon to the current desktop I'm doing #653 _very_ piecemeal, to try and make the PRs less egregious. ## Validation Steps Performed * validated that center on launch still works * validated that QM works on different monitors based on `initialPosition` * validated entering/exiting QM behaves as expected ## TODO! * [ ] When snapping the quake window between desktops with <kbd>win+shift+arrow</kbd>, the window doesn't horizontally re-size to the new monitor dimensions. It should.
2021-04-26 21:36:23 +02:00
else if (launchMode == LaunchMode::FocusMode ||
launchMode == LaunchMode::MaximizedFocusMode)
{
_root->ToggleFocusMode();
}
});
_root->Create();
_ApplyLanguageSettingChange();
_ApplyTheme(_settings.GlobalSettings().Theme());
Add startup task, setting to launch application on login (#4908) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR adds a new boolean global setting, startOnUserLogin, along with associated AppLogic to request enabling or disabling of the StartupTask. Added UAP5 extensions to AppX manifests. <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References #2189 <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #2189 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [x] Tests added/passed * [x] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #2189 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments Please note, I'm a non-practicing C++ developer, there are a number of things I wasn't sure how to handle in the appropriate fashion, mostly around error handling and what probably looks like an incredibly naive (and messy) way to implement the async co_await behavior. Error handling-wise, I found (don't ask me how!) that if you somehow mismatch the startup task's ID between the manifest and the call to `StartupTask::GetAsync(hstring taskId)`, you'll get a very opaque WinRT exception that boils down to a generic invalid argument message. This isn't likely to happen in the wild, but worth mentioning... I had enough trouble getting myself familiarized with the project, environment, and C++/WinRT in general didn't want to try to tackle adding tests for this quite yet since (as I mentioned) I don't really know what I'm doing. I'm happy to give it a try with perhaps a bit of assistance in getting started 😃 Further work in this area of the application outside of this immediate PR might need to include adding an additional setting to contain launch args that the startup task can pass to the app so that users can specify a non-default profile to launch on start, window position (e.g., #653). <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed ✔️ Default settings: Given the user does not have the `startOnUserLogin` setting in their profile.json, When the default settings are opened (via alt+click on Settings), Then the global settings should contain the `"startOnUserLogin": false` token ✔️ Applying setting on application launch Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `disabled` and the application is not running When the application is launched Then the `Windows Terminal` entry in the user's Startup list should be `enabled` ✔️ Applying setting on settings change Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `enabled` and the application is running When the `startOnUserLogin` setting is changed to `false` and the settings file is saved to disk Then the `Windows Terminal` startup task entry should be `disabled` ✔️ Setting is ignored when user has manually disabled startup Given the `startOnUserLogin` is `true` and the application is not running and the `Windows Terminal` startup task has been set to `disabled` via user action When the application is launched Then the startup task should remain disabled and the application should not throw an exception #### note: Task Manager does not seem to re-scan startup task states after launch; the Settings -> Apps -> Startup page also requires closing or moving away to refresh the status of entries
2020-06-01 22:24:43 +02:00
_ApplyStartupTaskStateChange();
TraceLoggingWrite(
g_hTerminalAppProvider,
"AppCreated",
TraceLoggingDescription("Event emitted when the application is started"),
TraceLoggingBool(_settings.GlobalSettings().ShowTabsInTitlebar(), "TabsInTitlebar"),
TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES),
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance));
}
// Method Description:
// - Show a ContentDialog with buttons to take further action. Uses the
// FrameworkElements provided as the title and content of this dialog, and
// displays buttons (or a single button). Two buttons (primary and secondary)
// will be displayed if this is an warning dialog for closing the terminal,
// this allows the users to abandon the closing action. Otherwise, a single
// close button will be displayed.
// - Only one dialog can be visible at a time. If another dialog is visible
// when this is called, nothing happens.
// Arguments:
// - dialog: the dialog object that is going to show up
// Return value:
// - an IAsyncOperation with the dialog result
winrt::Windows::Foundation::IAsyncOperation<ContentDialogResult> AppLogic::ShowDialog(winrt::Windows::UI::Xaml::Controls::ContentDialog dialog)
{
// DON'T release this lock in a wil::scope_exit. The scope_exit will get
// called when we await, which is not what we want.
std::unique_lock lock{ _dialogLock, std::try_to_lock };
if (!lock)
{
// Another dialog is visible.
co_return ContentDialogResult::None;
}
// IMPORTANT: This is necessary as documented in the ContentDialog MSDN docs.
// Since we're hosting the dialog in a Xaml island, we need to connect it to the
// xaml tree somehow.
dialog.XamlRoot(_root->XamlRoot());
// IMPORTANT: Set the requested theme of the dialog, because the
// PopupRoot isn't directly in the Xaml tree of our root. So the dialog
// won't inherit our RequestedTheme automagically.
// GH#5195, GH#3654 Because we cannot set RequestedTheme at the application level,
// we occasionally run into issues where parts of our UI end up themed incorrectly.
// Dialogs, for example, live under a different Xaml root element than the rest of
// our application. This makes our popup menus and buttons "disappear" when the
// user wants Terminal to be in a different theme than the rest of the system.
// This hack---and it _is_ a hack--walks up a dialog's ancestry and forces the
// theme on each element up to the root. We're relying a bit on Xaml's implementation
// details here, but it does have the desired effect.
// It's not enough to set the theme on the dialog alone.
auto themingLambda{ [this](const Windows::Foundation::IInspectable& sender, const RoutedEventArgs&) {
auto theme{ _settings.GlobalSettings().Theme() };
auto element{ sender.try_as<winrt::Windows::UI::Xaml::FrameworkElement>() };
while (element)
{
element.RequestedTheme(theme);
element = element.Parent().try_as<winrt::Windows::UI::Xaml::FrameworkElement>();
}
} };
themingLambda(dialog, nullptr); // if it's already in the tree
auto loadedRevoker{ dialog.Loaded(winrt::auto_revoke, themingLambda) }; // if it's not yet in the tree
// Display the dialog.
co_return co_await dialog.ShowAsync(Controls::ContentDialogPlacement::Popup);
// After the dialog is dismissed, the dialog lock (held by `lock`) will
// be released so another can be shown
}
// Method Description:
// - Displays a dialog for errors found while loading or validating the
// settings. Uses the resources under the provided title and content keys
// as the title and first content of the dialog, then also displays a
// message for whatever exception was found while validating the settings.
// - Only one dialog can be visible at a time. If another dialog is visible
// when this is called, nothing happens. See ShowDialog for details
// Arguments:
// - titleKey: The key to use to lookup the title text from our resources.
// - contentKey: The key to use to lookup the content text from our resources.
void AppLogic::_ShowLoadErrorsDialog(const winrt::hstring& titleKey,
const winrt::hstring& contentKey,
HRESULT settingsLoadedResult)
{
auto title = GetLibraryResourceString(titleKey);
auto buttonText = RS_(L"Ok");
Controls::TextBlock warningsTextBlock;
// Make sure you can copy-paste
warningsTextBlock.IsTextSelectionEnabled(true);
// Make sure the lines of text wrap
warningsTextBlock.TextWrapping(TextWrapping::Wrap);
winrt::Windows::UI::Xaml::Documents::Run errorRun;
const auto errorLabel = GetLibraryResourceString(contentKey);
errorRun.Text(errorLabel);
warningsTextBlock.Inlines().Append(errorRun);
warningsTextBlock.Inlines().Append(Documents::LineBreak{});
if (FAILED(settingsLoadedResult))
{
if (!_settingsLoadExceptionText.empty())
{
warningsTextBlock.Inlines().Append(_BuildErrorRun(_settingsLoadExceptionText, ::winrt::Windows::UI::Xaml::Application::Current().as<::winrt::TerminalApp::App>().Resources()));
warningsTextBlock.Inlines().Append(Documents::LineBreak{});
}
}
// Add a note that we're using the default settings in this case.
winrt::Windows::UI::Xaml::Documents::Run usingDefaultsRun;
const auto usingDefaultsText = RS_(L"UsingDefaultSettingsText");
usingDefaultsRun.Text(usingDefaultsText);
warningsTextBlock.Inlines().Append(Documents::LineBreak{});
warningsTextBlock.Inlines().Append(usingDefaultsRun);
Controls::ContentDialog dialog;
dialog.Title(winrt::box_value(title));
dialog.Content(winrt::box_value(warningsTextBlock));
dialog.CloseButtonText(buttonText);
dialog.DefaultButton(Controls::ContentDialogButton::Close);
ShowDialog(dialog);
}
// Method Description:
// - Displays a dialog for warnings found while loading or validating the
// settings. Displays messages for whatever warnings were found while
// validating the settings.
// - Only one dialog can be visible at a time. If another dialog is visible
// when this is called, nothing happens. See ShowDialog for details
void AppLogic::_ShowLoadWarningsDialog()
{
auto title = RS_(L"SettingsValidateErrorTitle");
auto buttonText = RS_(L"Ok");
Controls::TextBlock warningsTextBlock;
// Make sure you can copy-paste
warningsTextBlock.IsTextSelectionEnabled(true);
// Make sure the lines of text wrap
warningsTextBlock.TextWrapping(TextWrapping::Wrap);
for (const auto& warning : _warnings)
{
// Try looking up the warning message key for each warning.
const auto warningText = _GetWarningText(warning);
if (!warningText.empty())
{
warningsTextBlock.Inlines().Append(_BuildErrorRun(warningText, ::winrt::Windows::UI::Xaml::Application::Current().as<::winrt::TerminalApp::App>().Resources()));
// The "LegacyGlobalsProperty" warning is special - it has a URL
// that goes with it. So we need to manually construct a
// Hyperlink and insert it along with the warning text.
if (warning == SettingsLoadWarnings::LegacyGlobalsProperty)
{
// Add the URL here too
const auto legacyGlobalsLinkLabel = RS_(L"LegacyGlobalsPropertyHrefLabel");
const auto legacyGlobalsLinkUriValue = RS_(L"LegacyGlobalsPropertyHrefUrl");
winrt::Windows::UI::Xaml::Documents::Run legacyGlobalsLinkText;
winrt::Windows::UI::Xaml::Documents::Hyperlink legacyGlobalsLink;
winrt::Windows::Foundation::Uri legacyGlobalsLinkUri{ legacyGlobalsLinkUriValue };
legacyGlobalsLinkText.Text(legacyGlobalsLinkLabel);
legacyGlobalsLink.NavigateUri(legacyGlobalsLinkUri);
legacyGlobalsLink.Inlines().Append(legacyGlobalsLinkText);
warningsTextBlock.Inlines().Append(legacyGlobalsLink);
}
warningsTextBlock.Inlines().Append(Documents::LineBreak{});
}
}
Controls::ContentDialog dialog;
dialog.Title(winrt::box_value(title));
dialog.Content(winrt::box_value(warningsTextBlock));
dialog.CloseButtonText(buttonText);
dialog.DefaultButton(Controls::ContentDialogButton::Close);
ShowDialog(dialog);
}
// Method Description:
// - Triggered when the application is finished loading. If we failed to load
// the settings, then this will display the error dialog. This is done
// here instead of when loading the settings, because we need our UI to be
// visible to display the dialog, and when we're loading the settings,
// the UI might not be visible yet.
// Arguments:
// - <unused>
void AppLogic::_OnLoaded(const IInspectable& /*sender*/,
const RoutedEventArgs& /*eventArgs*/)
{
if (_settings.GlobalSettings().InputServiceWarning())
{
const auto keyboardServiceIsDisabled = !_IsKeyboardServiceEnabled();
if (keyboardServiceIsDisabled)
{
_root->ShowKeyboardServiceWarning();
}
}
if (FAILED(_settingsLoadedResult))
{
const winrt::hstring titleKey = USES_RESOURCE(L"InitialJsonParseErrorTitle");
const winrt::hstring textKey = USES_RESOURCE(L"InitialJsonParseErrorText");
_ShowLoadErrorsDialog(titleKey, textKey, _settingsLoadedResult);
}
else if (_settingsLoadedResult == S_FALSE)
{
_ShowLoadWarningsDialog();
}
}
// Method Description:
// - Helper for determining if the "Touch Keyboard and Handwriting Panel
// Service" is enabled. If it isn't, we want to be able to display a
// warning to the user, because they won't be able to type in the
// Terminal.
// Return Value:
// - true if the service is enabled, or if we fail to query the service. We
// return true in that case, to be less noisy (though, that is unexpected)
bool AppLogic::_IsKeyboardServiceEnabled()
{
if (IsUwp())
{
return true;
}
// If at any point we fail to open the service manager, the service,
// etc, then just quick return true to disable the dialog. We'd rather
// not be noisy with this dialog if we failed for some reason.
// Open the service manager. This will return 0 if it failed.
wil::unique_schandle hManager{ OpenSCManager(nullptr, nullptr, 0) };
if (LOG_LAST_ERROR_IF(!hManager.is_valid()))
{
return true;
}
// Get a handle to the keyboard service
wil::unique_schandle hService{ OpenService(hManager.get(), TabletInputServiceKey.data(), SERVICE_QUERY_STATUS) };
if (LOG_LAST_ERROR_IF(!hService.is_valid()))
{
return true;
}
// Get the current state of the service
SERVICE_STATUS status{ 0 };
if (!LOG_IF_WIN32_BOOL_FALSE(QueryServiceStatus(hService.get(), &status)))
{
return true;
}
const auto state = status.dwCurrentState;
return (state == SERVICE_RUNNING || state == SERVICE_START_PENDING);
}
// Method Description:
// - Get the size in pixels of the client area we'll need to launch this
// terminal app. This method will use the default profile's settings to do
// this calculation, as well as the _system_ dpi scaling. See also
// TermControl::GetProposedDimensions.
// Arguments:
// - <none>
// Return Value:
// - a point containing the requested dimensions in pixels.
Add support for running a `wt` commandline in the curent window WITH A KEYBINDING (#6537) ## Summary of the Pull Request Adds a execute commandline action (`wt`), which lets a user bind a key to a specific `wt` commandline. This commandline will get parsed and run _in the current window_. ## References * Related to #4472 * Related to #5400 - I need this for the commandline mode of the Command Palette * Related to #5970 ## PR Checklist * [x] Closes oh, there's not actually an issue for this. * [x] I work here * [x] Tests added/passed * [ ] Requires documentation to be updated - yes it does ## Detailed Description of the Pull Request / Additional comments One important part of this change concerns how panes are initialized at runtime. We've had some persistent trouble with initializing multiple panes, because they rely on knowing how big they'll actually be, to be able to determine if they can split again. We previously worked around this by ignoring the size check when we were in "startup", processing an initial commandline. This PR however requires us to be able to know the initial size of a pane at runtime, but before the parents have necessarily been added to the tree, or had their renderer's set up. This led to the development of `Pane::PreCalculateCanSplit`, which is very highly similar to `Pane::PreCalculateAutoSplit`. This method attempts to figure out how big a pane _will_ take, before the parent has necessarily laid out. This also involves a small change to `TermControl`, because if its renderer hasn't been set up yet, it'll always think the font is `{0, fontHeight}`, which will let the Terminal keep splitting in the x direction. This change also makes the TermControl set up a renderer to get the real font size when it hasn't yet been initialized. ## Validation Steps Performed This was what the json blob I was using for testing evolved into ```json { "command": { "action":"wt", "commandline": "new-tab cmd.exe /k #work 15 ; split-pane cmd.exe /k #work 15 ; split-pane cmd.exe /k media-commandline ; new-tab powershell dev\\symbols.ps1 ; new-tab -p \"Ubuntu\" ; new-tab -p \"haunter.gif\" ; focus-tab -t 0", }, "keys": ["ctrl+shift+n"] } ``` I also added some tests. # TODO * [x] Creating a `{ "command": "wt" }` action without a commandline will spawn a new `wt.exe` process? - Probably should just do nothing for the empty string
2020-07-17 23:05:29 +02:00
winrt::Windows::Foundation::Size AppLogic::GetLaunchDimensions(uint32_t dpi)
{
if (!_loadedInitialSettings)
{
// Load settings if we haven't already
LoadSettings();
}
// Use the default profile to determine how big of a window we need.
const auto settings{ TerminalSettings::CreateWithNewTerminalArgs(_settings, nullptr, nullptr) };
auto proposedSize = TermControl::GetProposedDimensions(settings.DefaultSettings(), dpi);
const float scale = static_cast<float>(dpi) / static_cast<float>(USER_DEFAULT_SCREEN_DPI);
// GH#2061 - If the global setting "Always show tab bar" is
// set or if "Show tabs in title bar" is set, then we'll need to add
// the height of the tab bar here.
if (_settings.GlobalSettings().ShowTabsInTitlebar())
{
// If we're showing the tabs in the titlebar, we need to use a
// TitlebarControl here to calculate how much space to reserve.
//
// We'll create a fake TitlebarControl, and we'll propose an
// available size to it with Measure(). After Measure() is called,
// the TitlebarControl's DesiredSize will contain the _unscaled_
// size that the titlebar would like to use. We'll use that as part
// of the height calculation here.
auto titlebar = TitlebarControl{ static_cast<uint64_t>(0) };
titlebar.Measure({ SHRT_MAX, SHRT_MAX });
Add support for running a `wt` commandline in the curent window WITH A KEYBINDING (#6537) ## Summary of the Pull Request Adds a execute commandline action (`wt`), which lets a user bind a key to a specific `wt` commandline. This commandline will get parsed and run _in the current window_. ## References * Related to #4472 * Related to #5400 - I need this for the commandline mode of the Command Palette * Related to #5970 ## PR Checklist * [x] Closes oh, there's not actually an issue for this. * [x] I work here * [x] Tests added/passed * [ ] Requires documentation to be updated - yes it does ## Detailed Description of the Pull Request / Additional comments One important part of this change concerns how panes are initialized at runtime. We've had some persistent trouble with initializing multiple panes, because they rely on knowing how big they'll actually be, to be able to determine if they can split again. We previously worked around this by ignoring the size check when we were in "startup", processing an initial commandline. This PR however requires us to be able to know the initial size of a pane at runtime, but before the parents have necessarily been added to the tree, or had their renderer's set up. This led to the development of `Pane::PreCalculateCanSplit`, which is very highly similar to `Pane::PreCalculateAutoSplit`. This method attempts to figure out how big a pane _will_ take, before the parent has necessarily laid out. This also involves a small change to `TermControl`, because if its renderer hasn't been set up yet, it'll always think the font is `{0, fontHeight}`, which will let the Terminal keep splitting in the x direction. This change also makes the TermControl set up a renderer to get the real font size when it hasn't yet been initialized. ## Validation Steps Performed This was what the json blob I was using for testing evolved into ```json { "command": { "action":"wt", "commandline": "new-tab cmd.exe /k #work 15 ; split-pane cmd.exe /k #work 15 ; split-pane cmd.exe /k media-commandline ; new-tab powershell dev\\symbols.ps1 ; new-tab -p \"Ubuntu\" ; new-tab -p \"haunter.gif\" ; focus-tab -t 0", }, "keys": ["ctrl+shift+n"] } ``` I also added some tests. # TODO * [x] Creating a `{ "command": "wt" }` action without a commandline will spawn a new `wt.exe` process? - Probably should just do nothing for the empty string
2020-07-17 23:05:29 +02:00
proposedSize.Height += (titlebar.DesiredSize().Height) * scale;
}
else if (_settings.GlobalSettings().AlwaysShowTabs())
{
// Otherwise, let's use a TabRowControl to calculate how much extra
// space we'll need.
//
// Similarly to above, we'll measure it with an arbitrarily large
// available space, to make sure we get all the space it wants.
auto tabControl = TabRowControl();
tabControl.Measure({ SHRT_MAX, SHRT_MAX });
// For whatever reason, there's about 10px of unaccounted-for space
// in the application. I couldn't tell you where these 10px are
// coming from, but they need to be included in this math.
proposedSize.Height += (tabControl.DesiredSize().Height + 10) * scale;
}
return proposedSize;
}
// Method Description:
// - Get the launch mode in json settings file. Now there
// two launch mode: default, maximized. Default means the window
// will launch according to the launch dimensions provided. Maximized
// means the window will launch as a maximized window
// Arguments:
// - <none>
// Return Value:
// - LaunchMode enum that indicates the launch mode
LaunchMode AppLogic::GetLaunchMode()
{
if (!_loadedInitialSettings)
{
// Load settings if we haven't already
LoadSettings();
}
// GH#4620/#5801 - If the user passed --maximized or --fullscreen on the
// commandline, then use that to override the value from the settings.
const auto valueFromSettings = _settings.GlobalSettings().LaunchMode();
const auto valueFromCommandlineArgs = _appArgs.GetLaunchMode();
return valueFromCommandlineArgs.has_value() ?
valueFromCommandlineArgs.value() :
valueFromSettings;
}
// Method Description:
// - Get the user defined initial position from Json settings file.
// This position represents the top left corner of the Terminal window.
// This setting is optional, if not provided, we will use the system
// default size, which is provided in IslandWindow::MakeWindow.
// Arguments:
// - defaultInitialX: the system default x coordinate value
// - defaultInitialY: the system default y coordinate value
// Return Value:
// - a point containing the requested initial position in pixels.
TerminalApp::InitialPosition AppLogic::GetInitialPosition(int64_t defaultInitialX, int64_t defaultInitialY)
{
if (!_loadedInitialSettings)
{
// Load settings if we haven't already
LoadSettings();
}
const auto initialPosition{ _settings.GlobalSettings().InitialPosition() };
return {
initialPosition.X ? initialPosition.X.Value() : defaultInitialX,
initialPosition.Y ? initialPosition.Y.Value() : defaultInitialY
};
}
bool AppLogic::CenterOnLaunch()
{
if (!_loadedInitialSettings)
{
// Load settings if we haven't already
LoadSettings();
}
return _settings.GlobalSettings().CenterOnLaunch();
}
winrt::Windows::UI::Xaml::ElementTheme AppLogic::GetRequestedTheme()
{
if (!_loadedInitialSettings)
{
// Load settings if we haven't already
LoadSettings();
}
return _settings.GlobalSettings().Theme();
}
bool AppLogic::GetShowTabsInTitlebar()
{
if (!_loadedInitialSettings)
{
// Load settings if we haven't already
LoadSettings();
}
return _settings.GlobalSettings().ShowTabsInTitlebar();
}
7996: Always on Top setting does not persist (#8125) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes https://github.com/microsoft/terminal/issues/7996 * [x] CLA signed. * [ ] Documentation updated - irrelevant * [ ] Schema updated - irrelevant * [ ] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #xxx <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments Currently the value of AlwaysOnTop is read by the AppHost from AppLogic that takes this value from the root TerminalPage. However at this stage neither AppLogic nor TerminalPage are initialized, and thus the return value is always false. This PR introduces a "GetInitialAlwaysOnTop" method to AppLogic that returns a value that is configured in the settings. In addition, the TerminalPage creation was fixed to read the configuration value upon creation (and not just after settings reload). <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed * Only manual testing * Starting the system with both initial value set to true and false * Verifying that dynamic toggling on / off is not affected
2020-11-02 19:51:29 +01:00
bool AppLogic::GetInitialAlwaysOnTop()
{
if (!_loadedInitialSettings)
{
// Load settings if we haven't already
LoadSettings();
}
return _settings.GlobalSettings().AlwaysOnTop();
}
Snap to character grid when resizing window (#3181) When user resizes window, snap the size to align with the character grid (like e.g. putty, mintty and most unix terminals). Properly resolves arbitrary pane configuration (even with different font sizes and padding) trying to align each pane as close as possible. It also fixes terminal minimum size enforcement which was not quite well handled, especially with multiple panes. This PR does not however try to keep the terminals aligned at other user actions (e.g. font change or pane split). That is to be tracked by some other activity. Snapping is resolved in the pane tree, recursively, so it (hopefully) works for any possible layout. Along the way I had to clean up some things as so to make the resulting code not so cumbersome: 1. Pane.cpp: Replaced _firstPercent and _secondPercent with single _desiredSplitPosition to reduce invariants - these had to be kept in sync so their sum always gives 1 (and were not really a percent). The desired part refers to fact that since panes are aligned, there is usually some deviation from that ratio. 2. Pane.cpp: Fixed _GetMinSize() - it was improperly accounting for split direction 3. TerminalControl: Made dedicated member for padding instead of reading it from a control itself. This is because the winrt property functions turned out to be slow and this algorithm needs to access it many times. I also cached scrollbar width for the same reason. 4. AppHost: Moved window to client size resolution to virtual method, where IslandWindow and NonClientIslandWindow have their own implementations (as opposite to pointer casting). One problem with current implementation is I had to make a long call chain from the window that requests snapping to the (root) pane that implements it: IslandWindow -> AppHost's callback -> App -> TerminalPage -> Tab -> Pane. I don't know if this can be done better. ## Validation Steps Performed Spam split pane buttons, randomly change font sizes with ctrl+mouse wheel and drag the window back and forth. Closes #2834 Closes #2277
2020-01-08 22:19:23 +01:00
// Method Description:
// - See Pane::CalcSnappedDimension
float AppLogic::CalcSnappedDimension(const bool widthOrHeight, const float dimension) const
{
return _root->CalcSnappedDimension(widthOrHeight, dimension);
}
// Method Description:
// - Attempt to load the settings. If we fail for any reason, returns an error.
// Return Value:
// - S_OK if we successfully parsed the settings, otherwise an appropriate HRESULT.
[[nodiscard]] HRESULT AppLogic::_TryLoadSettings() noexcept
{
HRESULT hr = E_FAIL;
try
{
auto newSettings = _isUwp ? CascadiaSettings::LoadUniversal() : CascadiaSettings::LoadAll();
_settings = newSettings;
if (_settings.GetLoadingError())
{
_settingsLoadExceptionText = _GetErrorText(_settings.GetLoadingError().Value());
return E_INVALIDARG;
}
else if (!_settings.GetSerializationErrorMessage().empty())
{
_settingsLoadExceptionText = _settings.GetSerializationErrorMessage();
return E_INVALIDARG;
}
_warnings.clear();
for (uint32_t i = 0; i < _settings.Warnings().Size(); i++)
{
_warnings.push_back(_settings.Warnings().GetAt(i));
}
_hasSettingsStartupActions = false;
const auto startupActions = _settings.GlobalSettings().StartupActions();
if (!startupActions.empty())
{
_settingsAppArgs.FullResetState();
ExecuteCommandlineArgs args{ _settings.GlobalSettings().StartupActions() };
auto result = _settingsAppArgs.ParseArgs(args);
if (result == 0)
{
_hasSettingsStartupActions = true;
// Validation also injects new-tab command if implicit new-tab was provided.
_settingsAppArgs.ValidateStartupCommands();
}
else
{
_warnings.push_back(SettingsLoadWarnings::FailedToParseStartupActions);
}
}
hr = _warnings.empty() ? S_OK : S_FALSE;
}
catch (const winrt::hresult_error& e)
{
hr = e.code();
_settingsLoadExceptionText = e.message();
LOG_HR(hr);
}
catch (...)
{
hr = wil::ResultFromCaughtException();
LOG_HR(hr);
}
return hr;
}
// Method Description:
// - Initialized our settings. See CascadiaSettings for more details.
// Additionally hooks up our callbacks for keybinding events to the
// keybindings object.
// NOTE: This must be called from a MTA if we're running as a packaged
// application. The Windows.Storage APIs require a MTA. If this isn't
// happening during startup, it'll need to happen on a background thread.
void AppLogic::LoadSettings()
{
auto start = std::chrono::high_resolution_clock::now();
TraceLoggingWrite(
g_hTerminalAppProvider,
"SettingsLoadStarted",
TraceLoggingDescription("Event emitted before loading the settings"),
TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES),
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance));
// Attempt to load the settings.
// If it fails,
// - use Default settings,
// - don't persist them (LoadAll won't save them in this case).
// - _settingsLoadedResult will be set to an error, indicating that
// we should display the loading error.
// * We can't display the error now, because we might not have a
// UI yet. We'll display the error in _OnLoaded.
_settingsLoadedResult = _TryLoadSettings();
if (FAILED(_settingsLoadedResult))
{
_settings = CascadiaSettings::LoadDefaults();
}
auto end = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> delta = end - start;
TraceLoggingWrite(
g_hTerminalAppProvider,
"SettingsLoadComplete",
TraceLoggingDescription("Event emitted when loading the settings is finished"),
TraceLoggingFloat64(delta.count(), "Duration"),
TraceLoggingKeyword(MICROSOFT_KEYWORD_MEASURES),
TelemetryPrivacyDataTag(PDT_ProductAndServicePerformance));
_loadedInitialSettings = true;
// Register for directory change notification.
_RegisterSettingsChange();
Jumplist::UpdateJumplist(_settings);
}
// Method Description:
// - Registers for changes to the settings folder and upon a updated settings
// profile calls _ReloadSettings().
// Arguments:
// - <none>
// Return Value:
// - <none>
void AppLogic::_RegisterSettingsChange()
{
// Get the containing folder.
Introduce TerminalSettingsModel project (#7667) Introduces a new TerminalSettingsModel (TSM) project. This project is responsible for (de)serializing and exposing Windows Terminal's settings as WinRT objects. ## References #885: TSM epic #1564: Settings UI is dependent on this for data binding and settings access #6904: TSM Spec In the process of ripping out TSM from TerminalApp, a few other changes were made to make this possible: 1. AppLogic's `ApplicationDisplayName` and `ApplicationVersion` was moved to `CascadiaSettings` - These are defined as static functions. They also no longer check if `AppLogic::Current()` is nullptr. 2. `enum LaunchMode` was moved from TerminalApp to TSM 3. `AzureConnectionType` and `TelnetConnectionType` were moved from the profile generators to their respective TerminalConnections 4. CascadiaSettings' `SettingsPath` and `DefaultSettingsPath` are exposed as `hstring` instead of `std::filesystem::path` 5. `Command::ExpandCommands()` was exposed via the IDL - This required some of the warnings to be saved to an `IVector` instead of `std::vector`, among some other small changes. 6. The localization resources had to be split into two halves. - Resource file linked in init.cpp. Verified at runtime thanks to the StaticResourceLoader. 7. Added constructors to some `ActionArgs` 8. Utils.h/cpp were moved to `cascadia/inc`. `JsonKey()` was moved to `JsonUtils`. Both TermApp and TSM need access to Utils.h/cpp. A large amount of work includes moving to the new namespace (`TerminalApp` --> `Microsoft::Terminal::Settings::Model`). Fixing the tests had its own complications. Testing required us to split up TSM into a DLL and LIB, similar to TermApp. Discussion on creating a non-local test variant can be found in #7743. Closes #885
2020-10-06 18:56:59 +02:00
const std::filesystem::path settingsPath{ std::wstring_view{ CascadiaSettings::SettingsPath() } };
const auto folder = settingsPath.parent_path();
_reader.create(folder.c_str(),
false,
wil::FolderChangeEvents::All,
[this, settingsPath](wil::FolderChangeEvent event, PCWSTR fileModified) {
// We want file modifications, AND when files are renamed to be
// settings.json. This second case will oftentimes happen with text
// editors, who will write a temp file, then rename it to be the
// actual file you wrote. So listen for that too.
if (!(event == wil::FolderChangeEvent::Modified ||
event == wil::FolderChangeEvent::RenameNewName ||
event == wil::FolderChangeEvent::Removed))
{
return;
}
std::filesystem::path modifiedFilePath = fileModified;
// Getting basename (filename.ext)
const auto settingsBasename = settingsPath.filename();
const auto modifiedBasename = modifiedFilePath.filename();
if (settingsBasename == modifiedBasename)
{
this->_DispatchReloadSettings();
}
});
}
// Method Description:
// - Dispatches a settings reload with debounce.
// Text editors implement Save in a bunch of different ways, so
// this stops us from reloading too many times or too quickly.
fire_and_forget AppLogic::_DispatchReloadSettings()
{
static constexpr auto FileActivityQuiesceTime{ std::chrono::milliseconds(50) };
if (!_settingsReloadQueued.exchange(true))
{
co_await winrt::resume_after(FileActivityQuiesceTime);
_ReloadSettings();
_settingsReloadQueued.store(false);
}
}
void AppLogic::_ApplyLanguageSettingChange()
{
using ApplicationLanguages = winrt::Windows::Globalization::ApplicationLanguages;
const auto language = _settings.GlobalSettings().Language();
const auto primaryLanguageOverride = ApplicationLanguages::PrimaryLanguageOverride();
if (primaryLanguageOverride != language)
{
ApplicationLanguages::PrimaryLanguageOverride(language);
}
}
Converts Dispatcher().RunAsync to WinRT Coroutines (#4051) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR turns all* instances of `Dispatcher().RunAsync` to WinRT coroutines 👌. This was good coding fodder to fill my plane ride ✈️. Enjoy your holidays everyone! *With the exception of three functions whose signatures cannot be changed due to inheritance and function overriding in `TermControlAutomationPeer` [`L44`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L44), [`L58`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L58), [`L72`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L72). <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #3919 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [ ] Tests added/passed * [ ] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #3919 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments My thought pattern here was to minimally disturb the existing code where possible. So where I could, I converted existing functions into coroutine using functions (like in the [core example](https://github.com/microsoft/terminal/issues/3919#issue-536598706)). For ~the most part~ all instances, I used the format where [`this` is accessed safely within a locked scope](https://github.com/microsoft/terminal/issues/3919#issuecomment-564730620). Some function signatures were changed to take objects by value instead of reference, so the coroutines don't crash when the objects are accessed past their original lifetime. The [copy](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1132) and [paste](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1170) event handler entry points were originally set to a high priority; however, the WinRT coroutines don't appear to support a priority scheme so this priority setting was not preserved in the translation. <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed Compiles and runs, and for every event with a clear trigger repro, I triggered it to ensure crashes weren't introduced.
2020-01-10 04:29:49 +01:00
fire_and_forget AppLogic::_LoadErrorsDialogRoutine()
{
co_await winrt::resume_foreground(_root->Dispatcher());
const winrt::hstring titleKey = USES_RESOURCE(L"ReloadJsonParseErrorTitle");
const winrt::hstring textKey = USES_RESOURCE(L"ReloadJsonParseErrorText");
_ShowLoadErrorsDialog(titleKey, textKey, _settingsLoadedResult);
}
fire_and_forget AppLogic::_ShowLoadWarningsDialogRoutine()
{
co_await winrt::resume_foreground(_root->Dispatcher());
_ShowLoadWarningsDialog();
}
fire_and_forget AppLogic::_RefreshThemeRoutine()
{
co_await winrt::resume_foreground(_root->Dispatcher());
// Refresh the UI theme
_ApplyTheme(_settings.GlobalSettings().Theme());
Converts Dispatcher().RunAsync to WinRT Coroutines (#4051) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR turns all* instances of `Dispatcher().RunAsync` to WinRT coroutines 👌. This was good coding fodder to fill my plane ride ✈️. Enjoy your holidays everyone! *With the exception of three functions whose signatures cannot be changed due to inheritance and function overriding in `TermControlAutomationPeer` [`L44`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L44), [`L58`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L58), [`L72`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L72). <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #3919 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [ ] Tests added/passed * [ ] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #3919 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments My thought pattern here was to minimally disturb the existing code where possible. So where I could, I converted existing functions into coroutine using functions (like in the [core example](https://github.com/microsoft/terminal/issues/3919#issue-536598706)). For ~the most part~ all instances, I used the format where [`this` is accessed safely within a locked scope](https://github.com/microsoft/terminal/issues/3919#issuecomment-564730620). Some function signatures were changed to take objects by value instead of reference, so the coroutines don't crash when the objects are accessed past their original lifetime. The [copy](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1132) and [paste](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1170) event handler entry points were originally set to a high priority; however, the WinRT coroutines don't appear to support a priority scheme so this priority setting was not preserved in the translation. <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed Compiles and runs, and for every event with a clear trigger repro, I triggered it to ensure crashes weren't introduced.
2020-01-10 04:29:49 +01:00
}
// Function Description:
// Returns the current app package or nullptr.
// TRANSITIONAL
// Exists to work around a compiler bug. This function encapsulates the
// exception handling that we used to keep around calls to Package::Current,
// so that when it's called inside a coroutine and fails it doesn't explode
// terribly.
static winrt::Windows::ApplicationModel::Package GetCurrentPackageNoThrow() noexcept
{
try
{
return winrt::Windows::ApplicationModel::Package::Current();
}
catch (...)
{
// discard any exception -- literally pretend we're not in a package
}
return nullptr;
}
Add startup task, setting to launch application on login (#4908) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR adds a new boolean global setting, startOnUserLogin, along with associated AppLogic to request enabling or disabling of the StartupTask. Added UAP5 extensions to AppX manifests. <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References #2189 <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #2189 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [x] Tests added/passed * [x] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #2189 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments Please note, I'm a non-practicing C++ developer, there are a number of things I wasn't sure how to handle in the appropriate fashion, mostly around error handling and what probably looks like an incredibly naive (and messy) way to implement the async co_await behavior. Error handling-wise, I found (don't ask me how!) that if you somehow mismatch the startup task's ID between the manifest and the call to `StartupTask::GetAsync(hstring taskId)`, you'll get a very opaque WinRT exception that boils down to a generic invalid argument message. This isn't likely to happen in the wild, but worth mentioning... I had enough trouble getting myself familiarized with the project, environment, and C++/WinRT in general didn't want to try to tackle adding tests for this quite yet since (as I mentioned) I don't really know what I'm doing. I'm happy to give it a try with perhaps a bit of assistance in getting started 😃 Further work in this area of the application outside of this immediate PR might need to include adding an additional setting to contain launch args that the startup task can pass to the app so that users can specify a non-default profile to launch on start, window position (e.g., #653). <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed ✔️ Default settings: Given the user does not have the `startOnUserLogin` setting in their profile.json, When the default settings are opened (via alt+click on Settings), Then the global settings should contain the `"startOnUserLogin": false` token ✔️ Applying setting on application launch Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `disabled` and the application is not running When the application is launched Then the `Windows Terminal` entry in the user's Startup list should be `enabled` ✔️ Applying setting on settings change Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `enabled` and the application is running When the `startOnUserLogin` setting is changed to `false` and the settings file is saved to disk Then the `Windows Terminal` startup task entry should be `disabled` ✔️ Setting is ignored when user has manually disabled startup Given the `startOnUserLogin` is `true` and the application is not running and the `Windows Terminal` startup task has been set to `disabled` via user action When the application is launched Then the startup task should remain disabled and the application should not throw an exception #### note: Task Manager does not seem to re-scan startup task states after launch; the Settings -> Apps -> Startup page also requires closing or moving away to refresh the status of entries
2020-06-01 22:24:43 +02:00
fire_and_forget AppLogic::_ApplyStartupTaskStateChange()
try
Add startup task, setting to launch application on login (#4908) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR adds a new boolean global setting, startOnUserLogin, along with associated AppLogic to request enabling or disabling of the StartupTask. Added UAP5 extensions to AppX manifests. <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References #2189 <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #2189 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [x] Tests added/passed * [x] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #2189 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments Please note, I'm a non-practicing C++ developer, there are a number of things I wasn't sure how to handle in the appropriate fashion, mostly around error handling and what probably looks like an incredibly naive (and messy) way to implement the async co_await behavior. Error handling-wise, I found (don't ask me how!) that if you somehow mismatch the startup task's ID between the manifest and the call to `StartupTask::GetAsync(hstring taskId)`, you'll get a very opaque WinRT exception that boils down to a generic invalid argument message. This isn't likely to happen in the wild, but worth mentioning... I had enough trouble getting myself familiarized with the project, environment, and C++/WinRT in general didn't want to try to tackle adding tests for this quite yet since (as I mentioned) I don't really know what I'm doing. I'm happy to give it a try with perhaps a bit of assistance in getting started 😃 Further work in this area of the application outside of this immediate PR might need to include adding an additional setting to contain launch args that the startup task can pass to the app so that users can specify a non-default profile to launch on start, window position (e.g., #653). <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed ✔️ Default settings: Given the user does not have the `startOnUserLogin` setting in their profile.json, When the default settings are opened (via alt+click on Settings), Then the global settings should contain the `"startOnUserLogin": false` token ✔️ Applying setting on application launch Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `disabled` and the application is not running When the application is launched Then the `Windows Terminal` entry in the user's Startup list should be `enabled` ✔️ Applying setting on settings change Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `enabled` and the application is running When the `startOnUserLogin` setting is changed to `false` and the settings file is saved to disk Then the `Windows Terminal` startup task entry should be `disabled` ✔️ Setting is ignored when user has manually disabled startup Given the `startOnUserLogin` is `true` and the application is not running and the `Windows Terminal` startup task has been set to `disabled` via user action When the application is launched Then the startup task should remain disabled and the application should not throw an exception #### note: Task Manager does not seem to re-scan startup task states after launch; the Settings -> Apps -> Startup page also requires closing or moving away to refresh the status of entries
2020-06-01 22:24:43 +02:00
{
// First, make sure we're running in a packaged context. This method
// won't work, and will crash mysteriously if we're running unpackaged.
const auto package{ GetCurrentPackageNoThrow() };
if (package == nullptr)
{
return;
}
Add startup task, setting to launch application on login (#4908) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR adds a new boolean global setting, startOnUserLogin, along with associated AppLogic to request enabling or disabling of the StartupTask. Added UAP5 extensions to AppX manifests. <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References #2189 <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #2189 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [x] Tests added/passed * [x] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #2189 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments Please note, I'm a non-practicing C++ developer, there are a number of things I wasn't sure how to handle in the appropriate fashion, mostly around error handling and what probably looks like an incredibly naive (and messy) way to implement the async co_await behavior. Error handling-wise, I found (don't ask me how!) that if you somehow mismatch the startup task's ID between the manifest and the call to `StartupTask::GetAsync(hstring taskId)`, you'll get a very opaque WinRT exception that boils down to a generic invalid argument message. This isn't likely to happen in the wild, but worth mentioning... I had enough trouble getting myself familiarized with the project, environment, and C++/WinRT in general didn't want to try to tackle adding tests for this quite yet since (as I mentioned) I don't really know what I'm doing. I'm happy to give it a try with perhaps a bit of assistance in getting started 😃 Further work in this area of the application outside of this immediate PR might need to include adding an additional setting to contain launch args that the startup task can pass to the app so that users can specify a non-default profile to launch on start, window position (e.g., #653). <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed ✔️ Default settings: Given the user does not have the `startOnUserLogin` setting in their profile.json, When the default settings are opened (via alt+click on Settings), Then the global settings should contain the `"startOnUserLogin": false` token ✔️ Applying setting on application launch Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `disabled` and the application is not running When the application is launched Then the `Windows Terminal` entry in the user's Startup list should be `enabled` ✔️ Applying setting on settings change Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `enabled` and the application is running When the `startOnUserLogin` setting is changed to `false` and the settings file is saved to disk Then the `Windows Terminal` startup task entry should be `disabled` ✔️ Setting is ignored when user has manually disabled startup Given the `startOnUserLogin` is `true` and the application is not running and the `Windows Terminal` startup task has been set to `disabled` via user action When the application is launched Then the startup task should remain disabled and the application should not throw an exception #### note: Task Manager does not seem to re-scan startup task states after launch; the Settings -> Apps -> Startup page also requires closing or moving away to refresh the status of entries
2020-06-01 22:24:43 +02:00
auto weakThis{ get_weak() };
co_await winrt::resume_foreground(_root->Dispatcher(), CoreDispatcherPriority::Normal);
if (auto page{ weakThis.get() })
{
StartupTaskState state;
bool tryEnableStartupTask = _settings.GlobalSettings().StartOnUserLogin();
Add startup task, setting to launch application on login (#4908) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR adds a new boolean global setting, startOnUserLogin, along with associated AppLogic to request enabling or disabling of the StartupTask. Added UAP5 extensions to AppX manifests. <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References #2189 <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #2189 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [x] Tests added/passed * [x] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #2189 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments Please note, I'm a non-practicing C++ developer, there are a number of things I wasn't sure how to handle in the appropriate fashion, mostly around error handling and what probably looks like an incredibly naive (and messy) way to implement the async co_await behavior. Error handling-wise, I found (don't ask me how!) that if you somehow mismatch the startup task's ID between the manifest and the call to `StartupTask::GetAsync(hstring taskId)`, you'll get a very opaque WinRT exception that boils down to a generic invalid argument message. This isn't likely to happen in the wild, but worth mentioning... I had enough trouble getting myself familiarized with the project, environment, and C++/WinRT in general didn't want to try to tackle adding tests for this quite yet since (as I mentioned) I don't really know what I'm doing. I'm happy to give it a try with perhaps a bit of assistance in getting started 😃 Further work in this area of the application outside of this immediate PR might need to include adding an additional setting to contain launch args that the startup task can pass to the app so that users can specify a non-default profile to launch on start, window position (e.g., #653). <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed ✔️ Default settings: Given the user does not have the `startOnUserLogin` setting in their profile.json, When the default settings are opened (via alt+click on Settings), Then the global settings should contain the `"startOnUserLogin": false` token ✔️ Applying setting on application launch Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `disabled` and the application is not running When the application is launched Then the `Windows Terminal` entry in the user's Startup list should be `enabled` ✔️ Applying setting on settings change Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `enabled` and the application is running When the `startOnUserLogin` setting is changed to `false` and the settings file is saved to disk Then the `Windows Terminal` startup task entry should be `disabled` ✔️ Setting is ignored when user has manually disabled startup Given the `startOnUserLogin` is `true` and the application is not running and the `Windows Terminal` startup task has been set to `disabled` via user action When the application is launched Then the startup task should remain disabled and the application should not throw an exception #### note: Task Manager does not seem to re-scan startup task states after launch; the Settings -> Apps -> Startup page also requires closing or moving away to refresh the status of entries
2020-06-01 22:24:43 +02:00
StartupTask task = co_await StartupTask::GetAsync(StartupTaskName);
state = task.State();
switch (state)
{
case StartupTaskState::Disabled:
{
if (tryEnableStartupTask)
{
co_await task.RequestEnableAsync();
}
break;
}
case StartupTaskState::DisabledByUser:
{
// TODO: GH#6254: define UX for other StartupTaskStates
break;
}
case StartupTaskState::Enabled:
{
if (!tryEnableStartupTask)
{
task.Disable();
}
break;
}
}
}
}
CATCH_LOG();
// Method Description:
2021-04-29 00:13:28 +02:00
// - Reloads the settings from the settings.json file.
void AppLogic::_ReloadSettings()
{
// Attempt to load our settings.
// If it fails,
// - don't change the settings (and don't actually apply the new settings)
// - don't persist them.
// - display a loading error
_settingsLoadedResult = _TryLoadSettings();
if (FAILED(_settingsLoadedResult))
{
Converts Dispatcher().RunAsync to WinRT Coroutines (#4051) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR turns all* instances of `Dispatcher().RunAsync` to WinRT coroutines 👌. This was good coding fodder to fill my plane ride ✈️. Enjoy your holidays everyone! *With the exception of three functions whose signatures cannot be changed due to inheritance and function overriding in `TermControlAutomationPeer` [`L44`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L44), [`L58`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L58), [`L72`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L72). <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #3919 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [ ] Tests added/passed * [ ] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #3919 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments My thought pattern here was to minimally disturb the existing code where possible. So where I could, I converted existing functions into coroutine using functions (like in the [core example](https://github.com/microsoft/terminal/issues/3919#issue-536598706)). For ~the most part~ all instances, I used the format where [`this` is accessed safely within a locked scope](https://github.com/microsoft/terminal/issues/3919#issuecomment-564730620). Some function signatures were changed to take objects by value instead of reference, so the coroutines don't crash when the objects are accessed past their original lifetime. The [copy](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1132) and [paste](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1170) event handler entry points were originally set to a high priority; however, the WinRT coroutines don't appear to support a priority scheme so this priority setting was not preserved in the translation. <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed Compiles and runs, and for every event with a clear trigger repro, I triggered it to ensure crashes weren't introduced.
2020-01-10 04:29:49 +01:00
_LoadErrorsDialogRoutine();
return;
}
else if (_settingsLoadedResult == S_FALSE)
{
Converts Dispatcher().RunAsync to WinRT Coroutines (#4051) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR turns all* instances of `Dispatcher().RunAsync` to WinRT coroutines 👌. This was good coding fodder to fill my plane ride ✈️. Enjoy your holidays everyone! *With the exception of three functions whose signatures cannot be changed due to inheritance and function overriding in `TermControlAutomationPeer` [`L44`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L44), [`L58`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L58), [`L72`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L72). <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #3919 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [ ] Tests added/passed * [ ] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #3919 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments My thought pattern here was to minimally disturb the existing code where possible. So where I could, I converted existing functions into coroutine using functions (like in the [core example](https://github.com/microsoft/terminal/issues/3919#issue-536598706)). For ~the most part~ all instances, I used the format where [`this` is accessed safely within a locked scope](https://github.com/microsoft/terminal/issues/3919#issuecomment-564730620). Some function signatures were changed to take objects by value instead of reference, so the coroutines don't crash when the objects are accessed past their original lifetime. The [copy](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1132) and [paste](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1170) event handler entry points were originally set to a high priority; however, the WinRT coroutines don't appear to support a priority scheme so this priority setting was not preserved in the translation. <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed Compiles and runs, and for every event with a clear trigger repro, I triggered it to ensure crashes weren't introduced.
2020-01-10 04:29:49 +01:00
_ShowLoadWarningsDialogRoutine();
}
// Here, we successfully reloaded the settings, and created a new
// TerminalSettings object.
// Update the settings in TerminalPage
_root->SetSettings(_settings, true);
_ApplyLanguageSettingChange();
Converts Dispatcher().RunAsync to WinRT Coroutines (#4051) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR turns all* instances of `Dispatcher().RunAsync` to WinRT coroutines 👌. This was good coding fodder to fill my plane ride ✈️. Enjoy your holidays everyone! *With the exception of three functions whose signatures cannot be changed due to inheritance and function overriding in `TermControlAutomationPeer` [`L44`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L44), [`L58`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L58), [`L72`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L72). <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #3919 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [ ] Tests added/passed * [ ] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #3919 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments My thought pattern here was to minimally disturb the existing code where possible. So where I could, I converted existing functions into coroutine using functions (like in the [core example](https://github.com/microsoft/terminal/issues/3919#issue-536598706)). For ~the most part~ all instances, I used the format where [`this` is accessed safely within a locked scope](https://github.com/microsoft/terminal/issues/3919#issuecomment-564730620). Some function signatures were changed to take objects by value instead of reference, so the coroutines don't crash when the objects are accessed past their original lifetime. The [copy](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1132) and [paste](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1170) event handler entry points were originally set to a high priority; however, the WinRT coroutines don't appear to support a priority scheme so this priority setting was not preserved in the translation. <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed Compiles and runs, and for every event with a clear trigger repro, I triggered it to ensure crashes weren't introduced.
2020-01-10 04:29:49 +01:00
_RefreshThemeRoutine();
Add startup task, setting to launch application on login (#4908) <!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? --> ## Summary of the Pull Request This PR adds a new boolean global setting, startOnUserLogin, along with associated AppLogic to request enabling or disabling of the StartupTask. Added UAP5 extensions to AppX manifests. <!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> ## References #2189 <!-- Please review the items on the PR checklist before submitting--> ## PR Checklist * [x] Closes #2189 * [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA * [x] Tests added/passed * [x] Requires documentation to be updated * [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #2189 <!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here --> ## Detailed Description of the Pull Request / Additional comments Please note, I'm a non-practicing C++ developer, there are a number of things I wasn't sure how to handle in the appropriate fashion, mostly around error handling and what probably looks like an incredibly naive (and messy) way to implement the async co_await behavior. Error handling-wise, I found (don't ask me how!) that if you somehow mismatch the startup task's ID between the manifest and the call to `StartupTask::GetAsync(hstring taskId)`, you'll get a very opaque WinRT exception that boils down to a generic invalid argument message. This isn't likely to happen in the wild, but worth mentioning... I had enough trouble getting myself familiarized with the project, environment, and C++/WinRT in general didn't want to try to tackle adding tests for this quite yet since (as I mentioned) I don't really know what I'm doing. I'm happy to give it a try with perhaps a bit of assistance in getting started 😃 Further work in this area of the application outside of this immediate PR might need to include adding an additional setting to contain launch args that the startup task can pass to the app so that users can specify a non-default profile to launch on start, window position (e.g., #653). <!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well --> ## Validation Steps Performed ✔️ Default settings: Given the user does not have the `startOnUserLogin` setting in their profile.json, When the default settings are opened (via alt+click on Settings), Then the global settings should contain the `"startOnUserLogin": false` token ✔️ Applying setting on application launch Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `disabled` and the application is not running When the application is launched Then the `Windows Terminal` entry in the user's Startup list should be `enabled` ✔️ Applying setting on settings change Given the `startOnUserLogin` is `true` and the `Windows Terminal` startup task is `enabled` and the application is running When the `startOnUserLogin` setting is changed to `false` and the settings file is saved to disk Then the `Windows Terminal` startup task entry should be `disabled` ✔️ Setting is ignored when user has manually disabled startup Given the `startOnUserLogin` is `true` and the application is not running and the `Windows Terminal` startup task has been set to `disabled` via user action When the application is launched Then the startup task should remain disabled and the application should not throw an exception #### note: Task Manager does not seem to re-scan startup task states after launch; the Settings -> Apps -> Startup page also requires closing or moving away to refresh the status of entries
2020-06-01 22:24:43 +02:00
_ApplyStartupTaskStateChange();
Jumplist::UpdateJumplist(_settings);
2021-04-29 00:13:28 +02:00
_SettingsChangedHandlers(*this, nullptr);
}
// Method Description:
// - Returns a pointer to the global shared settings.
Introduce TerminalSettingsModel project (#7667) Introduces a new TerminalSettingsModel (TSM) project. This project is responsible for (de)serializing and exposing Windows Terminal's settings as WinRT objects. ## References #885: TSM epic #1564: Settings UI is dependent on this for data binding and settings access #6904: TSM Spec In the process of ripping out TSM from TerminalApp, a few other changes were made to make this possible: 1. AppLogic's `ApplicationDisplayName` and `ApplicationVersion` was moved to `CascadiaSettings` - These are defined as static functions. They also no longer check if `AppLogic::Current()` is nullptr. 2. `enum LaunchMode` was moved from TerminalApp to TSM 3. `AzureConnectionType` and `TelnetConnectionType` were moved from the profile generators to their respective TerminalConnections 4. CascadiaSettings' `SettingsPath` and `DefaultSettingsPath` are exposed as `hstring` instead of `std::filesystem::path` 5. `Command::ExpandCommands()` was exposed via the IDL - This required some of the warnings to be saved to an `IVector` instead of `std::vector`, among some other small changes. 6. The localization resources had to be split into two halves. - Resource file linked in init.cpp. Verified at runtime thanks to the StaticResourceLoader. 7. Added constructors to some `ActionArgs` 8. Utils.h/cpp were moved to `cascadia/inc`. `JsonKey()` was moved to `JsonUtils`. Both TermApp and TSM need access to Utils.h/cpp. A large amount of work includes moving to the new namespace (`TerminalApp` --> `Microsoft::Terminal::Settings::Model`). Fixing the tests had its own complications. Testing required us to split up TSM into a DLL and LIB, similar to TermApp. Discussion on creating a non-local test variant can be found in #7743. Closes #885
2020-10-06 18:56:59 +02:00
[[nodiscard]] CascadiaSettings AppLogic::GetSettings() const noexcept
{
return _settings;
}
// Method Description:
// - Update the current theme of the application. This will trigger our
// RequestedThemeChanged event, to have our host change the theme of the
// root of the application.
// Arguments:
// - newTheme: The ElementTheme to apply to our elements.
void AppLogic::_ApplyTheme(const Windows::UI::Xaml::ElementTheme& newTheme)
{
// Propagate the event to the host layer, so it can update its own UI
_RequestedThemeChangedHandlers(*this, newTheme);
}
UIElement AppLogic::GetRoot() noexcept
{
return _root.as<winrt::Windows::UI::Xaml::Controls::Control>();
}
// Method Description:
// - Gets the title of the currently focused terminal control. If there
// isn't a control selected for any reason, returns "Windows Terminal"
// Arguments:
// - <none>
// Return Value:
// - the title of the focused control if there is one, else "Windows Terminal"
hstring AppLogic::Title()
{
if (_root)
{
return _root->Title();
}
return { L"Windows Terminal" };
}
// Method Description:
// - Used to tell the app that the titlebar has been clicked. The App won't
// actually receive any clicks in the titlebar area, so this is a helper
// to clue the app in that a click has happened. The App will use this as
// a indicator that it needs to dismiss any open flyouts.
// Arguments:
// - <none>
// Return Value:
// - <none>
void AppLogic::TitlebarClicked()
{
if (_root)
{
_root->TitlebarClicked();
}
}
// Method Description:
// - Implements the F7 handler (per GH#638)
// - Implements the Alt handler (per GH#6421)
// Return value:
// - whether the key was handled
bool AppLogic::OnDirectKeyEvent(const uint32_t vkey, const uint8_t scanCode, const bool down)
{
if (_root)
{
// Manually bubble the OnDirectKeyEvent event up through the focus tree.
auto xamlRoot{ _root->XamlRoot() };
auto focusedObject{ Windows::UI::Xaml::Input::FocusManager::GetFocusedElement(xamlRoot) };
do
{
if (auto keyListener{ focusedObject.try_as<IDirectKeyListener>() })
{
if (keyListener.OnDirectKeyEvent(vkey, scanCode, down))
{
return true;
}
// otherwise, keep walking. bubble the event manually.
}
if (auto focusedElement{ focusedObject.try_as<Windows::UI::Xaml::FrameworkElement>() })
{
focusedObject = focusedElement.Parent();
// Parent() seems to return null when the focusedElement is created from an ItemTemplate.
// Use the VisualTreeHelper's GetParent as a fallback.
if (!focusedObject)
{
focusedObject = winrt::Windows::UI::Xaml::Media::VisualTreeHelper::GetParent(focusedElement);
}
}
else
{
break; // we hit a non-FE object, stop bubbling.
}
} while (focusedObject);
}
return false;
}
// Method Description:
// - Used to tell the app that the 'X' button has been clicked and
// the user wants to close the app. We kick off the close warning
// experience.
// Arguments:
// - <none>
// Return Value:
// - <none>
void AppLogic::WindowCloseButtonClicked()
{
if (_root)
{
_root->CloseWindow();
}
}
// Method Description:
// - Gets the taskbar state value from the last active control
// Return Value:
// - The taskbar state of the last active control
size_t AppLogic::GetLastActiveControlTaskbarState()
{
if (_root)
{
return _root->GetLastActiveControlTaskbarState();
}
return {};
}
// Method Description:
// - Gets the taskbar progress value from the last active control
// Return Value:
// - The taskbar progress of the last active control
size_t AppLogic::GetLastActiveControlTaskbarProgress()
{
if (_root)
{
return _root->GetLastActiveControlTaskbarProgress();
}
return {};
}
// Method Description:
// - Sets the initial commandline to process on startup, and attempts to
// parse it. Commands will be parsed into a list of ShortcutActions that
// will be processed on TerminalPage::Create().
// - This function will have no effective result after Create() is called.
// - This function returns 0, unless a there was a non-zero result from
// trying to parse one of the commands provided. In that case, no commands
// after the failing command will be parsed, and the non-zero code
// returned.
// Arguments:
// - args: an array of strings to process as a commandline. These args can contain spaces
// Return Value:
// - the result of the first command who's parsing returned a non-zero code,
// or 0. (see AppLogic::_ParseArgs)
int32_t AppLogic::SetStartupCommandline(array_view<const winrt::hstring> args)
{
Add support for running a `wt` commandline in the curent window WITH A KEYBINDING (#6537) ## Summary of the Pull Request Adds a execute commandline action (`wt`), which lets a user bind a key to a specific `wt` commandline. This commandline will get parsed and run _in the current window_. ## References * Related to #4472 * Related to #5400 - I need this for the commandline mode of the Command Palette * Related to #5970 ## PR Checklist * [x] Closes oh, there's not actually an issue for this. * [x] I work here * [x] Tests added/passed * [ ] Requires documentation to be updated - yes it does ## Detailed Description of the Pull Request / Additional comments One important part of this change concerns how panes are initialized at runtime. We've had some persistent trouble with initializing multiple panes, because they rely on knowing how big they'll actually be, to be able to determine if they can split again. We previously worked around this by ignoring the size check when we were in "startup", processing an initial commandline. This PR however requires us to be able to know the initial size of a pane at runtime, but before the parents have necessarily been added to the tree, or had their renderer's set up. This led to the development of `Pane::PreCalculateCanSplit`, which is very highly similar to `Pane::PreCalculateAutoSplit`. This method attempts to figure out how big a pane _will_ take, before the parent has necessarily laid out. This also involves a small change to `TermControl`, because if its renderer hasn't been set up yet, it'll always think the font is `{0, fontHeight}`, which will let the Terminal keep splitting in the x direction. This change also makes the TermControl set up a renderer to get the real font size when it hasn't yet been initialized. ## Validation Steps Performed This was what the json blob I was using for testing evolved into ```json { "command": { "action":"wt", "commandline": "new-tab cmd.exe /k #work 15 ; split-pane cmd.exe /k #work 15 ; split-pane cmd.exe /k media-commandline ; new-tab powershell dev\\symbols.ps1 ; new-tab -p \"Ubuntu\" ; new-tab -p \"haunter.gif\" ; focus-tab -t 0", }, "keys": ["ctrl+shift+n"] } ``` I also added some tests. # TODO * [x] Creating a `{ "command": "wt" }` action without a commandline will spawn a new `wt.exe` process? - Probably should just do nothing for the empty string
2020-07-17 23:05:29 +02:00
const auto result = _appArgs.ParseArgs(args);
if (result == 0)
{
// If the size of the arguments list is 1,
// then it contains only the executable name and no other arguments.
_hasCommandLineArguments = args.size() > 1;
_appArgs.ValidateStartupCommands();
_root->SetStartupActions(_appArgs.GetStartupActions());
// Check if we were started as a COM server for inbound connections of console sessions
// coming out of the operating system default application feature. If so,
// tell TerminalPage to start the listener as we have to make sure it has the chance
// to register a handler to hear about the requests first and is all ready to receive
// them before the COM server registers itself. Otherwise, the request might come
// in and be routed to an event with no handlers or a non-ready Page.
if (_appArgs.IsHandoffListener())
{
_root->SetInboundListener(true);
}
}
return result;
}
// Method Description:
// - Triggers the setup of the listener for incoming console connections
// from the operating system.
// Arguments:
// - <none>
// Return Value:
// - <none>
void AppLogic::SetInboundListener()
{
_root->SetInboundListener(false);
}
Add support for running a commandline in another WT window (#8898) ## Summary of the Pull Request **If you're reading this PR and haven't signed off on #8135, go there first.** ![window-management-000](https://user-images.githubusercontent.com/18356694/103932910-25199380-50e8-11eb-97e3-594a31da62d2.gif) This provides the basic parts of the implementation of #4472. Namely: * We add support for the `--window,-w <window-id>` argument to `wt.exe`, to allow a commandline to be given to another window. * If `window-id` is `0`, run the given commands in _the current window_. * If `window-id` is a negative number, run the commands in a _new_ Terminal window. * If `window-id` is the ID of an existing window, then run the commandline in that window. * If `window-id` is _not_ the ID of an existing window, create a new window. That window will be assigned the ID provided in the commandline. The provided subcommands will be run in that new window. * If `window-id` is omitted, then create a new window. ## References * Spec: #8135 * Megathread: #5000 * Project: projects/5 ## PR Checklist * [x] Closes #4472 * [x] I work here * [x] Tests added/passed * [ ] Requires documentation to be updated - **sure does** ## Detailed Description of the Pull Request / Additional comments Note that `wt -w 1 -d c:\foo cmd.exe` does work, by causing window 1 to change There are limitations, and there are plenty of things to work on in the future: * [ ] We don't support names for windows yet * [ ] We don't support window glomming by default, or a setting to configure what happens when `-w` is omitted. I thought it best to lay the groundwork first, then come back to that. * [ ] `-w 0` currently just uses the "last activated" window, not "the current". There's more follow-up work to try and smartly find the actual window we're being called from. * [ ] Basically anything else that's listed in projects/5. I'm cutting this PR where it currently is, because this is already a huge PR. I believe the remaining tasks will all be easier to land, once this is in. ## Validation Steps Performed I've been creating windows, and closing them, and running cmdlines for a while now. I'm gonna keep doing that while the PR is open, till no bugs remain. # TODOs * [x] There are a bunch of `GetID`, `GetPID` calls that aren't try/caught 😬 - [x] `Monarch.cpp` - [x] `Peasant.cpp` - [x] `WindowManager.cpp` - [x] `AppHost.cpp` * [x] If the monarch gets hung, then _you can't launch any Terminals_ 😨 We should handle this gracefully. - Proposed idea: give the Monarch some time to respond to a proposal for a commandline. If there's no response in that timeframe, this window is now a _hermit_, outside of society entirely. It can't be elected Monarch. It can't receive command lines. It has no ID. - Could we gracefully recover from such a state? maybe, probably not though. - Same deal if a peasant hangs, it could end up hanging the monarch, right? Like if you do `wt -w 2`, and `2` is hung, then does the monarch get hung waiting on the hung peasant? - After talking with @miniksa, **we're gonna punt this from the initial implementation**. If people legit hit this in the wild, we'll fix it then.
2021-02-10 12:28:09 +01:00
// Method Description:
// - Parse the provided commandline arguments into actions, and try to
// perform them immediately.
// - This function returns 0, unless a there was a non-zero result from
// trying to parse one of the commands provided. In that case, no commands
// after the failing command will be parsed, and the non-zero code
// returned.
// - If a non-empty cwd is provided, the entire terminal exe will switch to
// that CWD while we handle these actions, then return to the original
// CWD.
// Arguments:
// - args: an array of strings to process as a commandline. These args can contain spaces
// - cwd: The directory to use as the CWD while performing these actions.
// Return Value:
// - the result of the first command who's parsing returned a non-zero code,
// or 0. (see AppLogic::_ParseArgs)
int32_t AppLogic::ExecuteCommandline(array_view<const winrt::hstring> args,
const winrt::hstring& cwd)
Add `Microsoft.Terminal.Remoting.dll` (#8607) Adds a `Microsoft.Terminal.Remoting.dll` to our solution. This DLL will be responsible for all the Monarch/Peasant work that's been described in #7240 & #8135. This PR does _not_ implement the Monarch/Peasant architecture in any significant way. The goal of this PR is to just to establish the project layout, and the most basic connections. This should make reviewing the actual meat of the implementation (in a later PR) easier. It will also give us the opportunity to include some of the basic weird things we're doing (with `CoRegisterClass`) in the Terminal _now_, and get them selfhosted, before building on them too much. This PR does have windows registering the `Monarch` class with COM. When windows are created, they'll as the Monarch if they should create a new window or not. In this PR, the Monarch will always reply "yes, please make a new window". Similar to other projects in our solution, we're adding 3 projects here: * `Microsoft.Terminal.Remoting.lib`: the actual implementation, as a static lib. * `Microsoft.Terminal.Remoting.dll`: The implementation linked as a DLL, for use in `WindowsTerminal.exe`. * `Remoting.UnitTests.dll`: A unit test dll that links with the static lib. There are plenty of TODOs scattered about the code. Clearly, most of this isn't implemented yet, but I do have more WIP branches. I'm using [`projects/5`](https://github.com/microsoft/terminal/projects/5) as my notation for TODOs that are too small for an issue, but are part of the whole Process Model 2.0 work. ## References * #5000 - this is the process model megathread * #7240 - The process model 2.0 spec. * #8135 - the window management spec. (please review me, I have 0/3 signoffs even after the discussion we had 😢) * #8171 - the Monarch/peasant sample. (please review me, I have 1/2) ## PR Checklist * [x] Closes nothing, this is just infrastructure * [x] I work here * [x] Tests added/passed * [n/a] Requires documentation to be updated
2021-01-07 23:59:37 +01:00
{
::TerminalApp::AppCommandlineArgs appArgs;
auto result = appArgs.ParseArgs(args);
if (result == 0)
{
auto actions = winrt::single_threaded_vector<ActionAndArgs>(std::move(appArgs.GetStartupActions()));
Add support for running a commandline in another WT window (#8898) ## Summary of the Pull Request **If you're reading this PR and haven't signed off on #8135, go there first.** ![window-management-000](https://user-images.githubusercontent.com/18356694/103932910-25199380-50e8-11eb-97e3-594a31da62d2.gif) This provides the basic parts of the implementation of #4472. Namely: * We add support for the `--window,-w <window-id>` argument to `wt.exe`, to allow a commandline to be given to another window. * If `window-id` is `0`, run the given commands in _the current window_. * If `window-id` is a negative number, run the commands in a _new_ Terminal window. * If `window-id` is the ID of an existing window, then run the commandline in that window. * If `window-id` is _not_ the ID of an existing window, create a new window. That window will be assigned the ID provided in the commandline. The provided subcommands will be run in that new window. * If `window-id` is omitted, then create a new window. ## References * Spec: #8135 * Megathread: #5000 * Project: projects/5 ## PR Checklist * [x] Closes #4472 * [x] I work here * [x] Tests added/passed * [ ] Requires documentation to be updated - **sure does** ## Detailed Description of the Pull Request / Additional comments Note that `wt -w 1 -d c:\foo cmd.exe` does work, by causing window 1 to change There are limitations, and there are plenty of things to work on in the future: * [ ] We don't support names for windows yet * [ ] We don't support window glomming by default, or a setting to configure what happens when `-w` is omitted. I thought it best to lay the groundwork first, then come back to that. * [ ] `-w 0` currently just uses the "last activated" window, not "the current". There's more follow-up work to try and smartly find the actual window we're being called from. * [ ] Basically anything else that's listed in projects/5. I'm cutting this PR where it currently is, because this is already a huge PR. I believe the remaining tasks will all be easier to land, once this is in. ## Validation Steps Performed I've been creating windows, and closing them, and running cmdlines for a while now. I'm gonna keep doing that while the PR is open, till no bugs remain. # TODOs * [x] There are a bunch of `GetID`, `GetPID` calls that aren't try/caught 😬 - [x] `Monarch.cpp` - [x] `Peasant.cpp` - [x] `WindowManager.cpp` - [x] `AppHost.cpp` * [x] If the monarch gets hung, then _you can't launch any Terminals_ 😨 We should handle this gracefully. - Proposed idea: give the Monarch some time to respond to a proposal for a commandline. If there's no response in that timeframe, this window is now a _hermit_, outside of society entirely. It can't be elected Monarch. It can't receive command lines. It has no ID. - Could we gracefully recover from such a state? maybe, probably not though. - Same deal if a peasant hangs, it could end up hanging the monarch, right? Like if you do `wt -w 2`, and `2` is hung, then does the monarch get hung waiting on the hung peasant? - After talking with @miniksa, **we're gonna punt this from the initial implementation**. If people legit hit this in the wild, we'll fix it then.
2021-02-10 12:28:09 +01:00
_root->ProcessStartupActions(actions, false, cwd);
}
// Return the result of parsing with commandline, though it may or may not be used.
return result;
}
// Method Description:
// - Parse the given commandline args in an attempt to find the specified
// window. The rest of the args are ignored for now (they'll be handled
// whenever the commandline gets to the window it was intended for).
// - Note that this function will only ever be called by the monarch. A
// return value of `0` in this case does not mean "run the commandline in
// _this_ process", rather it means "run the commandline in the current
// process", whoever that may be.
// Arguments:
// - args: an array of strings to process as a commandline. These args can contain spaces
// Return Value:
// - 0: We should handle the args "in the current window".
// - WindowingBehaviorUseNew: We should handle the args in a new window
// - WindowingBehaviorUseExisting: We should handle the args "in
// the current window ON THIS DESKTOP"
// - WindowingBehaviorUseAnyExisting: We should handle the args "in the current
// window ON ANY DESKTOP"
Add support for running a commandline in another WT window (#8898) ## Summary of the Pull Request **If you're reading this PR and haven't signed off on #8135, go there first.** ![window-management-000](https://user-images.githubusercontent.com/18356694/103932910-25199380-50e8-11eb-97e3-594a31da62d2.gif) This provides the basic parts of the implementation of #4472. Namely: * We add support for the `--window,-w <window-id>` argument to `wt.exe`, to allow a commandline to be given to another window. * If `window-id` is `0`, run the given commands in _the current window_. * If `window-id` is a negative number, run the commands in a _new_ Terminal window. * If `window-id` is the ID of an existing window, then run the commandline in that window. * If `window-id` is _not_ the ID of an existing window, create a new window. That window will be assigned the ID provided in the commandline. The provided subcommands will be run in that new window. * If `window-id` is omitted, then create a new window. ## References * Spec: #8135 * Megathread: #5000 * Project: projects/5 ## PR Checklist * [x] Closes #4472 * [x] I work here * [x] Tests added/passed * [ ] Requires documentation to be updated - **sure does** ## Detailed Description of the Pull Request / Additional comments Note that `wt -w 1 -d c:\foo cmd.exe` does work, by causing window 1 to change There are limitations, and there are plenty of things to work on in the future: * [ ] We don't support names for windows yet * [ ] We don't support window glomming by default, or a setting to configure what happens when `-w` is omitted. I thought it best to lay the groundwork first, then come back to that. * [ ] `-w 0` currently just uses the "last activated" window, not "the current". There's more follow-up work to try and smartly find the actual window we're being called from. * [ ] Basically anything else that's listed in projects/5. I'm cutting this PR where it currently is, because this is already a huge PR. I believe the remaining tasks will all be easier to land, once this is in. ## Validation Steps Performed I've been creating windows, and closing them, and running cmdlines for a while now. I'm gonna keep doing that while the PR is open, till no bugs remain. # TODOs * [x] There are a bunch of `GetID`, `GetPID` calls that aren't try/caught 😬 - [x] `Monarch.cpp` - [x] `Peasant.cpp` - [x] `WindowManager.cpp` - [x] `AppHost.cpp` * [x] If the monarch gets hung, then _you can't launch any Terminals_ 😨 We should handle this gracefully. - Proposed idea: give the Monarch some time to respond to a proposal for a commandline. If there's no response in that timeframe, this window is now a _hermit_, outside of society entirely. It can't be elected Monarch. It can't receive command lines. It has no ID. - Could we gracefully recover from such a state? maybe, probably not though. - Same deal if a peasant hangs, it could end up hanging the monarch, right? Like if you do `wt -w 2`, and `2` is hung, then does the monarch get hung waiting on the hung peasant? - After talking with @miniksa, **we're gonna punt this from the initial implementation**. If people legit hit this in the wild, we'll fix it then.
2021-02-10 12:28:09 +01:00
// - anything else: We should handle the commandline in the window with the given ID.
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
TerminalApp::FindTargetWindowResult AppLogic::FindTargetWindow(array_view<const winrt::hstring> args)
{
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
if (!_loadedInitialSettings)
{
// Load settings if we haven't already
LoadSettings();
}
return AppLogic::_doFindTargetWindow(args, _settings.GlobalSettings().WindowingBehavior());
}
// The main body of this function is a static helper, to facilitate unit-testing
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
TerminalApp::FindTargetWindowResult AppLogic::_doFindTargetWindow(array_view<const winrt::hstring> args,
const Microsoft::Terminal::Settings::Model::WindowingMode& windowingBehavior)
Add support for running a commandline in another WT window (#8898) ## Summary of the Pull Request **If you're reading this PR and haven't signed off on #8135, go there first.** ![window-management-000](https://user-images.githubusercontent.com/18356694/103932910-25199380-50e8-11eb-97e3-594a31da62d2.gif) This provides the basic parts of the implementation of #4472. Namely: * We add support for the `--window,-w <window-id>` argument to `wt.exe`, to allow a commandline to be given to another window. * If `window-id` is `0`, run the given commands in _the current window_. * If `window-id` is a negative number, run the commands in a _new_ Terminal window. * If `window-id` is the ID of an existing window, then run the commandline in that window. * If `window-id` is _not_ the ID of an existing window, create a new window. That window will be assigned the ID provided in the commandline. The provided subcommands will be run in that new window. * If `window-id` is omitted, then create a new window. ## References * Spec: #8135 * Megathread: #5000 * Project: projects/5 ## PR Checklist * [x] Closes #4472 * [x] I work here * [x] Tests added/passed * [ ] Requires documentation to be updated - **sure does** ## Detailed Description of the Pull Request / Additional comments Note that `wt -w 1 -d c:\foo cmd.exe` does work, by causing window 1 to change There are limitations, and there are plenty of things to work on in the future: * [ ] We don't support names for windows yet * [ ] We don't support window glomming by default, or a setting to configure what happens when `-w` is omitted. I thought it best to lay the groundwork first, then come back to that. * [ ] `-w 0` currently just uses the "last activated" window, not "the current". There's more follow-up work to try and smartly find the actual window we're being called from. * [ ] Basically anything else that's listed in projects/5. I'm cutting this PR where it currently is, because this is already a huge PR. I believe the remaining tasks will all be easier to land, once this is in. ## Validation Steps Performed I've been creating windows, and closing them, and running cmdlines for a while now. I'm gonna keep doing that while the PR is open, till no bugs remain. # TODOs * [x] There are a bunch of `GetID`, `GetPID` calls that aren't try/caught 😬 - [x] `Monarch.cpp` - [x] `Peasant.cpp` - [x] `WindowManager.cpp` - [x] `AppHost.cpp` * [x] If the monarch gets hung, then _you can't launch any Terminals_ 😨 We should handle this gracefully. - Proposed idea: give the Monarch some time to respond to a proposal for a commandline. If there's no response in that timeframe, this window is now a _hermit_, outside of society entirely. It can't be elected Monarch. It can't receive command lines. It has no ID. - Could we gracefully recover from such a state? maybe, probably not though. - Same deal if a peasant hangs, it could end up hanging the monarch, right? Like if you do `wt -w 2`, and `2` is hung, then does the monarch get hung waiting on the hung peasant? - After talking with @miniksa, **we're gonna punt this from the initial implementation**. If people legit hit this in the wild, we'll fix it then.
2021-02-10 12:28:09 +01:00
{
::TerminalApp::AppCommandlineArgs appArgs;
const auto result = appArgs.ParseArgs(args);
if (result == 0)
{
if (!appArgs.GetExitMessage().empty())
{
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
return winrt::make<FindTargetWindowResult>(WindowingBehaviorUseNew);
}
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
const std::string parsedTarget{ appArgs.GetTargetWindow() };
// If the user did not provide any value on the commandline,
// then lookup our windowing behavior to determine what to do
// now.
if (parsedTarget.empty())
{
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
int32_t windowId = WindowingBehaviorUseNew;
switch (windowingBehavior)
{
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
case WindowingMode::UseNew:
windowId = WindowingBehaviorUseNew;
break;
case WindowingMode::UseExisting:
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
windowId = WindowingBehaviorUseExisting;
break;
case WindowingMode::UseAnyExisting:
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
windowId = WindowingBehaviorUseAnyExisting;
break;
}
return winrt::make<FindTargetWindowResult>(windowId);
}
// Here, the user _has_ provided a window-id on the commandline.
// What is it? Let's start by checking if it's an int, for the
// window's ID:
try
{
int32_t windowId = ::base::saturated_cast<int32_t>(std::stoi(parsedTarget));
// If the user provides _any_ negative number, then treat it as
// -1, for "use a new window".
if (windowId < 0)
{
windowId = -1;
}
// Hooray! This is a valid integer. The set of possible values
// here is {-1, 0, +}. Let's return that window ID.
return winrt::make<FindTargetWindowResult>(windowId);
}
catch (...)
{
// Value was not a valid int. It could be any other string to
// use as a title though!
//
// First, check the reserved keywords:
if (parsedTarget == "new")
{
return winrt::make<FindTargetWindowResult>(WindowingBehaviorUseNew);
}
else if (parsedTarget == "last")
{
return winrt::make<FindTargetWindowResult>(WindowingBehaviorUseExisting);
}
else
{
// The string they provided wasn't an int, it wasn't "new"
// or "last", so whatever it is, that's the name they get.
winrt::hstring winrtName{ til::u8u16(parsedTarget) };
return winrt::make<FindTargetWindowResult>(WindowingBehaviorUseName, winrtName);
}
}
Add `Microsoft.Terminal.Remoting.dll` (#8607) Adds a `Microsoft.Terminal.Remoting.dll` to our solution. This DLL will be responsible for all the Monarch/Peasant work that's been described in #7240 & #8135. This PR does _not_ implement the Monarch/Peasant architecture in any significant way. The goal of this PR is to just to establish the project layout, and the most basic connections. This should make reviewing the actual meat of the implementation (in a later PR) easier. It will also give us the opportunity to include some of the basic weird things we're doing (with `CoRegisterClass`) in the Terminal _now_, and get them selfhosted, before building on them too much. This PR does have windows registering the `Monarch` class with COM. When windows are created, they'll as the Monarch if they should create a new window or not. In this PR, the Monarch will always reply "yes, please make a new window". Similar to other projects in our solution, we're adding 3 projects here: * `Microsoft.Terminal.Remoting.lib`: the actual implementation, as a static lib. * `Microsoft.Terminal.Remoting.dll`: The implementation linked as a DLL, for use in `WindowsTerminal.exe`. * `Remoting.UnitTests.dll`: A unit test dll that links with the static lib. There are plenty of TODOs scattered about the code. Clearly, most of this isn't implemented yet, but I do have more WIP branches. I'm using [`projects/5`](https://github.com/microsoft/terminal/projects/5) as my notation for TODOs that are too small for an issue, but are part of the whole Process Model 2.0 work. ## References * #5000 - this is the process model megathread * #7240 - The process model 2.0 spec. * #8135 - the window management spec. (please review me, I have 0/3 signoffs even after the discussion we had 😢) * #8171 - the Monarch/peasant sample. (please review me, I have 1/2) ## PR Checklist * [x] Closes nothing, this is just infrastructure * [x] I work here * [x] Tests added/passed * [n/a] Requires documentation to be updated
2021-01-07 23:59:37 +01:00
}
Add support for running a commandline in another WT window (#8898) ## Summary of the Pull Request **If you're reading this PR and haven't signed off on #8135, go there first.** ![window-management-000](https://user-images.githubusercontent.com/18356694/103932910-25199380-50e8-11eb-97e3-594a31da62d2.gif) This provides the basic parts of the implementation of #4472. Namely: * We add support for the `--window,-w <window-id>` argument to `wt.exe`, to allow a commandline to be given to another window. * If `window-id` is `0`, run the given commands in _the current window_. * If `window-id` is a negative number, run the commands in a _new_ Terminal window. * If `window-id` is the ID of an existing window, then run the commandline in that window. * If `window-id` is _not_ the ID of an existing window, create a new window. That window will be assigned the ID provided in the commandline. The provided subcommands will be run in that new window. * If `window-id` is omitted, then create a new window. ## References * Spec: #8135 * Megathread: #5000 * Project: projects/5 ## PR Checklist * [x] Closes #4472 * [x] I work here * [x] Tests added/passed * [ ] Requires documentation to be updated - **sure does** ## Detailed Description of the Pull Request / Additional comments Note that `wt -w 1 -d c:\foo cmd.exe` does work, by causing window 1 to change There are limitations, and there are plenty of things to work on in the future: * [ ] We don't support names for windows yet * [ ] We don't support window glomming by default, or a setting to configure what happens when `-w` is omitted. I thought it best to lay the groundwork first, then come back to that. * [ ] `-w 0` currently just uses the "last activated" window, not "the current". There's more follow-up work to try and smartly find the actual window we're being called from. * [ ] Basically anything else that's listed in projects/5. I'm cutting this PR where it currently is, because this is already a huge PR. I believe the remaining tasks will all be easier to land, once this is in. ## Validation Steps Performed I've been creating windows, and closing them, and running cmdlines for a while now. I'm gonna keep doing that while the PR is open, till no bugs remain. # TODOs * [x] There are a bunch of `GetID`, `GetPID` calls that aren't try/caught 😬 - [x] `Monarch.cpp` - [x] `Peasant.cpp` - [x] `WindowManager.cpp` - [x] `AppHost.cpp` * [x] If the monarch gets hung, then _you can't launch any Terminals_ 😨 We should handle this gracefully. - Proposed idea: give the Monarch some time to respond to a proposal for a commandline. If there's no response in that timeframe, this window is now a _hermit_, outside of society entirely. It can't be elected Monarch. It can't receive command lines. It has no ID. - Could we gracefully recover from such a state? maybe, probably not though. - Same deal if a peasant hangs, it could end up hanging the monarch, right? Like if you do `wt -w 2`, and `2` is hung, then does the monarch get hung waiting on the hung peasant? - After talking with @miniksa, **we're gonna punt this from the initial implementation**. If people legit hit this in the wild, we'll fix it then.
2021-02-10 12:28:09 +01:00
// Any unsuccessful parse will be a new window. That new window will try
// to handle the commandline itself, and find that the commandline
// failed to parse. When that happens, the new window will display the
// message box.
//
// This will also work for the case where the user specifies an invalid
// commandline in conjunction with `-w 0`. This function will determine
// that the commandline has a parse error, and indicate that we should
// create a new window. Then, in that new window, we'll try to set the
// StartupActions, which will again fail, returning the correct error
// message.
Add support for naming windows with the `-w` parameter (#9300) This finishes the implementation of `--window` to also accept a string as the "name" of the window. So you can say ```sh wt -w foo new-tab wt -w foo split-pane ``` and have both those commands execute in the same window, the one named "foo". This is just slightly more ergonomic than manually using the IDs of windows. In the future, I'll be working on renaming windows, and displaying these names. > #### `--window,-w <window-id>` > Run these commands in the given Windows Terminal session. This enables opening > new tabs, splits, etc. in already running Windows Terminal windows. > * If `window-id` is `0`, run the given commands in _the current window_. > * If `window-id` is a negative number, or the reserved name `new`, run the > commands in a _new_ Terminal window. > * If `window-id` is the ID or name of an existing window, then run the > commandline in that window. > * If `window-id` is _not_ the ID or name of an existing window, create a new > window. That window will be assigned the ID or name provided in the > commandline. The provided subcommands will be run in that new window. > * If `window-id` is omitted, then obey the value of `windowingBehavior` when > determining which window to run the command in. Before this PR, I think we didn't actually properly support assigning the id with `wt -w 12345`. If `12345` didn't exist, it would make a new window, but just assign it the next id, not assign it 12345. ## References * #4472, #8135 * https://github.com/microsoft/terminal/projects/5 ## Validation Steps Performed Ran tests Messed with naming windows, working as expected. Closes https://github.com/microsoft/terminal/projects/5#card-51431478
2021-03-17 20:28:01 +01:00
return winrt::make<FindTargetWindowResult>(WindowingBehaviorUseNew);
Add `Microsoft.Terminal.Remoting.dll` (#8607) Adds a `Microsoft.Terminal.Remoting.dll` to our solution. This DLL will be responsible for all the Monarch/Peasant work that's been described in #7240 & #8135. This PR does _not_ implement the Monarch/Peasant architecture in any significant way. The goal of this PR is to just to establish the project layout, and the most basic connections. This should make reviewing the actual meat of the implementation (in a later PR) easier. It will also give us the opportunity to include some of the basic weird things we're doing (with `CoRegisterClass`) in the Terminal _now_, and get them selfhosted, before building on them too much. This PR does have windows registering the `Monarch` class with COM. When windows are created, they'll as the Monarch if they should create a new window or not. In this PR, the Monarch will always reply "yes, please make a new window". Similar to other projects in our solution, we're adding 3 projects here: * `Microsoft.Terminal.Remoting.lib`: the actual implementation, as a static lib. * `Microsoft.Terminal.Remoting.dll`: The implementation linked as a DLL, for use in `WindowsTerminal.exe`. * `Remoting.UnitTests.dll`: A unit test dll that links with the static lib. There are plenty of TODOs scattered about the code. Clearly, most of this isn't implemented yet, but I do have more WIP branches. I'm using [`projects/5`](https://github.com/microsoft/terminal/projects/5) as my notation for TODOs that are too small for an issue, but are part of the whole Process Model 2.0 work. ## References * #5000 - this is the process model megathread * #7240 - The process model 2.0 spec. * #8135 - the window management spec. (please review me, I have 0/3 signoffs even after the discussion we had 😢) * #8171 - the Monarch/peasant sample. (please review me, I have 1/2) ## PR Checklist * [x] Closes nothing, this is just infrastructure * [x] I work here * [x] Tests added/passed * [n/a] Requires documentation to be updated
2021-01-07 23:59:37 +01:00
}
// Method Description:
// - If there were any errors parsing the commandline that was used to
// initialize the terminal, this will return a string containing that
// message. If there were no errors, this message will be blank.
// - If the user requested help on any command (using --help), this will
// contain the help message.
// - If the user requested the version number (using --version), this will
// contain the version string.
// Arguments:
// - <none>
// Return Value:
// - the help text or error message for the provided commandline, if one
// exists, otherwise the empty string.
winrt::hstring AppLogic::ParseCommandlineMessage()
{
return winrt::to_hstring(_appArgs.GetExitMessage());
}
// Method Description:
// - Returns true if we should exit the application before even starting the
// window. We might want to do this if we're displaying an error message or
// the version string, or if we want to open the settings file.
// Arguments:
// - <none>
// Return Value:
// - true iff we should exit the application before even starting the window
bool AppLogic::ShouldExitEarly()
{
return _appArgs.ShouldExitEarly();
}
bool AppLogic::FocusMode() const
{
return _root ? _root->FocusMode() : false;
}
bool AppLogic::Fullscreen() const
{
return _root ? _root->Fullscreen() : false;
}
bool AppLogic::AlwaysOnTop() const
{
return _root ? _root->AlwaysOnTop() : false;
}
Introduce ActionMap to Terminal Settings Model (#9621) This entirely removes `KeyMapping` from the settings model, and builds on the work done in #9543 to consolidate all actions (key bindings and commands) into a unified data structure (`ActionMap`). ## References #9428 - Spec #6900 - Actions page Closes #7441 ## Detailed Description of the Pull Request / Additional comments The important thing here is to remember that we're shifting our philosophy of how to interact/represent actions. Prior to this, the actions arrays in the JSON would be deserialized twice: once for key bindings, and again for commands. By thinking of every entry in the relevant JSON as a `Command`, we can remove a lot of the context switching between working with a key binding vs a command palette item. #9543 allows us to make that shift. Given the work in that PR, we can now deserialize all of the relevant information from each JSON action item. This allows us to simplify `ActionMap::FromJson` to simply iterate over each JSON action item, deserialize it, and add it to our `ActionMap`. Internally, our `ActionMap` operates as discussed in #9428 by maintaining a `_KeyMap` that points to an action ID, and using that action ID to retrieve the `Command` from the `_ActionMap`. Adding actions to the `ActionMap` automatically accounts for name/key-chord collisions. A `NameMap` can be constructed when requested; this is for the Command Palette. Querying the `ActionMap` is fairly straightforward. Helper functions were needed to be able to distinguish an explicit unbinding vs the command not being found in the current layer. Internally, we store explicitly unbound names/key-chords as `ShortcutAction::Invalid` commands. However, we return `nullptr` when a query points to an unbound command. This is done to hide this complexity away from any caller. The command palette still needs special handling for nested and iterable commands. Thankfully, the expansion of iterable commands is performed on an `IMapView`, so we can just expose `NameMap` as a consolidation of `ActionMap`'s `NameMap` with its parents. The same can be said for exposing key chords in nested commands. ## Validation Steps Performed All local tests pass.
2021-05-05 06:50:13 +02:00
Windows::Foundation::Collections::IMapView<Microsoft::Terminal::Control::KeyChord, Microsoft::Terminal::Settings::Model::Command> AppLogic::GlobalHotkeys()
2021-04-29 00:13:28 +02:00
{
Introduce ActionMap to Terminal Settings Model (#9621) This entirely removes `KeyMapping` from the settings model, and builds on the work done in #9543 to consolidate all actions (key bindings and commands) into a unified data structure (`ActionMap`). ## References #9428 - Spec #6900 - Actions page Closes #7441 ## Detailed Description of the Pull Request / Additional comments The important thing here is to remember that we're shifting our philosophy of how to interact/represent actions. Prior to this, the actions arrays in the JSON would be deserialized twice: once for key bindings, and again for commands. By thinking of every entry in the relevant JSON as a `Command`, we can remove a lot of the context switching between working with a key binding vs a command palette item. #9543 allows us to make that shift. Given the work in that PR, we can now deserialize all of the relevant information from each JSON action item. This allows us to simplify `ActionMap::FromJson` to simply iterate over each JSON action item, deserialize it, and add it to our `ActionMap`. Internally, our `ActionMap` operates as discussed in #9428 by maintaining a `_KeyMap` that points to an action ID, and using that action ID to retrieve the `Command` from the `_ActionMap`. Adding actions to the `ActionMap` automatically accounts for name/key-chord collisions. A `NameMap` can be constructed when requested; this is for the Command Palette. Querying the `ActionMap` is fairly straightforward. Helper functions were needed to be able to distinguish an explicit unbinding vs the command not being found in the current layer. Internally, we store explicitly unbound names/key-chords as `ShortcutAction::Invalid` commands. However, we return `nullptr` when a query points to an unbound command. This is done to hide this complexity away from any caller. The command palette still needs special handling for nested and iterable commands. Thankfully, the expansion of iterable commands is performed on an `IMapView`, so we can just expose `NameMap` as a consolidation of `ActionMap`'s `NameMap` with its parents. The same can be said for exposing key chords in nested commands. ## Validation Steps Performed All local tests pass.
2021-05-05 06:50:13 +02:00
return _settings.GlobalSettings().ActionMap().GlobalHotkeys();
2021-04-29 00:13:28 +02:00
}
Add an action for identifying windows (#9523) ## Summary of the Pull Request This is a follow up to #9300. Now that we have names on our windows, it would be nice to see who is named what. So this adds two actions: * `identifyWindow`: This action will pop up a little toast (#8592) displaying the name and ID of the window, and is bound by default. ![identify-window-toast-000](https://user-images.githubusercontent.com/18356694/111529085-bf710580-872f-11eb-8880-b0b617596cfc.gif) * `identifyWindows`: This action will request that ALL windows pop up that toast. This is meant to feel like the "Identify" button on the Windows display settings. However, sometimes, it's wonky. ![teaching-tip-dismiss-001](https://user-images.githubusercontent.com/18356694/111529292-fe06c000-872f-11eb-8d4a-5688e4ce1175.gif) That's being tracked upstream on https://github.com/microsoft/microsoft-ui-xaml/issues/4382 Because it's so wonky, we won't bind that by default. Maybe if we get that fixed, then we'll change the default binding from `identifyWindow` to `identifyWindows` ## References ## PR Checklist * [x] Closes https://github.com/microsoft/terminal/projects/5#card-51431492 * [x] I work here * [x] Tests added/passed * [ ] Requires documentation to be updated ## Detailed Description of the Pull Request / Additional comments You may note that there are some macros to make interacting with lots and lots of actions easier. There's a lot of boilerplate whenever you need to make a new action, so I thought: "Can we make that easier?" Turns out you can make it a _LOT_ easier, but that work is still behind another PR after this one. Get excited
2021-03-30 18:08:03 +02:00
void AppLogic::IdentifyWindow()
{
if (_root)
{
_root->IdentifyWindow();
}
}
winrt::hstring AppLogic::WindowName()
{
return _root ? _root->WindowName() : L"";
}
void AppLogic::WindowName(const winrt::hstring& name)
{
if (_root)
{
_root->WindowName(name);
}
}
uint64_t AppLogic::WindowId()
{
return _root ? _root->WindowId() : 0;
}
void AppLogic::WindowId(const uint64_t& id)
{
if (_root)
{
_root->WindowId(id);
}
}
Add support for renaming windows (#9662) ## Summary of the Pull Request This PR adds support for renaming windows. ![window-renaming-000](https://user-images.githubusercontent.com/18356694/113034344-9a30be00-9157-11eb-9443-975f3c294f56.gif) ![window-renaming-001](https://user-images.githubusercontent.com/18356694/113034452-b5033280-9157-11eb-9e35-e5ac80fef0bc.gif) It does so through two new actions: * `renameWindow` takes a `name` parameter, and attempts to set the window's name to the provided name. This is useful if you always want to hit <kbd>F3</kbd> and rename a window to "foo" (READ: probably not that useful) * `openWindowRenamer` is more interesting: it opens a `TeachingTip` with a `TextBox`. When the user hits Ok, it'll request a rename for the provided value. This lets the user pick a new name for the window at runtime. In both cases, if there's already a window with that name, then the monarch will reject the rename, and pop a `Toast` in the window informing the user that the rename failed. Nifty! ## References * Builds on the toasts from #9523 * #5000 - process model megathread ## PR Checklist * [x] Closes https://github.com/microsoft/terminal/projects/5#card-50771747 * [x] I work here * [x] Tests addded (and pass with the help of #9660) * [ ] Requires documentation to be updated ## Detailed Description of the Pull Request / Additional comments I'm sending this PR while finishing up the tests. I figured I'll have time to sneak them in before I get the necessary reviews. > PAIN: We can't immediately focus the textbox in the TeachingTip. It's > not technically focusable until it is opened. However, it doesn't > provide an even tto tell us when it is opened. That's tracked in > microsoft/microsoft-ui-xaml#1607. So for now, the user _needs_ to > click on the text box manually. > We're also not using a ContentDialog for this, because in Xaml > Islands a text box in a ContentDialog won't recieve _any_ keypresses. > Fun! ## Validation Steps Performed I've been playing with ```json { "keys": "f1", "command": "identifyWindow" }, { "keys": "f2", "command": "identifyWindows" }, { "keys": "f3", "command": "openWindowRenamer" }, { "keys": "f4", "command": { "action": "renameWindow", "name": "foo" } }, { "keys": "f5", "command": { "action": "renameWindow", "name": "bar" } }, ``` and they seem to work as expected
2021-04-02 18:00:04 +02:00
void AppLogic::RenameFailed()
{
if (_root)
{
_root->RenameFailed();
}
}
Make the window name `_quake` special (#9785) ## Summary of the Pull Request This PR adds some special behavior to the window named "\_quake". * When creating the quake window, it ignores "initialRows" and "initialCols" and opens on the top half of the monitor. - It uses `initialPosition` to determine which monitor this is * It cannot be moved * It can only be vertically resized on the bottom border. * It's always in focus mode. - We should probably have an issue tracking "Allow showing tabs in focus mode"? Maybe? - This one element is maybe the one I'm least attached to When renaming a window to "\_quake", it adopts all those behaviors as well. It does not exit focus mode when leaving QM, nor does it resize back. That seemed unnecessary. ## References * As spec'ed in #9274 * See also #8888 ## PR Checklist * [x] In the pursuit of #653 * [x] I work here * [ ] Tests added/passed * [ ] Requires documentation to be updated, but I'm not gonna do any of that till quake mode is totally done. ## Detailed Description of the Pull Request / Additional comments Note that this doesn't do things like: * dropdown * global hotkey summon * summon to the current monitor * summon to the current desktop I'm doing #653 _very_ piecemeal, to try and make the PRs less egregious. ## Validation Steps Performed * validated that center on launch still works * validated that QM works on different monitors based on `initialPosition` * validated entering/exiting QM behaves as expected ## TODO! * [ ] When snapping the quake window between desktops with <kbd>win+shift+arrow</kbd>, the window doesn't horizontally re-size to the new monitor dimensions. It should.
2021-04-26 21:36:23 +02:00
bool AppLogic::IsQuakeWindow() const noexcept
{
return _root->IsQuakeWindow();
}
}