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.
## Summary of the Pull Request
When a connection is Closed, show an indicator in the respective tab.
When the active pane's connection is Closed, show a "Restart Connection"
action in the right-click context menu and in the tab context menu.
## Validation Steps Performed
- Force close a connection, check the indicator is shown in the tab.
- Right-click on pane shows the Restart Connection action if its
connection is closed
- Right-click on tab shows the Restart Connection action if the active
pane's connection is closed
- Indicator is cleared after connection is restarted (no panes in closed
state)
## PR Checklist
- [x] Closes#14909
- [x] Tests added/passed
- [ ] Documentation updated
- [ ] Schema updated (if necessary)
## Summary of the Pull Request
Resolves the following in #15812
> - [x] `toggleBroadcastInput` isn't in the default settings
> - [x] The cursors forget to keep blinking if you focus each pane and
then unfocus them
> - [x] They don't stop blinking when you unbroadcast
> - [x] Broadcast border doesn't appear when you make new panes, but
they ARE broadcasted-to!
## References and Relevant Issues
x-ref:
* #2634
* #14393
## Detailed Description of the Pull Request / Additional comments
There was literally no logic in the original PR for starting the cursor
blinking. It's entirely unknowable how that ever worked. This makes it
all much more explicit.
We're taking the hacky `DisplayCursorWhileBlurred` from #15363, and
promoting that to the less-hacky `CursorVisibility`. Broadcast input
mode can use that to force the cursor to be visible always.
The last checkbox in that issue is harder, and I didn't want to further
pollute this delta with the paste plumbing.
`TerminalTab::_RecalculateAndApplyReadOnly` didn't know about whether a
tab should be closable or not, based on the theme settings. Similarly
(though, unreported), the theme update in
`TerminalPage::_updateAllTabCloseButtons` didn't really know about
readonly mode.
This fixes both these issues by moving responsibility for the tab close
button visibility into `TabBase` itself.
Closes#15902
Uses the `RaiseNotificationEvent()` API from UIA automation peers to
announce successful `MovePane` and `MoveTab` actions. The announcements
are localized in the resw file.
Closes#15159
Based on #13575
This PR's goal is to allow something like a `Tab` to raise a
ShortcutAction, by saying "this action should be performed on ME". We've
had a whole category of these issues in the past:
* #15734
* #15760
* #13579
* #13942
* #13942
* Heck even dating back to #10832
So, this tries to remove a bit of that footgun. This probably isn't the
_final_ form of what this refactor might look like, but the code is
certainly better than before.
Basically, there's a few bits:
* `ShortcutActionDispatch.DoAction` now takes a `sender`, which can be
_anything_.
* Most actions that use a "Get the focused _thing_ then do something to
it" are changed to "If there was a sender, let's use that - otherwise,
we'll use the focused _thing_".
* TerminalTab was largely refactored to use this, instead of making
requests to the `TerminalPage` to just do a thing to it.
I've got a few TODO!s left, but wanted to get initial feedback.
* [x] `TerminalPage::_HandleTogglePaneZoom`
* [x] `TerminalPage::_HandleFocusPane`
* [x] `TerminalPage::_MoveTab`
Closes#15734
When a tab gets closed, `_RemoveTab` will call `TabBase::Shutdown()`,
which then re-raises the `Closed` event, which will end up calling
`_RemoveTab` again, etc. The only reason this didn't crash WT so far
is because `_RemoveOnCloseRoutine` contains a `resume_foreground`,
which would resolve the recursion and turn it into CPU usage.
It would spin as long as WinUI hasn't discard the tab object,
which takes an unpredictable amount of time.
Raising the `Closed` event from `Shutdown()` is unnecessary, because
the handlers of the event end up calling `_RemoveTab` anyways.
Technically the entire `Closed` event can be removed now, but I left it
in anyways because resolving the architectural "knot" around the way
tab closing after the last pane closes is implemented requires much
more significant changes.
This commit additionally removes the `_createCloseLock` mutex in `Pane`
as it was very likely not working as intended anyways. Only some methods
were protected by it and it doesn't avoid any STA/MTA/NA issues either.
## Validation Steps Performed
* Closing tabs and panes always ends up calling `Shutdown()` ✅
_targets #14943_
When this is true, this will re-use the existing commandline to
pre-filter the results. This is especially helpful for completing a
suggestion based on the text that's already been typed.
Like with command history, this requires that shell integration is
enabled before it will work.## Summary of the Pull Request
## References and Relevant Issues
See also #13445
As spec'd in #14864
## Validation Steps Performed
Tested manually
There's two parts to this PR that should be considered _separately_.
1. The Suggestions UI, a new graphical menu for displaying suggestions /
completions to the user in the context of the terminal the user is
working in.
2. The VsCode shell completions protocol. This enables the shell to
invoke this UI via a VT sequence.
These are being introduced at the same time, because they both require
one another. However, I need to absolutely emphasize:
### THE FORMAT OF THE COMPLETION PROTOCOL IS EXPERIMENTAL AND SUBJECT TO
CHANGE
This is what we've prototyped with VsCode, but we're still working on
how we want to conclusively define that protocol. However, we can also
refine the Suggestions UI independently of how the protocol is actually
implemented.
This will let us rev the Suggestions UI to support other things like
tooltips, recent commands, tasks, INDEPENDENTLY of us rev'ing the
completion protocol.
So yes, they're both here, but let's not nitpick that protocol for now.
### Checklist
* Doesn't actually close anything
* Heavily related to #3121, but I'm not gonna say that's closed till we
settle on the protocol
* See also:
* #1595
* #14779
* https://github.com/microsoft/vscode/pull/171648
### Detailed Description
#### Suggestions UI
The Suggestions UI is spec'ed over in #14864, so go read that. It's
basically a transient Command Palette, that floats by the user's cursor.
It's heavily forked from the Command Palette code, with all the business
about switching modes removed. The major bit of new code is
`SuggestionsControl::Anchor`. It also supports two "modes":
* A "palette", which is like the command palette - a list with a text
box
* A "menu", which is more like the intellisense flyout. No text box.
This is the mode that the shell completions use
#### Shell Completions Protocol
I literally cannot say this enough times - this protocol is experimental
and subject to change. Build on it at your own peril. It's disabled in
Release builds (but available in preview behind
`globals.experimental.enableShellCompletionMenu`), so that when it
ships, no one can take a dependency on it accidentally.
Right now we're just taking a blob of JSON, passing that up to the App
layer, who asks `Command` to parse it and build a list of `sendInput`
actions to populate the menu with. It's not a particularly elegant
solution, but it's good enough to prototype with.
#### How do I test this?
I've been testing this in two parts. You'll need a snippet in your
powershell profile, and a keybinding in the Terminal settings to trigger
it. The work together by binding <kbd>Ctrl+space</kbd> to _essentially_
send <kbd>F12</kbd><kbd>b</kbd>. Wacky, but it works.
```json
{ "command": { "action": "sendInput","input": "\u001b[24~b" }, "keys": "ctrl+space" },
```
```ps1
function Send-Completions2 {
$commandLine = ""
$cursorIndex = 0
# TODO: Since fuzzy matching exists, should completions be provided only for character after the
# last space and then filter on the client side? That would let you trigger ctrl+space
# anywhere on a word and have full completions available
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$commandLine, [ref]$cursorIndex)
$completionPrefix = $commandLine
# Get completions
$result = "`e]633;Completions"
if ($completionPrefix.Length -gt 0) {
# Get and send completions
$completions = TabExpansion2 -inputScript $completionPrefix -cursorColumn $cursorIndex
if ($null -ne $completions.CompletionMatches) {
$result += ";$($completions.ReplacementIndex);$($completions.ReplacementLength);$($cursorIndex);"
$result += $completions.CompletionMatches | ConvertTo-Json -Compress
}
}
$result += "`a"
Write-Host -NoNewLine $result
}
function Set-MappedKeyHandlers {
# VS Code send completions request (may override Ctrl+Spacebar)
Set-PSReadLineKeyHandler -Chord 'F12,b' -ScriptBlock {
Send-Completions2
}
}
# Register key handlers if PSReadLine is available
if (Get-Module -Name PSReadLine) {
Set-MappedKeyHandlers
}
```
### TODO
* [x] `(prompt | format-hex).`<kbd>Ctrl+space</kbd> -> This always
throws an exception. Seems like the payload is always clipped to
```{"CompletionText":"Ascii","ListItemText":"Ascii","ResultType":5,"ToolTip":"string
Ascii { get```
and that ain't JSON. Investigate on the pwsh side?
## Summary of the Pull Request
Add support for running profiles in the Add Tab drop down as
administrator without a keyboard.
## References and Relevant Issues
#14517
## Detailed Description of the Pull Request / Additional comments
This pull request adds a FlyoutMenu to each Profile entry in the Add New
tab drop down. When a profile is right clicked or held for 2 seconds in
the case of no mouse input will present a MenuItem to allow the user to
click and run the selected profile as administrator
## Validation Steps Performed
- Responds to pointer input events (mouse, pointer, touchpad)
- Adjusts to theme changes.
- Only shows when a profile is selected. Will not show on settings or
pallete entries
## PR Checklist
- [x] Closes#14517
- [ ] Tests added/passed
- [ ] Documentation updated
- If checked, please file a pull request on [our docs
repo](https://github.com/MicrosoftDocs/terminal) and link it here: #xxx
- [ ] Schema updated (if necessary)
Resurrection of #9222.
Spec draft in #9365.
Consensus from community feedback is that the whole of that spec is
_nice to have_, but what REALLY matters is just broadcasting to all the
panes in a tab. So, in the interest of best serving our community, I'm
pushing this out as the initial implementation, before we figure out the
rest of design. Regardless of how we choose to implement the rest of the
features detailed in the spec, the UX for this part of the feature
remains the same.
This PR adds a new action: `toggleBroadcastInput`. Performing this
action starts broadcasting to all panes in this tab. Keystrokes in one
pane will be sent to all panes in the tab.
An icon in the tab is used to indicate when this mode is active.
Furthermore, the borders of all panes will be highlighted with
`SystemAccentColorDark2`/`SystemAccentColorLight2` (depending on the
theme), to indicate they're also active.
* [x] Closes#2634.
- (we should lick a reserved thread for follow-ups)
Co-authored-by: Don-Vito khvitaly@gmail.com
## Summary of the Pull Request
Adds a dismiss selection option to the "copy" action.
## PR Checklist
- [x] Closes#15371
- [x] Tests added/passed
- [x] Documentation updated
- If checked, please file a pull request on [our docs
repo](https://github.com/MicrosoftDocs/terminal) and link it here:
MicrosoftDocs/terminal#686
- [x] Schema updated (if necessary)
---------
Co-authored-by: Carlos Zamora <carlos.zamora@microsoft.com>
Due to an implementation detail in the Xaml compiler--which wants to
ensure that all metadata providers on an App are available
immediately--we were eagerly loading the settings UI DLL and all of its
dependencies, even in sessions where the user was not going to open
Settings.
By turning off eager provider generation and handling it ourselves, we
get to control exactly when the settings UI is loaded.
This required some gentle poking-through of the barrier between App and
Page, but it is almost certainly worth it.
Turning on the Xaml code generation flag to not generate providers
automatically adds an `AddProvider` member to the internal interface for
the autogenerated XamlMetadataProvider. We needed to switch to using the
internal interface rather than the projected type in our custom App base
class to get at it.
Providers that App/Page use must be initialized by the time we start the
WindowsXamlManager, so we load Control and Controls (ha) eagerly and
early.
It looks like it may save 400ms of CPU time (?) on startup.
This PR adds a `searchWeb` command to search the selected text on the web.
Arguments:
- `queryUrl`: URL of the web page to launch (the selected text will be
inserted where the first `%s` is found in the query string)
To make the search text more "compact" and handle multi-line selections,
I'm concatenating the selected lines and replacing consecutive
whitespaces with a single space (we may change this with something more
clever in case).
## Validation Steps Performed
Manual testing with single, multi-line, block selections.
Closes#10175
---------
Co-authored-by: Marco Pelagatti <marco.pelagatti@iongroup.com>
Co-authored-by: Mike Griese <migrie@microsoft.com>
When `elevate` is set to `true`, `_maybeElevate` would try to
modify `newTerminalArgs` and crash, because during tab duplication
there aren't any `newTerminalArgs`. This issue may happen for instance
when receiving hand-off from a non-elevated client and then trying
to duplicate that tab.
Closes#15534
## Validation Steps Performed
* Launch with `"elevate": false`
* Set `"elevate": true`
* Duplicate a tab
* Doesn't crash ✅
_targets #15280_
When ctrl+clicking on a profile, pre-evaluate the starting directory of
that profile, and stash that in the commandline we pass to elevate shim.
So in the case of something like "use parent process directory", we'll
run `elevate-shim new-tab -p {guid} -d "C:\\the path\\of\\terminal\\."`
Closes#15173
---------
Co-authored-by: Leonard Hecker <lhecker@microsoft.com>
XAML/WinUI may pump the event loop internally. One of the functions
that does this right now is `DesktopWindowXamlSource::Close()`.
This is problematic in the previous code, because we'd set `_window`
to `nullptr` before calling `Close()` and so any of the `IslandWindow`
callbacks may be invoked during shutdown, which then try to potentially
access `_window` and end up crashing. This commit fixes the issue by
simply not nulling out the `_window` and calling `Close()` directly.
Furthermore, `NonClientIslandWindow` may directly access WinUI
objects in its message handlers which also crashes.
I've had this happen roughly ~1% of my test exits in a debug build
and every single time on a (artificial) very slow CPU.
## Validation Steps Performed
* Closing a window destroys the rendering instance ✅
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.
After retrieving the items via `GetStorageItemsAsync()` inside a try
clause it fails to check if the pointer is actually non-null.
Apart from this this commit fixes the unsafe use of `this` by properly
using `get_weak()`. Finally it allows >1 paths to be dropped.
## Validation Steps Performed
* Dropping >1 file works ✅
* Dropping >1 directory works ✅
This MR introduces `activeOnly ` for the `showCloseButton` theme option
causing the close button only to appear on the active tab.
This is more or less following the approach explained here
https://github.com/orgs/microsoft/projects/686/views/2?pane=issue&itemId=19775774
which indeed just works 😄 .
You notice when switching theme the close buttons is back on all tabs
again as well.
Closes#13672
I didn't check specific unit tests for this. I hope by making this MR
the pipeline will show if I broke something. Or just let me know if you
want me to add something specific for this.
Adds an action for immediately restarting the connection. I suspect
most folks that wanted #3726 will be happy just with the
<kbd>enter</kbd> solution from #14060, but this will work without having
to `exit` the client. Just, relaunch whatever the commandline is. Easy
peasy.
Closes#3726.
Obsoletes #14549
A different take on #14548.
> We didn't love that a connection could transition back in the state
diagram, from Closed -> Start. That felt wrong. To remedy this, we're
going to allow the ControlCore to...
ASK the app to restart its connection. This is a much more sensible
approach, than leaving the ConnectionInfo in the core and having the
core do the restart itself. That's mental.
Cleanup from #14060Closes#14327
Obsoletes #14548
Original bug report #15049
Relates to feature #1571
MenuFlyoutSubItem, when collapsing from profile selection, move focus
back to the titlebar.
An extra Closing event handler is needed to keep focus on the command
shell.
Closes#15049
The ability to build and run Terminal as a UWP application was removed
in #12119. We left some of its vestiges around, but now there is no need
for them.
This sets `x:Load` to `false` for the two elements.
On my system, with Windows Defender disabled, this reduces CPU
usage by 15ms and the visual delay during launch by 40ms.
Part of #5907
## Validation Steps Performed
* Ctrl+Shift+P opens command palette ✅
* Context menu opens command palette ✅
* Context menu opens about dialog ✅
TL;DR: we stopped getting `TabView.TabItemsChanged`. This meant that the
tab view would change its apparent order, but we wouldn't change the
backing tab order.
I'm fixing this by grabbing the index of the tab that starts the drag,
and the index of the tab view item at the end of the drag, and using
that to reorder our backing list.
Closes#15121
Upstream https://github.com/microsoft/microsoft-ui-xaml/issues/8388
Regressed in #15078 - I'm pretty confident about this, since I've got a
1.18.931 build of the Terminal with tear-out, but not MUX 2.8.
Existing environment variables can be referenced by enclosing the name
in percent characters (e.g. `%PATH%`).
Resurrects #9287 by @christapley.
Tests added and manually tested.
Closes#2785Closes#9233
Co-authored-by: Chris Tapley <chris.tapley.81@gmail.com>
This PR adds support to the About Dialog for checking the store to see
if there's a new version of the Terminal package available. We'll only
do this once per day, per terminal window.
In dev mode, we'll always fake it and say there's an update to `x.y.z`
available.
This also involved pulling all of the About dialog code out into its own
class. All that is goodness.
We don't currently provide a button for _installing_ the update. We just
check. Incremental progress is better than none.
Co-authored-by: Mike Griese <migrie@microsoft.com>
Co-authored-by: Leonard Hecker <lhecker@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 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.
_Behold, the penultimate chapter in the saga of tear-out! This
significant update bestows upon the user the power to transport tabs
betwixt Terminal windows. Alas, the drag and drop capabilities of
TabView are not yet refined, so this PR primarily concerns itself with
the intricacies of plumbing. When a tab is extracted and deposited
elsewhere, it is necessary to have the recipient make an inquiry to the
Monarch, who in turn will beseech the sender to transmit the tab
content, akin to the act of moving a tab. Curious it may seem, but the
method has proven effective._
The penultimate tear-out PR. This PR enables the user to move tabs from
one Terminal window to another. The TabView drag/drop APIs have some
rough edges, so this PR is mostly plumbing. When a tab is drag/dropped,
we need to get the recipient to ask the Monarch to ask the sender to
send the tab content, like a MoveTab action. Wacky, but it works.
There's a LONG tail of UX gaps. Those I'm going to track in #14900. It
is more valuable for us to merge this now than to figure out workarounds
immediately.
The next PR will be the last main PR in this saga - in which we enable
dragging a tab out of the window and dropping to create a new window.
* Closes#1256
* Related to #5000
* Follow-ups get to go in #14900
## Detailed description
As I mentioned, it's mostly plumbing. The order that we get tab drag
events is... unfortunate... for our use case. So we do a lot of sending
`RequestReceiveContentArgs` up and down between windows, just to
communicate who the tab was dropped on to whomever the tab was dragged
from.
There's a diagram for this that I originally put in
https://github.com/microsoft/terminal/issues/5000#issuecomment-1435328038:
```mermaid
sequenceDiagram
participant Source
participant Target
participant Monarch
Note Left of Source: _onTabDragStarting
Source --> Source: stash dragged content
Source --> Source: pack window ID into DataPackage
Source ->> Target: Drag tab
Note right of Target: _onTabStripDragOver
Target ->> Target: AcceptedOperation(DataPackageOperation::Move)
Source --> Target: Release mouse (to drop)
Note right of Target: _onTabStripDrop
Target --> Target: get WindowID from DataPackage
Target -) Monarch: Request that WindowID sends content to us<br>RequestRecieveContent
Monarch -) Source: Tell to send content to Target.Id<br>RequestSendContent, SendContent
Source --> Source: detach our content
Source -) Monarch: RequestMoveContent(stashed, target.id)
Monarch -) Target: AttachContent(stashed)
# Target -->> Source:
# Note Left of Source: TabViewTabDragStartingEventArgs<br>.OperationCompleted
# Note Left of Source: _onTabDroppedCompleted
```
Really really though, let's try to avoid nits about the UX at this time.
This PR works with what we've got. Mail threads are percolating. I've
got 19 chapters worth of Hobbit branch names to use for those follow
ups.
_Lo! Harken to me, for I shall divulge the heart of the tab tear-out
saga. Verily, this PR shall bestow upon thee the power to move tabs and
panes between windows by means of pre-defined actions. Though be warned,
it does not yet grant thee the power to drag and drop them as thou
mayest desire. Yet, the same plumbing that underpins this work shall
remain steadfast. Behold, the majority of this undertaking concerns the
elevation of the RequestMoveContent event from the TerminalPage to the
very summit of the Monarch. From thence, a great AttachContent method
shall descend back to the lowest depths. Furthermore, there are minor
revisions to TermControl that shall enable thee to better detach the
content and attach it to a new one._
This is the most important part of the tab tear-out saga. This PR
enables the user to move tabs and panes between windows using
pre-defined actions. It does _not_ enable the user to drag/drop them
yet, but the same fundamental plumbing will still apply. Most of the PR
is plumbing the `RequestMoveContent` event up from the `TerminalPage` up
to the `Monarch`, and then plumbing an `AttachContent` method back down.
There are also small changes to `TermControl` to better support
detaching the content and attaching to a new one.
For testing, I recommend:
```json
{ "keys": "f1", "command": { "action": "moveTab", "window": "1" } },
{ "keys": "f2", "command": { "action": "moveTab", "window": "2" } },
{ "keys": "f3", "command": { "action": "movePane", "window": "1" } },
{ "keys": "f4", "command": { "action": "movePane", "window": "2" } },
{ "keys": "shift+f3", "command": { "action": "movePane", "window": "1", "index": 3 } },
{ "keys": "shift+f4", "command": { "action": "movePane", "window": "2", "index": 3 } },
```
* Related to #1256
* Related to #5000
---------
Co-authored-by: Carlos Zamora <carlos.zamora@microsoft.com>
## Summary
_Thus we come to the introduction of a new servant, the
`ContentManager`, a singular entity that serves at the behest of the
`emperor`. It is its charge to keep track of all `TermControl` instances
created by the windows, for each window must seek its blessing before
calling forth such an instance._
_With the aid of the `ContentManager`, the `TermControl` shall now be
traced by the hand of fate through the use of unique identifying marks,
known as `GUID`s. Yet, its purpose remains yet unknown, for it is merely
a waypoint upon the journey yet to come._
_This act of bridging also brings a change to the handling of events
within the `TermControl`. This change shall see the addition of a
revoker, similar to the manner in which the `AppHost` hath employed it,
to the `TermControl`. Additionally, there is a new layer of indirection
between the `ControlCore` and the `App` layer, making ready for the day
when the `TermControl` may be repositioned and re-parented with ease._
_Consider this but a trivial act, a mere shadow of things yet to come,
for its impact shall be felt but briefly, like the passing of a gentle
breeze._
Related to #5000
Related to #1256
# Detailed description
This PR is another small bridge PR between the big work in #14843, and
the PR that will enable panes to move between windows.
This introduces a new class, called `ContentManager`. This is a global
singleton object, owned by the emperor. Whenever a window wants to
instantiate a new `TermControl`, it must ask the ContentManager to give
it one. This allows the ContentManager to track each "content" by GUID.
That's it. We don't do anything with them in this PR by itself, we just
track them.
This also includes a small change to the way TermControl events are
handled. It adds an `AppHost`-like revoker struct, and weak_ref's all
the handlers. We also add a layer of indirection between the
ControlCore's raising of events and the App layer's handling. This will
make reparenting content easier in the future.
This is a pretty trivial change which shouldn't have any major side
effects. Consider it exposition of the things to come. It's
intentionally small to try and keep the reviews more managable.
## 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
```
Credit where credit is due - @jboelter did literally all the hard work.
I just separated this out to two elements:
* Are we running elevated?
* Can we drag drop?
As we learned in #7754, the builtin administrator _can_ drag drop. But
critically, they are also running as admin! The way we had this logic
before, we're treat them as unelevated, because we had been overloading
the meaning here.
This splits these into two separate functions. Comes with the added
benefit of re-adding the elevation shield to the Terminal window for
users with UAC disabled (which was missing before) (and can _still_ be
disabled).
Closes#13928
Tested on a Win10 VM with `EnableLua=0`
Experimental for now. `experimental.rightClickContextMenu`, a
per-profile setting. Long term we want to enable full mouse bindings, at
which point this would be replaced.
Closes#3337
This adds **two** context menus to the `TermControl` - one for
right-clicking with a selection, and one without. The implementation is
designed to follows the API experience of the context menu on something
like a [`RichEditBox`](winui2gallery://item/RichEditBox). The hosting
application adds a handler for the menu's `Opening` event, and appends
whatever items it wants at that time.
So `TermControl` only implements a few "actions" by default - copy,
past, find. `TerminalApp` is then responsible for adding anything else
it needs. Right now, those actions are:
* Duplicate tab
* Duplicate pane
* Close Tab
* Close pane
Screenshots in
https://github.com/microsoft/terminal/pull/14775#issuecomment-1415737393
Adds a global setting `compatibility.reloadEnvironmentVariables` with a
default value of `true`. When set, during connection creation a new
environment block will be generated to ensure it has the latest
environment variables.
Closes#1125
Co-authored-by: Leonard Hecker <lhecker@microsoft.com>
Does two things related to URLs emitted via OSC8.
* Allows `wsl$` and `wsl.localhost` as the hostname in `file://` URIs
* Generally allows _all_ URIs that parse as a URI.
The relevant security comments: https://github.com/microsoft/terminal/pull/7526#issuecomment-764160208
> this doesn't let a would-be attacker specify command-line arguments (ala "cmd.exe /s /c do_a_bad_thing") (using somebody else's reputation to cause mayhem)
>
> `ShellExecute` de-elevates because it bounces a launch request off the shell
>
> "Works predictably for 15% of applications" (h/t to PhMajerus' AXSH, and other on-Windows requestors) is better in so many ways than "Works for 0% of applications", in my estimation. Incremental progress 😄 while we work on features that'll make it even more broadly applicable.
Closes#10188Closes#7562
_And so begins the first chapter in the epic tale of the Terminal's tab
tear-out. This commit, though humble in its nature, shall mark the
beginning of a grand journey._
_This initial offering, though small in its scope, doth serve to divide
the code that currently resides within TerminalPage and AppLogic, moving
it unto a new entity known as TerminalWindow. In the ages to come, these
classes shall take on separate responsibilities, each with their own
purpose._
_The AppLogic shall hold sway over the entire process, shared among all
Terminal windows, while the AppHost, TerminalWindow, and TerminalPage
shall rule over each individual window._
_This pull request prepares the way for the future, moving state that
pertains to the individual windows into the TerminalWindow. This is a
task of great labor, for it requires moving much code, but the end
result shall bring greater organization to the codebase._
_And so the stage is set, for in the next pull request, the Process
Model v3 shall be revealed, unifying all Terminal windows into a single
process, a grand accomplishment indeed._
_courtesy of G.P.T. Tolkien_
<details>
<summary>Or, as I wrote it originally. </summary>
This is the first of the commits in the long saga which will culminate
in tab tear-out for the Terminal.
This the most functionally trivial of the PRs. It mostly just splits up
code that's currently in TerminalPage & AppLogic, and moves it into a
new class `TerminalWindow`. In the future, these classes will separate
responsibility as such:
* There will be one `AppLogic` per process, shared across all Terminal
windows.
* There will be one `AppHost`, `TerminalWindow`, and `TerminalPage` for
each individual window in the process.
This PR prepares for that by moving some state that's applicable to
_individual windows_ into `TerminalWindow`. This is almost exclusively a
code moving PR. There should be minimal functional changes.
</details>
In the next PR, we'll introduce the actual "Process Model v3", merging
all Terminal windows into a single terminal process.
Related to #5000. See
https://github.com/Microsoft/terminal/issues/5000#issuecomment-1407110045
for my current todo list.
Related to #1256.
These commits are all artificially broken down pieces. Honestly, I don't
want to really merge them till they're all ready, so we know that the
work e2e. This my feigned attempt to break it into digestable PRs.
Lightly manually tested, things seem to still all work? Most of this
code was actually written in deeper branches, it was only today I
realized it all needed to come back to this branch.
* [x] The window persistence fishy-ness of the subsequent PR isn't
present here. So that's something.
* [x] Localtests still pass
### Detailed description
> Q: Does `AppLogic` not keep track of its windows?
Sure doesn't! I didn't think that was something it needed to know.
>Q: Why does `TerminalWindow` (per-window) have access to the
commandline args (per-process)
It's because it's _not_ per process. Commandline args _are_ per-window.
Consider - you launch the Terminal, then run a `wt -w -1 -- foo`. That
makes its own window. In this process, yes. But that new window has its
own commandline args, separate from the ones that started the original
process.
This pull request removes, in full, our dependency on cpprestsdk. This
allows us to shed 500KiB-1.2MiB from our package off the top and enables
the following future investments:
- Removal of the App CRT forwarders to save an additional ~500KiB
- Switching over to the HybridCRT and removing our dependency on _any
CRT_.
cpprest was built on my dev box two or so years ago, and is in _utter_
violation of our compliance guidelines on SBOM et al.
In addition, this change allows us to use the proxy server configured
in Windows Settings.
I did this in four steps (represented roughly by the individual commits):
1. Switch from cpprest's http_client/json to Windows.Web.Http and
Windows.Data.Json
2. Switch from websocketpp to winhttp.dll's WebSocket implementation¹
3. Remove all remaining utility classes
4. Purge all dependencies from all projects and scripts on cpprest.
I also took this opportunity to add a feature flag that allows Dev
builds to run AzureConnection in-process.
¹ Windows.Networking.Sockets' API is so unergonomic that it was simply
infeasible (and also _horrible_) to use it.
## Validation Steps
I've run the Azure Connection quite a bit inproc.
Closes#4575.
Might be related to #5977, #11714, and with the user agent thing maybe #14403.
## Summary of the Pull Request
Updates the tab event handling so that the "Export Text" and "Find" tab context menu items work when a tab isn't focused.
## PR Checklist
* [x] Closes#13948
* [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [ ] Tests added/passed
* [ ] Documentation updated. If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/terminal) and link it here: #xxx
* [ ] Schema updated.
* [ ] 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
## Validation Steps Performed
Manually tested.
`s/it's/its/`
Note that I didn't touch the several errors in the doc and doc/spec directories, since those seem to be dated and signed email excerpts, and I don't want to violate authorial integrity. Let me know if you would like me to fix those as well.
## References
p 57. Murray, L. (1824). English grammar. Philadelphia : E. T. Scott.
I skimmed several hundred usages of the word "it's" in the code. This actually wasn't as tiresome as it sounds, since many of the code comments in this repo are entertaining and educational — the adjectives do not _necessarily_ apply in that order, but do _possibly_ apply in that order.
Implements an initial version of #1571 as it has been specified, the
only big thing missing now is the possibility to add actions, which
depends on #6899.
Further upcoming spec tracked in #12584
Implemented according to [instructions by @zadjii-msft]. Mostly
relatively straightforward, but some notable details:
- In accordance with the spec, the counting/indexing of profiles is
based on their index in the json (so the index of the profile, not of
the entry in the menu).
- Resolving a profile name to an actual profile is done in a similar
fashion as how currently the `DefaultProfile` field is populated: the
`CascadiaSettings` constructor now has an extra `_resolve` function
that will iterate over all entries and resolve the names to instances;
this same function will compute all profile sets (the set of all
profiles from source "x", and the set of all remaining profiles)
- ~Fun~ fact: I spent two whole afternoons and evenings trying to add 2
classes (which turned out to be a trivial `.vcxproj` error), and then
managed to finish the entire rest of it in another afternoon and
evening...
## Validation Steps Performed
A lot of manual testing; as mentioned above I was not able to run any
tests so I could not add them for now. However, the logic is not too
tricky so it should be relatively safe.
Closes#1571
[instructions by @zadjii-msft]: https://github.com/microsoft/terminal/issues/1571#issuecomment-1184851000