tl;dr: ~Apphost() may pump the message loop.
That's no bueno. See comments in the diff.
Additionally, this PR enables `_assertIsMainThread` in
release to trace down mysterious crashes in those builds.
Right now, we do not use a sufficiently unique name to disambiguate
Terminal instances running on the same desktop.
Mutexes (mutants) are named objects that live in the user's session,
under `Sessions\1\BaseNamedObjects` (for the local desktop session).
When multiple users are logged into the same session--such as with "Run
as different user"--they share a local BaseNamedObjects namespace. Ugh.
We cannot use [`CreatePrivateNamespace`] as it requires a boundary
descriptor, and the only boundary descriptors supported by the current
API are based on package identity. I also fear that
`CreatePrivateNamespace` is subject to a race condition with
`OpenPrivateNamespace`; Create will not Open an existing one, so we
would need to back off and retry either opening or creating. Yuck.
After this commit, we will hash the user's SID into the name of both the
window class and the mutant, right after the path hash (if running
unpackaged).
Closes#18704
[`CreatePrivateNamespace`]:
https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createprivatenamespacea
The crash occurs because WinRT `abort()`s when it encounters
a `std::wstring_view` without null-terminator.
Closes#19093
## Validation Steps Performed
* Set `wtd` as the default terminal
* Launch `cmd`
* Launch `wtd`
* 2 windows ✅
This changes the ConPTY handoff COM server from `REGCLS_SINGLEUSE`
to `REGCLS_MULTIPLEUSE`. The former causes a race condition, because
handoff runs concurrently with the creation of WinUI windows.
This can then result in the a window getting the wrong handoff.
It then moves the "root" of ConPTY handoff from `TerminalPage`
(WindowEmperor -> AppHost -> TerminalWindow -> TerminalPage)
into `WindowEmperor` (WindowEmperor).
Closes#19049
## Validation Steps Performed
* Launching cmd from the Start Menu shows a "Command Prompt" tab ✅
* Win+R -> `cmd` creates windows in the foreground ✅
* Win+R -> `cmd /c start /max cmd` creates a fullscreen tab ✅
* This even works for multiple windows, unlike with Canary ✅
* Win+R -> `cmd /c start /min cmd` does not work ❌
* It also doesn't work in Canary, so it's not a bug in this PR ✅
## Summary of the Pull Request
Adds branding and distribution metadata to the following telemetry
events:
- ActionDispatched (branding only)
- JsonSettingsChanged
- UISettingsChanged
- SessionBecameInteractive
Also removes the settings logger output from the debugger and some
leftover debugging functions.
Adds a label to the XSettingsChanged settings value to make it easier to
read on the backend.
Once an application has returned from handling `WM_ENDSESSION`
the OS may kill the app at any point. This means we must
persist our state while inside the message handler.
Closes#17179
## Validation Steps Performed
Honestly, none. It's a race condition in the first place.
If `persistedWindowLayout` is enabled, we now persist the window layout
every few minutes (excluding the text buffer).
This was done by adding a `SafeDispatcherTimer` to the `WindowEmperor`
that calls `PersistState()` every 5 minutes. For `BuildStartupKind`, I
split up `Persist` into `PersistAll` and `PersistLayout`. This way, we
go through all the same code flow that `Persist` had except for
specifically serializing the buffer.
## Validation Steps Performed
✅ (with the timer set to 3 seconds) create a window layout and ensure
the layout is restored after forcefully stopping Terminal (aka
simulating a "crash")
Closes#18838
I finally realized the missing piece.
We need to clear the state array unconditionally,
as otherwise it won't get cleared. Duh.
Closes#18584
## Validation Steps Performed
* Craft a state.json with a layout
* Launch Terminal while the feature is disabled
* state.json is cleaned up on exit ✅
The logic didn't work when persistence was enabled and you had 2 windows
and closed the 2nd one, or when dragging the last tab out of the only
window.
## Validation Steps Performed
* 2 windows, close the 2nd one, app doesn't exit ✅
* 1 window, 1 tab, drag the tab out of the window, app doesn't exit ✅
This fixes the bit check for key down and adds a few comments.
Closes#18331
## Validation Steps Performed
Printing the resulting INPUT_RECORDs shows both key down and up events
when pressing F7. Alt-Space now also works again.
The CoreWindow approach to implementing this has proven itself to be bug
prone. This PR switches to using the much better Win32 ShowCursor API,
which uses a reference count. This prevents the exact sort of race
condition we have where we we disable the cursor in our code and the
WinUI code then sets it to a different cursor internally which gets the
system out of sync. There's no WinUI API to just hide the cursor and if
it did, it would probably be a Boolean which would result in the same
issue.
Closes#18400
## Validation Steps Performed
It's difficult to assert the correctness of this approach, outside of
just trying it out (which I did and it works). The good news is that
this uses a static bool to ensure we only hide it exactly once and show
it exactly once and we do the latter on every WM_ACTIVATE message which
should hopefully restore the cursor when tabbing out and back in at
least.
Fixes
* Cursor vanishing, because
```cpp
CoreWindow::GetForCurrentThread().PointerCursor()
```
returned a non-null, but still invisible cursor.
* Alt/F7 not dispatching to newly created windows, because the
`WM_ACTIVATE` message now arrives before the `AppHost` is initialized.
This caused the messages to be delivered to old windows.
* Windows Terminal blocking expedited shutdown,
because we return `FALSE` on non-`ENDSESSION_CLOSEAPP` messages.
Closes#18331Closes#18335
## Validation Steps Performed
* Cursor still doesn't really vanish for me in the first place ✅
* Alt/F7 work in new windows without triggering old ones ✅
Forgetti di spaghetti in #18215.
Closes#18324
## Validation Steps Performed
* Launch through the start menu
* Explicitly minimize
* Then...
* Launch through the start menu again ✅
* Launch via wtd.exe in Win+R ✅
* Launch via wtd.exe in another Terminal ✅
* Launch via handoff ✅
As before, a minor refactor:
* I started off by removing the Monarch/Peasant with the goal of moving
it into and deduplicating its functionality with `WindowEmperor`.
* Since I needed a replacement for the Monarch (= ensures that there's
a single instance), I wrote single-instance code with a NT mutex
and by yeeting data across processes with `WM_COPYDATA`.
* This resulted in severe threading issues, because it now started up
way faster. The more I tried to solve them the deeper I had to dig,
because you can't just put a mutex around `CascadiaSettings`.
I then tried to seeif WinUI can run multiple windows on a single
thread and, as it turns out, it can.
So, I removed the multi- from the window threading.
* At this point I had dig about 1 mile deep and brought no ladder.
So, to finish it up, I had to clean up the entire eventing system
around `WindowEmperor`, cleaned up all the coroutines,
and cleaned up all the callbacks.
Closes#16183Closes#16221Closes#16487Closes#16532Closes#16733Closes#16755Closes#17015Closes#17360Closes#17420Closes#17457Closes#17799Closes#17976Closes#18057Closes#18084Closes#18169Closes#18176Closes#18191
## Validation Steps Performed
* It does not crash ✅
* New/close tab ✅
* New/close window ✅
* Move tabs between windows ✅
* Split tab into new window ✅
* Persist windows on exit / restore startup ✅
This PR clones `winrt::fire_and_forget` and replaces the uncaught
exception handler with one that logs instead of terminating.
My hope is that this removes one source of random crashes.
## Validation Steps Performed
I added a `THROW_HR` to `TermControl::UpdateControlSettings`
before and after the suspension point and ensured the application
won't crash anymore.
Between fmt 7.1.3 and 11.0.2 a lot has happened. `wchar_t` support is
now more limited and implicit conversions don't work anymore.
Furthermore, even the non-`FMT_COMPILE` API is now compile-time checked
and so it fails to work in our UI code which passes `hstring` format
strings which aren't implicitly convertible to the expected type.
`fmt::runtime` was introduced for this but it also fails to work for
`hstring` parameters. To solve this, a new `RS_fmt` macro was added
to abstract the added `std::wstring_view` casting away.
Finally, some additional changes to reduce `stringstream` usage
have been made, whenever `format_to`, etc., is available.
This mostly affects `ActionArgs.cpp`.
Closes#16000
## Validation Steps Performed
* Compiles ✅
* Settings page opens ✅
This fixes 2 bugs:
* `PersistState` being called when the window is closed
(as opposed to closing the tab). The settings check was missing.
* Session cleanup running depending on whether the feature is
currently enabled as opposed to whether it was enabled on launch.
Closes#17206Closes#17207
## Validation Steps Performed
* Create a bunch of leftover buffer_*.txt files by running
the current Dev version off of main
* Build this branch, then open and close a window
* All buffer_*.txt are gone and state.json is cleaned up ✅
This changes `NewTabArgs`, `SplitPaneArgs`, and `NewWindowArgs` to
accept a `INewContentArgs`, rather than just a `NewTerminalArgs`. This
allows a couple things:
* Users can open arbitrary types of panes with the existing `splitPane`,
`newWindow` actions, just by passing `"type": "scartchpad"` (for
example). This is a lot more flexible than re-defining different
`"openScratchpad"`, `"openTasksPane"`, etc, etc actions for every kind
of pane.
* This allows us to use the existing machinery of session restore to
also restore non-terminal panes.
The `type` property was added to `newTab`, `splitPane`, `newWindow`.
When omitted, we still just treat the json as a blob of NewTerminalArgs.
There's not actually any other kinds of `INewContentArgs` in this PR
(other than the placeholder `GenericContentArgs`). In
[`dev/migrie/fhl/md-pane`](https://github.com/microsoft/terminal/compare/dev/migrie/f/tasks-pane...dev/migrie/fhl/md-pane),
I have a type of pane that would LOVE to add some args here. So that's
forward-thinking.
There's really just two stealth types of pane for now: `settings`, and
`scratchpad`. Those I DON'T have as constants or anything in this PR.
They probably should be? Though, I suspect around the time of the tasks
& MD panes, I'll come up with whatever structure I actually want them to
take.
### future considerations here
* In the future, this should allow extensions to say "I know how to host
`foo` content", for 3p content.
* The `wt` CLI args were not yet updated to also accept `--type` yet.
There's no reason we couldn't easily do that.
* I considered adding `ICanHasCommandline` to allow arbitrary content to
generate a `wt` commandline-serializable string. Punted on that for now.
## other PRs
* #16170
* #16171
* #16172
* #16895
* #16914 <-- you are here
Closes#17014
This changeset allows Windows Terminal to dump its buffer contents as
UTF-16LE VT text onto disk and restore it later. This functionality is
enabled whenever `persistedWindowLayout` is being used.
Closes#961Closes#16741
## Validation Steps Performed
* Open multiple windows with multiple tabs and restart the app
Everything's restored ✅
* Reopen a tab with output from `RenderingTests.exe`
Everything's restored ✅
* Closing tabs and windows with Ctrl+W deletes their buffer dumps ✅
* Closing tabs doesn't create buffer dumps ✅
* `[[nodiscard]]` and `[[maybe_unused]]` must come before `virtual` and
`static` qualifiers
* MSVC and Clang disagree on how `gsl::suppress` should look;
fortunately, GSL provides a macro to paper over the difference
* Clang throws "pessimizing move" warnings when you `std::move` a
temporary, as it makes copy elision impossible
* The fuzzing logic was using an unspecified template expansion
`CFuzzLogic<>` before the type had been declared
* LibraryResources was emitting most of the `.util` section with
read-write permissions and some of it with read-only
Refs #15952
This contains all the parts of #16598 that aren't specific to session
restore, but are required for the code in #16598:
* Adds new GUID<>String functions that remove the `{}` brackets.
* Adds `SessionId` to the `ITerminalConnection` interface.
* Flush the `ApplicationState` before we terminate the process.
* Not monitoring `state.json` for changes is important as it prevents
disturbing the session state while session persistence is ongoing.
That's because when `ApplicationState` flushes to disk, the FS
monitor will be triggered and reload the `ApplicationState` again.
#16592 passes the return value of `GetEnvironmentStringsW` directly
to the `hstring` constructor even though the former returns a
double-null terminated string and the latter expects a regular one.
This PR fixes the issue by using a basic strlen() loop to compute
the length ourselves. It's still theoretically beneficial over
the previous code, but now it's rather bitter since the code isn't
particularly short anymore and so the biggest benefit is gone.
Closes#16623
## Validation Steps Performed
* Validated the `env` string in a debugger ✅
It's 1 character shorter than the old `til::env` string.
That's fine however, since any `HSTRING` is always null-terminated
anyways and so we get an extra null-terminator for free.
* `wt powershell` works ✅
Closes MSFT:46744208
BODGY: If the emperor is being dtor'd, it's because we've gone past the
end of main, and released the ref in main. Then we might run into an
edge case where main releases it's ref to the emperor, but one of the
window threads might be in the process of exiting, and still holding a
strong ref to the emperor. In that case, we can actually end up with
the _window thread_ being the last reference, and calling App::Close
on that thread will crash us with a E_WRONG_THREAD.
This fixes the issue by calling `TerminateProcess` explicitly.
How validated: The ES team manually ran the test pass this was
crashing in a hundred times to make sure this actually fixed it.
Co-authored-by: Leonard Hecker <lhecker@microsoft.com>
This simplifies the function in two ways:
* Passing `nCmdShow` from `wWinMain` alleviates the need to interpret
the return value of `GetStartupInfoW`.
* `til::env::from_current_environment()` calls `GetEnvironmentStringsW`
to get the environment variables, while `to_string()` turns it back.
Calling the latter directly alleviates the need for this round-trip.
This PR is a few things:
* part the first: Convert the `compatibility.reloadEnvironmentVariables`
setting to a per-profile one.
* The settings should migrate it from the user's old global place to the
new one.
* We also added it to "Profile>Advanced" while I was here.
* Adds a new pair of commandline flags to `new-tab` and `split-pane`:
`--inheritEnvironment` / `--reloadEnvironment`
* On `wt` launch, bundle the entire environment that `wt` was spawned
with, and put it into the `Remoting.CommandlineArgs`, and give them to
the monarch (and ultimately, down to `TerminalPage` with the
`AppCommandlineArgs`). DO THIS ALWAYS.
* As a part of this, we’ll default to _reloading_ if there’s no explicit
commandline set, and _inheriting_ if there is.
* For example, `wt -- cmd` would inherit, and `wt -p “Command Prompt”`
would reload.[^1]
* This is a little wacky, but we’re trying to separate out the
intentions here:
* `wt -- cmd` feels like “I want to run cmd.exe (in a terminal tab)”.
That feels like the user would _like_ environment variables from the
calling process. They’re doing something more manual, so they get more
refined control over it.
* `wt` (or `wt -p “Command Prompt”`) is more like, “I want to run the
Terminal (or, my Command Prompt profile) using whatever the Terminal
would normally do”. So that feels more like a situation where it should
just reload by default. (Of course, this will respect their settings
here)
## References and Relevant Issues
https://github.com/microsoft/terminal/issues/15496#issuecomment-1692450231
has more notes.
## Detailed Description of the Pull Request / Additional comments
This is so VERY much plumbing. I'll try to leave comments in the
interesting parts.
## PR Checklist
- [x] This is not _all_ of #15496. We're also going to do a `-E foo=bar`
arg on top of this.
- [x] Tests added/passed
- [x] Schema updated
[^1]: In both these cases, plus the `environment` setting, of course.
This is my proposed solution to #15384.
Basically, the issue is that we cannot ever close a
`DesktopWindowXamlSource` ("DWXS"). If we do, then any other thread that
tries to access XAML metadata will explode, which happens frequently. A
DWXS is inextricably linked to an HWND. That means we have to not only
reuse DWXS's, but the HWNDs themselves. XAML also isn't agile, so we've
got to keep the `thread` that the DWXS was started on alive as well.
To do this, we're going to introduce the ability to "refrigerate" and
"reheat" window threads.
* A window thread is "**hot**" if it's actively got a window, and is
pumping window messages, and generally, is a normal thing.
* When a window is closed, we need to "**refrigerate**" it's
`WindowThread` and `IslandWindow`. `WindowEmperor` will take care of
tracking the threads that are refrigerated.
* When a new window is requested, the Emperor first try to
"**reheat**"/"**microwave**" a refrigerated thread. When a thread gets
reheated, we'll create a new AppHost (and `TerminalWindow`/`Page`), and
we'll use the _existing_ `IslandWindow` for that instance.
<sub>The metaphor is obviously ridiculous, but _you get it_ so who
cares.</sub>
In this way, we'll keep all the windows we've ever created around in
memory, for later reuse. This means that the leak goes from (~12MB x
number of windows closed) to (~12MB x maximum number of simultaneously
open Terminal windows). It's still not good.
We won't do this on Windows 11, because the bug that is the fundamental
premise of this issue is fixed already in the OS.
I'm not 100% confident in this yet.
* [x] There's still a d3d leak of some sort on exit in debug builds.
(maybe #15306 related)
* havent seen this in a while. Must have been a issue in an earlier
revision.
* [x] I need to validate more on Windows 11
* [x] **BAD**: Closing the last tab on Windows 11 doesn't close the
window
* [x] **BAD**: Closing a window on Windows 11 doesn't close the window -
it just closes the one tab item and keeps on choochin'
* [x] **BAD**: Close last tab, open new one, attempt to close window -
ALL windows go \*poof\*. Cause of course. No break into post-mortem
either.
* [x] more comments
* [ ] maybe a diagram
* [x] Restoring windows is at the wrong place entirely? I once reopened
the Terminal with two persisted windows, and it created one at 0,0
* [x] Remaining code TODO!s: 0 (?)
* [ ] "warm-reloading" `useTabsInTitlebar` (change while terminal is
running after closing a window, open a new one) REALLY doesn't work.
Obviously restores the last kind of window. Yike.
is all about #15384closes#15410 along the way. Might fork that fix off.
This is a resurrection of #5629. As it so happens, this crash-on-exit
was _not_ specific to my laptop. It's a bug in the XAML platform
somewhere, only on Windows 10.
In #14843, we moved this leak into `becomeMonarch`. Turns out, we don't
just need this leak for the monarch process, but for all of them.
It's not a real "leak", because ultimately, our `App` lives for the
entire lifetime of our process, and then gets cleaned up when we do. But
`dtor`ing the `App` - that's apparently a no-no.
Was originally in #15424, but I'm pulling it out for a super-hotfix
release.
Closes#15410
MSFT:35761869 looks like it was closed as no repro many moons ago. This
should close out our hits there (firmly **40% of the crashes we've
gotten on 1.18**)
`WindowEmperor` would exit as soon as the last window would enter
`RundownForExit()`, which is too early and triggers leak checks.
This commit splits up the shutdown up into deregistering the window from
the list of windows and into actually decrementing the window count.
Closes#15306
## Validation Steps Performed
* D2D leak warnings seem to disappear ✅
Before process model v3, each Terminal window was running in its own process, each with its own CWD. This allowed `startingDirectory: .` to work relative to the terminal's own CWD. However, now all windows share the same process, so there can only be one CWD. That's not great - folks who right-click "open in terminal", then "Use parent process directory" are only ever going to be able to use the CWD of the _first_ terminal opened.
This PR remedies this issue, with a theory we had for another issue. Essentially, we'll give each Terminal window a "virtual" CWD. The Terminal isn't actually in that CWD, the terminal is in `system32`. This also will prevent the Terminal from locking the directory it was originally opened in.
* Closes#5506
* There wasn't a 1.18 issue for "Use parent process directory is broken" yet, presumably selfhosters aren't using that feature
* Related to #14957
Many more notes on this topic in https://github.com/microsoft/terminal/issues/4637#issuecomment-1531979200
> **Warning**
> ## Breaking change‼️
This will break a profile like
```json
{
"commandline": "media-test.exe",
"name": "Use CWD for media-test",
"startingDirectory": "."
},
```
if the user right-clicks "open in terminal", then attempts to open that profile. There's some theoretical work we could do in a follow up to fix this, but I'm inclined to say that relative paths for `commandline`s were already dangerous and should have been avoided.
We had a report in a mail thread that someone's Terminal windows were
getting created hidden, and never showing themselves.
As a theory, I'm guessing that dwFlags didn't say that we should
actually use `wShowWindow`. So, to be more correct, let's actually obey
that.
I'm gonna send this package to them to see if it fixes them.
Related to #14957.
Likely regressed in #13838.
See
https://github.com/microsoft/terminal/issues/14957#issuecomment-1520522722.
I think there's a race here that lets the WindowEmperor muck around with
the window after it's done, but before we remove it from our list of
threads.
This _should_ remove the thread from the list, _then_ null out the
AppHost, then flush the XAML queue, preventing the A/V.
Closes MSFT:43995981
Original description, pre-process model v3:
> This is just the `SHOWDEFAULT` bit from #12979. This seems to also
work now, but I'm PR'ing it separately so it can be a separate revert
from #13811, if it is problematic.
More accurately:
This PR enables terminal windows to use the `wShowCmd` from the
STARTUPINFO passed to `windowsterminal.exe` to set the initial
visibility of the window. We can't just use `SW_SHOWDEFAULT`, because
all the windows are running in the initial process! After the first
window, the subsequent ones would ignore any params passed to their
originating `windowsterminal.exe` processes. To mitigate, we pass that
`wShowCmd` info from the source process, to the actual running terminal
process. That accounts for most of the delta here.
Closes#9053
This doesn't do the same for defterm-initiated connections. This is
because we don't need to! Defterm very explicitly rejects handoff for
minimized console apps. This is probably for the best! I put an attempt
in 66f8b25ec before I forgot that it was filtered long before the
Terminal. NOT doing this for /min saves us all sorts of "what happens if
`start /min cmd` tries to glom?" or "what if someone does `start /min
cmd && start /max cmd` and they glom together?".
<hr>
Also closes#15193, which was introduced as a part of this.
---------
Co-authored-by: Dustin L. Howett <duhowett@microsoft.com>
This is a revert of the revert of #12979. We mainly reverted that PR
because of an issue where restored windows would grow/shrink slightly on
external displays. It was too close to the ship date for that release,
so we backed it out wholesale (in #13098). I think I've found the real
root of the problem, and fixed it here.
The money diff here from the original PR:
4c08b9a1bc2e90b8284e4d8117d0de400784520f...c34495dcfc19ea67a9f4f9673d422760200683ab.
Basically, I had put the part where we actually handle the creation of
the window into `_AppInitializedHandler`, when we should have left the
window to be created in `_HandleCreateWindow` We create it there,
_hidden_, and then should only _show_ it in `_AppInitializedHandler`.
I'm _NOT_ incorporating the change for #9053. I reverted that bit in
1fac40355. I am too worried about that messing with the phwnd that I
wanted to get that reviewed and committed atomically, separately.
* fixes #11561
* tested manually
* I work here
This adds a setting (`compatibility.allowHeadless`) to let the Terminal
keep running even when all windows are closed. This lets hotkeys keep
working, because the Emperor thread is still running, just, without any
windows.
I'm really tempted to invoke the magic "closes" word on #9996, but
honestly, we should also add some sort of support for `wt --headless` or
`wt --hidden` or whatever, before we close that. There's also #13630
which seems imminently doable.
Tested manually. I'd post a gif of "close all terminal windows, then
invoke the quakeMode binding and \*presto\*, but that would be an
unnecessarily big gif.
Related to #9996 but not enough to close it if you ask me
_This is the last one 🎉_
## Summary
_In the final chapter of our tale, we present a PR of great
significance. It grants the power to tear tabs from their windows and
create a new window where they may be dropped, one not necessarily of
the Terminal sort. The dimensions of the original window are transferred
to this new abode, and its placement on the screen is determined by the
user's placement of the tab._
_This is the last main chapter of the tear-out saga, and the dawning of
the new age._
Closes#5000
Related to #1256
## Detailed description
We're really leaning on the existing `RequestNewWindow` event that the
monarch already had - honestly, most of that was so simple that it could
have just been in the parent PRs. We just need to add new support for
passing in a content blob of json, and making sure the Terminal always
uses that over commandline args. Easy enough.
There's a bit of wackiness here in adjusting the positioning just right
so that the new window appears in the right place, but it feels...
pretty good all things considered.
## Summary
_In the days of old, the windows were sundered, each with its own
process, like the scattered stars in the sky. But a new age hath dawned,
for all windows now reside within a single process, like the bright gems
of a single crown._
_And lo, there came the `WindowEmperor`, a new lord to rule over the
global state, wielding the power of hotkeys and the beacon of the
notification icon. The `WindowManager` was cast aside, no longer needed
to seek out other processes or determine the `Monarch`._
_Should the `WindowEmperor` determine that a new window shall be raised,
it shall set forth a new thread, born from the ether, to govern this new
realm. On the main thread shall reside a message loop, charged with the
weighty task of preserving the global state, guarded by hotkeys and the
beacon of the notification icon._
_Each window doth live on its own thread, each guarded by the new
`WindowThread`, a knightly champion to hold the `TerminalWindow`,
`AppHost`, and `IslandWindow` in its grasp. And so the windows shall run
free, no longer burdened by their former ways._
All windows are now in a single process, rather than in one process per
window. We'll add a new `WindowEmperor` class to manage global state
such as hotkeys and the notification icon. The `WindowManager` has been
streamlined and no longer needs to connect to other processes or
determine a new `Monarch`. Each window will run on its own thread, using
the new `WindowThread` class to encapsulate the thread and manage the
`TerminalWindow`, `AppHost`, and `IslandWindow`.
* Related to #5000
* Related to #1256
## Windows Terminal Process Model 3.0
Everything is now one process. All the windows for a single Terminal
instance live in a singular Terminal process. When a new terminal
process launches, it will still attempt to communicate with an existing
one. If it finds one, it'll pass the commandline to that process and
exit. Otherwise, it'll become the "monarch" and create a new window.
We'll introduce a new abstraction here, called the `WindowEmperor`.
`Monarch` & `Peasant` will still remain, for facilitating cross-window
communication. The Emperor will allow us to have a single dedicated
class for all global state, and will now always represent the "monarch"
(rather than our previously established non-deterministic monarchy to
elevate a random peasant to the role of monarch). We still need to do a
very minimal amount of x-proc calls. Namely, one right on startup, to
see if another `Terminal.exe` was already running. If we find one, then
we toss our commandline at it and bail. If we don't, then we need to
`CoRegister` the Monarch still, to prepare for subsequent launches to
send commands to us.
`WindowManager` takes the most changes here. It had a ton of logic to
redundantly attempt to connect to other monarchs of other processes, or
elect a new one. It doesn't need to do any of that anymore, which is a
pretty dramatic change to that class.
This creates the opportunity to move some lifetime management around.
We've played silly games in the past trying to have individual windows
determine if they're the singular monarch for global state.
`IslandWindow`s no longer need to track things like global hotkeys or
the notification icon. The emperor can do that - there's only ever one
emperor. It can also own a singular copy of the settings model, and hand
out references to each other thread.
Each window lives on separate threads. We'll need to separately
initialize XAML islands for each thread. This is totally fine, and
actually supported these days. We'll use a new class called
`WindowThread` to encapsulate one of these threads. It'll be responsible
for owning the `TerminalWindow`, `AppHost` and `IslandWindow` for a
single thread.
This introduces new classes of bugs we'll need to worry about. It's now
easier than ever to have "wrong thread" bugs when interacting with any
XAML object from another thread. A good case in point - we used to stash
a `static` `Brush` in `Pane`, for the color of the borders. We can't do
that anymore! The first window will end up stashing a brush from its
thread. So now when a second window starts, the app explodes, because
the panes of that window try to draw their borders using a brush from
the wrong thread.
_Another fun change_: The keybinding labels of the command palette.
`TerminalPage` is the thing that ends up expanding iterable `Command`s.
It does this largely with copies - it makes a new `map`, a new `vector`,
copies the `Command`s over, and does the work there before setting up
the cmdpal.
Except, it's not making a copy of the `Command`s, it's making a copy of
the `vector`, with winrt objects all pointing at the `Command` objects
that are ultimately owned by `CascadiaSettings`.
This doesn't matter if there's only one `TerminalPage` - we'll only ever
do that once. However, now there are many Pages, on different threads.
That causes one `TerminalPage` to end up expanding the subcommands of a
`Command` while another `TerminalPage` is ALSO iterating on those
subcommands.
_Emperor message window_: The Emperor will have its own HWND, that's
entirely unrelated to any terminal window. This window is a
`HWND_MESSAGE` window, which specifically cannot be visible, but is
useful for getting messages. We'll use that to handle the notification
icon and global hotkeys. This alleviates the need for the IslandWindow
to raise events for the tray icon up to the AppHost to handle them. Less
plumbing=more good.
### Class ownership diagram
_pretend that I know UML for a second_:
```mermaid
classDiagram
direction LR
class Monarch
class Peasant
class Emperor
class WindowThread
class AppHost
Monarch "1" --o "*" Peasant: Tracks
Emperor --* "1" AppLogic:
Monarch <..> "1" Emperor
Peasant "1" .. "1" WindowThread
Emperor "1" --o "*" WindowThread: Tracks
WindowThread --* AppHost
AppHost --* IslandWindow
AppHost --* TerminalWindow
TerminalWindow --* TerminalPage
```
* There's still only one `Monarch`. One for the Terminal process.
* There's still many `Peasant`s, one per window.
* The `Monarch` is no longer associated with a window. It's associated
with the `Emperor`, who maintains _all_ the Terminal windows (but is not
associated with any particular window)
* It may be relevant to note: As far as the `Remoting` dll is concerned,
it doesn't care if monarchs and peasants are associated with windows or
not. Prior to this PR, _yes_, the Monarch was in fact associated with a
specific window (which was also associated with a window). Now, the
monarch is associated with the Emperor, who isn't technically any of the
windows.
* The `Emperor` owns the `App` (and by extension, the single `AppLogic`
instance).
* Each Terminal window lives on its own thread, owed by a `WindowThread`
object.
* There's still one `AppHost`, one `IslandWindow`, one `TerminalWindow`
& `TerminalPage` per window.
* `AppLogic` hands out references to its settings to each
`TerminalWindow` as they're created.
### Isolated Mode
This was a bit of a tiny brainstorm Dustin and I discussed. This is a
new setting introduced as an escape watch from the "one process to rule
them all" model. Technically, the Terminal already did something like
this if it couldn't find a `Monarch`, though, we were never really sure
if that hit. This just adds a setting to manually enable this mode.
In isolated mode, we always instantiate a Monarch instance locally,
without attempting to use the `CoRegister`-ed one, and we _never_
register one. This prevents the Terminal from talking with other
windows.
* Global hotkeys won't work right
* Trying to run commandlines in other windows (`wt -w foo`) won't work
* Every window will be its own process again
* Tray icon behavior is left undefined for now.
* Tab tearout straight-up won't work.
### A diagram about settings
This helps explain how settings changes get propagated
```mermaid
sequenceDiagram
participant Emperor
participant AppLogic
participant AppHost
participant TerminalWindow
participant TerminalPage
Note Right of AppLogic: AL::ReloadSettings
AppLogic ->> Emperor: raise SettingsChanged
Note left of Emperor: E::...GlobalHotkeys
Note left of Emperor: E::...NotificationIcon
AppLogic ->> TerminalWindow: raise SettingsChanged<br>(to each window)
AppLogic ->> TerminalWindow:
AppLogic ->> TerminalWindow:
Note right of TerminalWindow: TW::UpdateSettingsHandler
Note right of TerminalWindow: TW::UpdateSettings
TerminalWindow ->> TerminalPage: SetSettings
TerminalWindow ->> AppHost: raise SettingsChanged
Note right of AppHost: AH::_HandleSettingsChanged
```