Commit Graph

3665 Commits

Author SHA1 Message Date
Leonard Hecker 5db8af6277
Return success if ReadCharacterInput read >0 characters (#15122)
This is a regression caused by 599b550. If I'm reading `stream.cpp`
in cf87590 right, it returns `STATUS_SUCCESS` if `ReadCharacterInput`
read at least 1 character. I think? this PR makes the code behave
exactly equivalent. The old code is a bit of an "acquired taste"
so it's a bit hard to tell.

Closes #15116

## PR Checklist
* Run `more long_text_file.txt` in cmd
* Press Spacebar
* Scrolls down 
* Press Q
* Exits 
2023-04-05 22:52:04 +00:00
Dustin L. Howett 5f70920491
When unpackaged, isolate the monarch by the install path (#15118)
Unpackaged installations don't have the luxury of magic package
isolation to stop them from accidentally touching each other's monarchs.
We need to enforce that ourselves by making their monarch CLSIDs unique
per install.

We'll use a v5 UUID based on the install folder to unique them.

Closes #15117
2023-04-05 17:04:58 -05:00
Leonard Hecker 62448969b3
Upgrade clang-format to 15.0.7 (#15110)
Upgrading clang-format lead to a few changes in the formatting
of code inside macros. Apart from the upgrade, I've also spent
some time removing all options from .clang-format that are
redundant with `BasedOnStyle: Microsoft`.
2023-04-05 10:03:20 -05:00
Leonard Hecker ecb5e37a7d
Use new row primitives for ResizeTraditional (#15105)
This will allow us to share the same fundamental text insertion
logic for both `ResizeTraditional` and `Reflow`, because both
can be implemented with `ROW::CopyRangeFrom`. It also replaces
the `BufferAllocator` struct with a `_allocateBuffer` function
which will help us allocate scratch buffer rows in the future.

Closes #14696

## PR Checklist
* Disable reflow resize in conhost
* Print "zhwik8.txt" - a enwik8.txt equivalent of Chinese Wikipedia
* Run `color 80` in cmd
* Resize windows from 120 to 119 columns
* Wide glyphs disappear and are replaced with whitespace 
* Resizing the window to >120 columns adds gray whitespace 
2023-04-05 09:59:20 -05:00
James Holderness aea0477bda
Filter out control characters that don't do anything (#15075)
On a real VT terminal, most of the control characters that don't do
anything are supposed to be filtered out, and not written to the buffer.
Up to to now, though, we've only been filtering out `NUL`. This PR
extends our control processing to filter the remaining characters that
aren't supposed to be displayed.

We introduced filtering for the `NUL` control in PR #3015.

The are two special cases worth mentioning.

1. The `SUB` control's main purpose is to the cancel a control sequence
that is in progress, but it also needs to output an error character (a
reverse question mark) to the display.

2. The `DEL` control is typically filtered out, but when a 96-character
set is designated, it can sometimes be mapped to a printable glyph that
needs to be displayed.

## Validation Steps Performed

I've manually tested that all the controls that are meant to be filtered
out are no longer being displayed.

I've also extended the existing `NUL` unit test to cover the full set of
controls characters that are supposed to be filtered.

Closes #10786
2023-04-05 09:58:52 -05:00
Dustin L. Howett 06526cac0c
Remove our dependency on any CRT--AppX or forwarders (#15097)
The upgrade to Microsoft.UI.Xaml 2.8 was the last piece we needed to
break our dependency on the App CRT *and* any CRT whatsoever.
2023-04-04 16:11:12 -05:00
Leonard Hecker 9dfdf2afa3
Introduce til::linear_flat_set (#15089)
`til::linear_flat_set` is a primitive hash map with linear probing.
The implementation is slightly complicated due to the use of templates.
I've strongly considered just writing multiple copies of this class,
by hand since the code is indeed fairly trivial but ended up deciding
against it, because this templated approach makes testing easier.

This class is in the order of 10x faster than `std::unordered_map`.
2023-04-04 19:50:10 +02:00
Leonard Hecker 2a839d8c5a
Fix accuracy bugs around float/double/int conversions (#15098)
I noticed this bug while resizing my window on my 150% scale display.
Every 3 "snaps" of the window size, it would fail to resize the text
buffer. I found that this occurs, because we convert the swap chain
size from a float into a double, which converts my 597.333313 height
into 597.33331298828125, which then multiplied by 1.5 results in
895.999969482421875. If you just cast this to an integer, it'll
result in a height of 895px instead of the expected 896px.

This PR addresses the issue in two ways:
* Replace casts to integers with `lrint` or `floor`, etc.
* Remove many of the redundant double <> float conversions.

## PR Checklist
* Resizing my window always resizes the text buffer 
2023-04-04 11:33:17 -05:00
James Pack da995a014f
Enable holding ctrl to open the Terminal elevated from File Explorer
## Summary of the Pull Request
This pull request adds support for holding the control key and clicking
the Open Terminal Here context menu item to elevate the request.
## References and Relevant Issues
#14810

## Detailed Description of the Pull Request / Additional comments

## Validation Steps Performed

## PR Checklist
- [x] Closes #14810
- [ ] 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)

---------

Co-authored-by: Mike Griese <migrie@microsoft.com>
2023-04-04 16:24:33 +00:00
Leonard Hecker 47a17cf2d7
Replace statics in headers with inline constants (#15100)
C++ is a very well balanced and reasonable language, which is why
`static` inside classes means "shared between all instances", whereas
`static` outside of classes means "not shared between all .cpp files".

32 years after this problem was written onto parchment it was fixed with
the introduction of inline variables in C++17, which tell the compiler
to deduplicate variables the same way it deduplicates functions.
2023-04-04 10:19:20 -05:00
Mike Griese c0f14567f3
Use DIPs for the window bounds when tearing out (#15094)
Fixes a bug where you'd drag across the boundary and the new window
would be at the wrong size

related to #14957
2023-04-04 14:21:43 +00:00
Leonard Hecker 5de1fd9a7b
Introduce til::generational - a struct comparison helper (#15088)
It can be costly, difficult, or often impossible to compare two
instances of a struct. This little helper can simplify this.

The underlying idea is that changes in state occur much less often than
the amount of data that's being processed in between. As such, this
helper assumes that _any_ modification to the struct it wraps is a
state change. When you compare the modified instance with another
the comparison operator will then always return false. This makes
state changes potentially more costly, because more state might be
invalidated than was necessary, but on the other hand it makes both,
the code simpler and the fast-path (no state change) much faster.

For instance, let's look at the amount of data that represents a
user's chosen font: It encompasses the font family, size and weight,
font axes (a vector of tuples), dpi and cell height/width overrides.
Comparing all that data, every time the user changes anything, is
fairly complex to code and maintain and costly at runtime, even though
the user will change the only font very seldomly. Instead, we can
optimize for the common case of no font changes occuring and simply
assume that if any font related field changed, all fields changed.
This is exactly what `til::generational` does.
2023-04-04 15:47:36 +02:00
Mike Griese 17cf44fa71
Upgrade to MUX 2.8 (#15078)
Updates the Terminal to Microsoft.UI.Xaml v2.8. 

* MUX 2.8 adds a dependency on WebView2, so we need to include parts of it too.
* See https://github.com/microsoft/microsoft-ui-xaml/pull/7574 for why
we're adding the `.props`
* The TabView thing: 
> tl;dr: In >=MUX 2.7, we were updating our tab colors by doing a
"Visual State Dance", as I called it. We'd manually change the
`TabViewItem`'s VisualState to one that it wasn't in, then change it
back to the one it should be in. This seemingly re-applied the new
values of the brushes. However in 2.8, this seemingly didn't work
anymore!
  > 
  > So instead, we do a "Theme Dance", like so:
  > ```c++
  >   const auto& reqTheme = TabViewItem().RequestedTheme();
  >   TabViewItem().RequestedTheme(ElementTheme::Light);
  >   TabViewItem().RequestedTheme(ElementTheme::Dark);
  >   TabViewItem().RequestedTheme(reqTheme);
  >   ```
> This causes the `ThemeResource`s to be re-evaluated to the new values.
> We never got to the root cause of why this seems different in 2.8. It
literally makes no sense.
Closes #13495

Co-authored-by: Dustin L. Howett <duhowett@microsoft.com>
2023-04-03 22:40:46 +00:00
Dustin L. Howett 06174a9cb3
Format URLs for display when we show the tooltip (#15095)
This will reduce the incidence of confusables, RTL, and non-printables
messing with the display of the URL.
2023-04-03 21:22:25 +00:00
Leonard Hecker 0656afcf13
Expose hyperlink attributes in PaintBufferGridLines (#15090)
Rendering hyperlinks is unneccessarily complex at the moment, because
it requires you to implement `UpdateDrawingBrushes`, manually extract
the hyperlink flag from the given `TextAttribute` and save it until the
next call to `PaintBufferGridLines` which does not get that flag.
This isn't particularly clean as it assumes that `PaintBufferGridLines`
will be called after `UpdateDrawingBrushes` in the first place.

Instead, we can simply pass the hyperlink flag to `UpdateDrawingBrushes`
so that the renderers don't need to deal with this anymore.

## PR Checklist
* Hyperlinks show up with a dotted line 
* Hovering hyperlinks underline them 
2023-04-03 20:39:36 +02:00
Leonard Hecker 0d38d17299
Add a simple tool to test rendering functionality (#15091)
This tool augments `vttest` by adding some things that are specific to
us (like non-VT console attributes), and some things `vttest` is
seemingly too old for (like emojis). I'm planning to add more "pages"
of tests to the application in the future, whenever the need arises.
2023-04-03 13:21:22 -05:00
Leonard Hecker 7ddd98de0a
Fix warnings in til for an upcoming version of MSVC (#15087)
A trivial change. :)
2023-04-03 13:14:01 -05:00
Sam Meyer 0105807be2
Add pre-build PowerShell version check (#14947)
Two PowerShell scripts were added so that developers new to the project
know if they have the wrong version of PowerShell installed.

When first building Terminal, it would continuously fail, and I didn't
really know why. I'm new to both this project and to open source, so
when I saw an error message about "pwsh.exe" not being found I was
confused and didn't know what went wrong. What I didn't know is that
Windows PowerShell and PowerShell Core had different names for
their .exe files, and since I had the latest version of Windows
PowerShell installed, I figured that I was completely set. So, once I
realized that Windows PowerShell (what I had installed) is
powershell.exe and PowerShell Core (what I needed to have installed) is
pwsh.exe, I downloaded PowerShell Core, and it built without issue. So,
in order to help other newbies, I made two scripts, `CheckPSVersion` and
`WindowsCheckPSVersion`, which make sure that PowerShell Core 7.0.0+ is
installed, outputting an error telling the developer to download Core
7.0.0+ if they have Windows PowerShell but not Core. These scripts are
run pre-build courtesy of `Microsoft.Terminal.Settings.ModelLib.vcxproj`

## Validation Steps Performed
Building with both Windows PowerShell and PowerShell core: builds
perfectly, no issues.
Building with Windows PowerShell but not PowerShell core: build fails,
but a nice error prints out that reminds the user to download the
correct version of PowerShell core.

Closes #14797
2023-03-31 18:02:29 -05:00
Dustin L. Howett e6a3fa8d4e
Add "portable mode", where settings load from the install path (#15051)
This pull request implements portable mode for Windows Terminal, which
will make side by side deployment of different versions generally more
feasible.

Portable mode was specified in #15032.

There are three broad categories of changes in this PR:

1. Changes to settings loading.
2. A new indicator in the settings UI plus a link to the portable mode
   docs.
3. A new application display name, `Terminal (Portable)`, which users
   will hopefully include in their bug reports.

It's surprisingly small for how big a deal it is!

Related to #15034
Closes #1386
2023-03-31 17:12:00 -05:00
Mike Griese bbd4d1b1e4
Fix a crash in the rclick context menu (#15079)
Due to a bad merge a few commits back. This event should have had a
revoker.

Probably regressed in #14851
2023-03-31 13:49:12 -07:00
Dustin L. Howett 984b03ca33
[SPEC] Add a lightweight spec for Portable Mode (#15032) 2023-03-31 15:46:00 -05:00
Mike Griese 7b0aca444f
Enable tearing out tabs to create new windows (#14935)
_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.
2023-03-31 19:37:17 +00:00
Dustin L. Howett dd63a0590b
Add support for an unpackaged distribution of Terminal (#15034)
Since the removal of the Win10-specific variant of the Terminal MSIX in
#15031, there has been no officially-sanctioned (or even unofficially
tested!) way to get an unzippable double-click-runnable version of
Windows Terminal.

Due to a quirk in the resource loading system, an unpackaged
distribution of Terminal needs to ship all of XAML's resources and all
of is own resources in a single `resources.pri` file. The tooling to
support this is minimal, and we were previously just coasting by on
Visual Studio's generosity plus how the prerelease distribution of XAML
embedded itself into the consuming package.

This pull request introduces a build phase plus a supporting script (or
three) that produces a ZIP file distribution of Windows Terminal when
given a Terminal MSIX and an XAML AppX.

The three scripts are:

1. A script to merge any number of PRI files and/or PRI dump files (made
   with `makepri dump /dt detailed`)
2. A script that specifically merges XAML's resources with Terminal's.
   This is necessary because the XAML package emits a couple PRI
   resources into Terminal's resources _even when it is not
   co-packaged._ We need to remove the conflicting resources.
3. Finally, a script to take a WT and XAML distribution and combine them
   -- resources, files, everything -- and strip out the things that we
   don't need. This script is an all-in-one that calls the other two and
   produces a ZIP file at the end.

The final distribution is named after the PFN
(`Microsoft.WindowsTerminal`, or `...Preview` or `WindowsTerminalDev`),
the version number and the architecture. When expanded, it produces a
directory named `terminal-X.Y.Z.A` (version number.)

I've also added the build script to the release pipeline.

As a treat, this also produces an unpackaged distribution out of every
CI build... that way, contributors can download live deployable copies
of WT Unpackaged to test out their changes. Pretty cool.

Refs #1386
2023-03-30 16:38:10 -05:00
James Holderness fc95802531
Merge the LineFeed functionality into AdaptDispatch (#14874)
The main purpose of this PR was to merge the `ITerminalApi::LineFeed`
implementations into a shared method in `AdaptDispatch`, and avoid the
VT code path depending on the `AdjustCursorPosition` function (which
could then be massively simplified). This refactoring also fixes some
bugs that existed in the original `LineFeed` implementations.

## References and Relevant Issues

This helps to close the gap between the Conhost and Terminal (#13408).
This improves some of the scrollbar mark bugs mentioned in #11000.

## Detailed Description of the Pull Request / Additional comments

I had initially hoped the line feed functionality could be implemented
entirely within `AdaptDispatch`, but there is still some Conhost and
Terminal-specific behavior that needs to be triggered when we reach the
bottom of the buffer, and the row coordinates are cycled.

In Conhost we need to trigger an accessibility scroll event, and in
Windows Terminal we need to update selection and marker offsets, reset
pattern intervals, and preserve the user's scroll offset. This is now
handled by a new `NotifyBufferRotation` method in `ITerminalApi`.

But this made me realise that the `_EraseAll` method should have been
doing the same thing when it reached the bottom of the buffer. So I've
added a call to the new `NotifyBufferRotation` API from there as well.

And in the case of Windows Terminal, the scroll offset preservation was
something that was also needed for a regular viewport pan. So I've put
that in a separate `_PreserveUserScrollOffset` method which is called
from the `SetViewportPosition` handler as well.

## Validation Steps Performed

Because of the API changes, there were a number of unit tests that
needed to be updated:

- Some of the `ScreenBufferTests` were accessing margin state in the
`SCREEN_INFORMATION` class which doesn't exist anymore, so I had to add
a little helper function which now manually detects the active margins.

- Some of the `AdapterTest` tests were dependent on APIs that no longer
exist, so they needed to be rewritten so they now check the resulting
state rather than expecting a mock API call.

- The `ScrollWithMargins` test in `ConptyRoundtripTests` was testing
functionality that didn't previously work correctly (issue #3673). Now
that it's been fixed, that test needed to be updated accordingly.

Other than getting the unit tests working, I've manually verified that
issue #3673 is now fixed. And I've also checked that the scroll markers,
selections, and user scroll offset are all being updated correctly, both
with a regular viewport pan, as well as when overrunning the buffer.

Closes #3673
2023-03-30 13:32:54 -05:00
Leonard Hecker da3a33f3bc
Minor cleanups after #14745 (#14748)
#14745 removed the only user of `GetAugmentedOutputBuffer`.
2023-03-30 10:27:04 -05:00
Mike Griese 9514c1191a
Enable dragging tabs between windows (#14901)
_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.
2023-03-30 15:20:23 +00:00
Mike Griese 17a5b77335
Add support for moving panes and tabs between windows (#14866)
_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>
2023-03-30 14:37:53 +00:00
James Holderness 34aa6aa0d4
Update DECSC/DECRC to match the newer DEC terminals (#15054)
When saving and restoring the cursor position with origin mode enabled,
we originally matched the behavior of the early DEC terminals, which
stored the position as an absolute offset. But if the margin boundaries
were changed prior to restoring the position, that could result in the
cursor being outside the margins, potentially with negative coordinates.

Our implementation avoided that bug by clamping the coordinates back
into range, but that's not how DEC ultimately fixed the issue. Starting
with the VT420, they began using relative coordinates (i.e. relative to
the margin origin), so a restored position could never end up negative.
This PR updates our implementation to match that newer behavior.

## Validation Steps Performed

Thank to testing performed by @al20878, we know this was the algorithm
used on the VT420, VT520, and VT525, and I've manually confirmed that
our implementation now matches their behavior.

I've also updated the `CursorSaveRestore` unit test which previously
covered our clamping behavior - it's now being used to confirm that
we're correctly using relative offsets when restoring the cursor.

Closes #15048
2023-03-28 14:03:41 -05:00
Dustin L. Howett c7816fdb05
Add flexible virtualization rules for HKCU\Console\Startup (#15050)
[Flexible Virtualization] is a little more restrictive than
`unvirtualizedResources`, but it's more descriptive and stands a chance
of working on Windows 10.

This makes `unvirtualizedResources` actually work for us - we can tell
the system exactly which registry keys we want to use. This is required
for our registry writes to work on Windows 10.

[Flexible Virtualization]:
https://learn.microsoft.com/en-us/windows/msix/desktop/flexible-virtualization
2023-03-28 10:23:57 -05:00
Leonard Hecker d9efdae982
Fix font size of HTML clipboard contents (#15046)
This regression is caused by 0eff8c0. It previously said `.Y` here.
I went through the diff again and found no other width/height mistake.

Closes #14762
Closes #15043
2023-03-27 11:44:54 -05:00
Dustin L. Howett c4d029829a
Add a second way of detecting whether DefTerm is available (#15040)
This will become meaningful soon.
2023-03-24 17:21:50 -05:00
Leonard Hecker f20cd3a9d3
Add an efficient text stream write function (#14821)
This adds PR adds a couple foundational functions and classes to make
our TextBuffer more performant and allow us to improve our Unicode
correctness in the future, by getting rid of our dependence on
`OutputCellIterator`. In the future we can then replace the simple
UTF-16 code point iterator with a proper grapheme cluster iterator.

While my focus is technically on Unicode correctness, the ~4x VT
throughput increase in OpenConsole is pretty nice too.

This PR adds:
* A new, simpler ROW iterator (unused in this PR)
* Cursor movement functions (`NavigateToPrevious`, `NavigateToNext`)
  They're based on functions that align the cursor to the start/end
  of the _current_ cell, so such functions can be added as well.
* `ReplaceText` to write a raw string of text with the possibility to
  specify a right margin.
* `CopyRangeFrom` will allow us to make reflow much faster, as it's able
  to bulk-copy already measured strings without re-measuring them.

Related to #8000

## Validation Steps Performed
* enwik8.txt, zhwik8.txt, emoji-test.txt, all work with proper
  wide glyph reflow at the end of a row 
* This produces "a 咪" where only "a" has a white background:
  ```sh
  printf '\e7こん\e8\x1b[107ma\x1b[m\n'
  ```
* This produces "abん":
  ```sh
  stdbuf -o0 printf '\x1b7こん\x1b8a'; printf 'b\n'
  ```
* This produces "xy" at the end of the line:
  ```sh
  stdbuf -o0 printf '\e[999C\bこ\bx'; printf 'y\n'
  ```
* This produces red whitespace followed by "こ " in the default
  background color at the end of the line, and "ん" on the next line:
  ```sh
  printf '\e[41m\e[K\e[m\e[999C\e[2Dこん\n'
  ```
2023-03-24 17:20:53 -05:00
Dustin L. Howett f5e9e8ea77
Consolidate our MSIX distribution back down to one package (#15031)
We ship a separate package to Windows 10, which contains a copy of XAML
embedded in it, because of a bug in activating classes from framework
packages while we're elevated.

We did this to avoid wasting disk space on Windows 11 installs (which is
critical given that we're preinstalled in the Windows image.)

The fix for this issue was released in a servicing update in April 2022.
Thanks to KB5011831, we no longer need this workaround!

And finally, this means that we no longer need to depend on a copy of
"pre-release" XAML. We only did that because it would copy all of its
assets into our package.

Introduced in #12560
Closes #14106
Closes (discussion) #14981
Reverts #14660
2023-03-24 08:31:17 -05:00
Mike Griese 36c6b7748e
Clean up more warnings (#15039)
* These `Icon` bindings were to `Profile`s which aren't Observable, but
it also doesn't matter
* More c# warnings

hopefully we'll just jump straight to real errors now.
2023-03-24 08:30:58 -05:00
Mike Griese b34444f40a
Fix `wt -w _quake` by not throwing when setting the window name (#15030)
If we get initialized with a window name, this will be called before
XAML is stood up, and constructing a PropertyChangedEventArgs will
throw. So don't.


Regressed in #14843 

Related to #5000, #14957
2023-03-24 08:30:37 -05:00
Dustin L. Howett f06cd1759f
VsDevCmdGenerator: respect the user's startingDirectory (#15035)
The PowerShell equivalent was added in the initial pull request, #7774.

Closes #13721
2023-03-23 18:14:48 -05:00
James Holderness 0f7d1f4568
Add support for the Presentation State reports (#14998)
This PR introduces two new sequences, `DECRQPSR` and `DECRSPS`, which
provide a way for applications to query and restore the presentation
state reports. This includes the tab stop report (`DECTABSR`) and the
cursor information report (`DECCIR`). 

One part of the cursor information report contains the character set
designations and mapped G-sets. But we weren't tracking that data in a
way that could easily be reported, so I needed to do some refactoring in
the `TerminalOutput` class to make that accessible.

Other than that, the rest was fairly straightforward. It was just a
matter of packaging up all the information into the correct format for
the returned `DCS` string, and in the case of the restore operations,
parsing the incoming data and applying the new state. 

## Validation Steps Performed

Thanks to @al20878, we were able to test these operations on a real
VT525, and I've manually verified that our implementation matches that
behavior. I've also added some unit tests covering both reports.

Closes #14984
2023-03-23 17:46:17 -05:00
James Holderness 7a2e4f8d9b
Fix DECCRA when copying from a double-width line (#15026)
When a `DECCRA` operation is copying content that spans a double width
line, it's possible that some range of the bounding rectangle will be
off-screen, and that range is not supposed to be copied. However, the
code checking for off-screen positions was using incorrect coordinates,
so we would mistakenly copy content that shouldn't be copied, and drop
content that should have been copied. This PR fixes that.

## References and Relevant Issues

This was a regression introduced in PR #14650 when fixing an issue with
horizontal scrolling of DBCS characters.

## Validation Steps Performed

I manually verified this fixes the test case in #15019, and I've also
added a unit test that replicates that case.

Closes #15019
2023-03-22 12:37:08 -05:00
Alex Noble 2acdc9d7e2
Add options to enable and disable read only mode (#14995)
## Summary of the Pull Request
PR adds functionality to enable or disable readOnly mode within panes.
This functionality is different to toggling as if you call the same
functionality twice, it will not toggle between states.

## References and Relevant Issues
- Closes https://github.com/microsoft/terminal/issues/14415
- Documentation https://github.com/MicrosoftDocs/terminal/pull/645

## Validation Steps Performed
- Checked readOnly is enabled when command triggered
- Checked readOnly is enabled when command triggered while read only
already enabled
- Checked readOnly is disabled when command triggered while read only is
enabled
- Checked readOnly stays disabled when command triggered while read only
is disabled
- Checked above with multiple tabs and split panes

## PR Checklist
- [ ] Closes #14415 
- [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:
https://github.com/MicrosoftDocs/terminal/pull/645
- [X] Schema updated (if necessary)

---------

Co-authored-by: Mike Griese <migrie@microsoft.com>
2023-03-22 12:32:56 -05:00
Mike Griese f3a722e0e9
Introduce a ContentManager helper (#14851)
## 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.
2023-03-22 12:11:44 -05:00
Dustin L. Howett e0046a4cca
Remove useRegExe and add rescap:unvirtualizedResources (#15028)
Due to a limitation in the Windows App Installer UI, Terminal had to
shell out to `reg.exe` to write the Delegation registry keys. The team
in charge of AppInstaller lifted that (once by-policy) limitation.

Therefore, we can remove our BODGY workaround.
2023-03-21 15:18:21 -05:00
Dustin L. Howett 5a34d92cb5
winget.yml: switch to manually using wingetcreate (#15023)
It was brought to my attention that we should be more restrictive in
which tasks we ovver a GitHub token to. Sorry!

With thanks to sitiom for the version parsing and the magic GitHub
action syntax incantation for determining what is a prerelease.
2023-03-20 17:38:20 -05:00
Dustin Howett e1079d8f55
winget: use the correct fork-user 2023-03-20 11:15:27 -05:00
Mike Griese b9248fa903
One process to rule them all (#14843)
## 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
```
2023-03-17 17:59:35 -05:00
sitiom bee22f3ec8
Add a Winget Releaser workflow (#14965)
[The winget-releaser action] automatically generates manifests for the
[Winget Community Repository] and submits them.

I suggest adding Dependabot to keep the action up to date. There were
many cases where the action was failing due to an outdated version.

Closes #14795

[The winget-releaser action]:
https://github.com/vedantmgoyal2009/winget-releaser
[Winget Community Repository]: https://github.com/microsoft/winget-pkgs
2023-03-17 17:57:42 -05:00
Dustin L. Howett b6bb3e0a80
Enable the Hybrid CRT for all C++ projects (#15010)
The less we need the C++ runtime, the better.

I measured this as growing our package by a fair amount...
but less than the size of XamlHost and all the forwarders combined.

Reducing our dependency surface makes us easier to deploy and more
reliable.

_as of 1.17 (2022-10)_

| **File**                | **Before** | **After** |        **Delta** |
| ----------------------- | ----------:| ---------:| ----------------:|
| `OpenConsole`           |  1,273,344 | 1,359,360 |   +86,016 (84kb) |
| `TerminalApp`           |  2,037,248 | 2,120,704 |   +83,456 (82kb) |
| `TerminalControl`       |  1,412,608 | 1,502,720 |   +90,112 (88kb) |
| `TerminalSettingsModel` |  1,510,912 | 1,621,504 | +110,592 (108kb) |
| `wt`                    |     97,280 |   122,368 |   +25,088 (25kb) |
| `WindowsTerminal`       |    508,928 |   575,488 |   +66,560 (65kb) |
| **MSIX Overall**        |  6,488,301 | 6,799,017 | +310,716 (303kb) |
2023-03-17 17:12:32 -05:00
Mike Griese c5c15e86f3
Clearly differentiate running elevated vs. drag/drop breaking (#14946)
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`
2023-03-17 17:01:37 -05:00
Leonard Hecker 00af187a97
Fix console aliases not working (#14991)
#14745 contains two regressions related to console alias handling:
* When `ProcessAliases` expands the backup buffer into (an) aliased
  command(s) it changes the `_bytesRead` field of `COOKED_READ_DATA`,
  requiring us to re-read it and reconstruct the `input` string-view.
* Multiline aliases are read line-by-line whereas #14745 didn't treat
  them any different from regular single-line inputs.

## Validation Steps Performed
In `cmd.exe` run
```
doskey test=echo foo$Techo bar$Techo baz
test
```
The output should look exactly like this:
```
C:\>doskey test=echo foo$Techo bar$Techo baz

C:\>test
foo

C:\>bar

C:\>baz

C:\>
```
2023-03-17 13:43:44 -07:00
James Holderness 2810155046
Add support for querying the DECAC settings (#14990)
This PR adds support for querying the color indices set by the `DECAC`
control, using the existing `DECRQSS` implementation.

## References and Relevant Issues

The initial `DECRQSS` support was added in PR #11152.
The `DECAC` functionality was added in PR #13058, but at the time we
didn't know how to format the associated `DECRQSS` query.

## Detailed Description of the Pull Request / Additional comments

For most `DECRQSS` queries, the setting being requested is identified by
the final characters of its escape sequence. However, for the `DECAC`
settings, you also need to include a parameter value, to indicate which
color item you're querying.

This meant we needed to extend the `DECRQSS` parser, so I also took this
opportunity to ensure we correctly parsed any parameter prefix chars. We
don't yet support any setting requiring a prefix, but this makes sure we
don't respond incorrectly if an app does query such a setting.

## Validation Steps Performed

Thanks to @al20878, we've been able to test how these queries are parsed
on a real VT525 terminal, and I've manually verified our implementation
matches that behavior.

I've also extended the existing `DECRQSS` unit test to confirm that we
are responding to the `DECAC` queries as expected.

Closes #13091
2023-03-17 14:16:47 -05:00
Mike Griese 5c9f756891
Properly configure the project dependencies for TerminalAzBridge (#15008)
I don't think this is the resolution for #14581, but this can't hurt. These deps were using the wrong GUIDs
2023-03-17 13:59:35 -05:00