114 Commits

Author SHA1 Message Date
Mike Griese
0cbde94e4b
Show number of search results & positions of hits in scrollbar (#14045)
This is a resurrection of #8588. That PR became painfully stale after
the `ControlCore` split. Original description:

> ## Summary of the Pull Request
> This is a PoC for:
> * Search status in SearchBox (aka number of matches + index of the
current match)
> * Live search (aka search upon typing)
> ## Detailed Description of the Pull Request / Additional comments
> * Introduced this optionally (global setting to enable it)
> * The approach is following:
>   * Every time the filter changes, enumerate all matches
>   * Upon navigation just take the relevant match and select it
> 

I cleaned it up a bit, and added support for also displaying the
positions of the matches in the scrollbar (if `showMarksOnScrollbar` is
also turned on).

It's also been made SUBSTANTIALLY easier after #15858 was merged.

Similar to before, searching while there's piles of output running isn't
_perfect_. But it's pretty awful currently, so that's not the end of the
world.

Gifs below.

* closes #8631 (which is a bullet point in #3920)
* closes #6319


Co-authored-by: Don-Vito <khvitaly@gmail.com>

---------

Co-authored-by: khvitaly <khvitaly@gmail.com>
2023-09-05 16:23:09 -05:00
Leonard Hecker
cd80f3c764
Use ICU for text search (#15858)
The ultimate goal of this PR was to use ICU for text search to
* Improve Unicode support
  Previously we used `towlower` and only supported BMP glphs.
* Improve search performance (10-100x)
  This allows us to search for all results in the entire text buffer
  at once without having to do so asynchronously.

Unfortunately, this required some significant changes too:
* ICU's search facilities operate on text positions which we need to be
  mapped back to buffer coordinates. This required the introduction of
  `CharToColumnMapper` to implement sort of a reverse-`_charOffsets`
  mapping. It turns text (character) positions back into coordinates.
* Previously search restarted every time you clicked the search button.
  It used the current selection as the starting position for the new
  search. But since ICU's `uregex` cannot search backwards we're
  required to accumulate all results in a vector first and so we
  need to cache that vector in between searches.
* We need to know when the cached vector became invalid and so we have
  to track any changes made to `TextBuffer`. The way this commit solves
  it is by splitting `GetRowByOffset` into `GetRowByOffset` for
  `const ROW` access and `GetMutableRowByOffset` which increments a
  mutation counter on each call. The `Search` instance can then compare
  its cached mutation count against the previous mutation count.

Finally, this commit makes 2 semi-unrelated changes:
* URL search now also uses ICU, since it's closely related to regular
  text search anyways. This significantly improves performance at
  large window sizes.
* A few minor issues in `UiaTracing` were fixed. In particular
  2 functions which passed strings as `wstring` by copy are now
  using `wstring_view` and `TraceLoggingCountedWideString`.

Related to #6319 and #8000

## Validation Steps Performed
* Search upward/downward in conhost 
* Search upward/downward in WT 
* Searching for any of ß, ẞ, ss or SS matches any of the other 
* Searching for any of Σ, σ, or ς matches any of the other 
2023-08-24 22:56:40 +00:00
Mike Griese
0f61b5f97d
Remove the FontSizeChanged event from TermControl (#15867)
I originally just wanted to close #1104, but then discovered that hey,
this event wasn't even used anymore. Excerpts of Teams convo:

* [Snap to character grid when resizing window by mcpiroman · Pull
Request #3181 · microsoft/terminal
(github.com)](https://github.com/microsoft/terminal/pull/3181/files#diff-d7ca72e0d5652fee837c06532efa614191bd5c41b18aa4d3ee6711f40138f04c)
added it to Tab.cpp
  * where it was added 
  * which called `pane->Relayout` which I don't even REMEMBER
* By [Add functionality to open the Settings UI tab through openSettings
by leonMSFT · Pull Request #7802 · microsoft/terminal
(github.com)](https://github.com/microsoft/terminal/pull/7802/files#diff-83d260047bed34d3d9d5a12ac62008b65bd6dc5f3b9642905a007c3efce27efd),
there was seemingly no FontSizeChanged in Tab.cpp (when it got moved to
terminaltab.cpp)
 

> `Pane::Relayout` functionally did nothing because sizing was switched
 to `star` sizing at some point in the past, so it was just deleted.

From [Misc pane refactoring by Rosefield · Pull Request #11373 ·
microsoft/terminal](https://github.com/microsoft/terminal/pull/11373/files#r736900998)

So, great. We can kill part of it, and convert the rest to a
`TypedEvent`, and get rid of `DECLARE_` / `DEFINE_`.

`ScrollPositionChangedEventArgs` was ALSO apparently already promoted to
a typed event, so kill that too.
2023-08-24 19:53:03 +00:00
Mike Griese
3afe7a8d11
Add a useCommandline property to the suggestions action (#15027)
_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
2023-08-15 15:39:36 +00:00
Mike Griese
e5a430ff68
Add support for opening the Suggestions UI with recent commands (#14943)
This adds support for a new action, `showSuggestions`, as described in
#14864. This adds just one `source` currently, `recentCommands`. This
requires shell integration to be enabled in the shell to work properly.
When it is enabled, activating that action will invoke the suggestions
UI as a palette, populated with `sendInput` actions for each of the
user's recent commands.

* These don't persist across reboots. 
* These are per-control.

There's mild plans to remedy that in a follow-up, though that needs a
bit more design consideration.

Closes #14779
2023-08-15 08:48:09 -05:00
Mike Griese
b556594793
Add an experimental setting for moving the cursor with the mouse (#15758)
## Summary of the Pull Request

This adds a new experimental per-setting to the terminal. 

```ts
"experimental.repositionCursorWithMouse": bool
```

When:
* the setting is on 
* AND you turn on shell integration (at least `133;B`)
* AND you click is somewhere _after_ the "active command" mark

we'll send a number of simulated keystrokes to the terminal based off
the number of cells between the place clicked and where the current
mouse cursor is.


## PR Checklist
- [ ] Related to #8573. I'm not marking as _closed_, because we should
probably polish this before we close that out. This is more a place to
start.

## Detailed Description of the Pull Request / Additional comments

There was a LOT of discussion in #8573. This is kinda a best effort
feature - it won't always work, but it should improve the experience
_most of the time_. We all kinda agreed that as much as the shell
probably should be responsible for doing this, there's myriad reasons
that won't work in practicality:
* That would also disable selection made by the terminal. That's a hard
sell.
* We'd need to invent some new mouse mode to support
click-to-reposition-but-drags-to-select-I-don't-want
* We'd then need shells to adopt that functionality.

And eventually settled that this was the least horrifying comprimise.

This has _e d g e  c a s e s_: 
* Does it work for wrapped lines? Well, kinda okay actually.
* Does it work for `vim`/`emacs`? Nope. 
* Does it work for emoji/wide glyphs? I wouldn't expect it to! I mean,
emoji input is messed up anyways, right?
* Other characters like `ESC` (which are rendered by the shell as two
cells "^[")? Nope.
* Does it do selections? Nope.
* Clicking across lines with continuation prompts? Nope.
* Tabs? Nope.
* Wraps within tmux/screen? Nope.


https://github.com/xtermjs/xterm.js/blob/master/src/browser/input/MoveToCell.ts
has probably a more complete implementation of how we'd want to generate
the keypresses and such.
2023-08-14 07:37:13 -05:00
Mike Griese
a0c88bb511
Add Suggestions UI & experimental shell completions support (#14938)
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?
2023-08-14 05:46:42 -05:00
Leonard Hecker
5b44476048
Replace IInputEvent with INPUT_RECORD (#15673)
`IInputEvent` makes adding Unicode support to `InputBuffer` more
difficult than necessary as the abstract class makes downcasting
as well as copying quite verbose. I found that using `INPUT_RECORD`s
directly leads to a significantly simplified implementation.

In addition, this commit fixes at least one bug: The previous approach
to detect the null key via `DoActiveModifierKeysMatch` didn't work.
As it compared the modifier keys as a bitset with `==` it failed to
match whenever the numpad key was set, which it usually is.

## Validation Steps Performed
* Unit and feature tests are 
2023-08-11 14:06:08 +00:00
Mike Griese
b4042eaaf0
Let marks be cleared by clear (and friends) (#15686)
Move scroll marks to `TextBuffer`, so they can be cleared by
EraseInDisplay and EraseScrollback.

Also removes the namespacing on them.

## References and Relevant Issues
* see also #11000 and #15057
* Resize/Reflow _doesn't_ work yet and I'm not attempting this here. 

## Validation Steps Performed

* `cls` works
* `Clear-Host` works
* `clear` works
* the "Clear buffer" action works
* They work when there's marks above the current viewport, and clear the
scrollback
* they work if you clear multiple "pages" of output, then scroll back to
where marks previously were
* resizing doesn't totally destroy the marks

Closes #15426
2023-07-18 21:10:57 +00:00
Leonard Hecker
6a26fd68c4
Fix race conditions in ControlCore (#15334)
`ControlCore` contained two bugs:
* Race condition on access of the 3 throttled funcs which may now
  be `reset()` during tear out
* The `ScrollPositionChanged` event emitter was written incorrectly
  and would emit the event from the background thread without
  throttling during tear out
2023-05-12 20:11:22 +00:00
Mike Griese
ae7595b8e1
Add til::property and other winrt helpers (#15029)
## Summary of the Pull Request

This was a fever dream I had last July. What if, instead of `WINRT_PROPERTY` magic macros everywhere, we had actual templated versions you could debug into. 

So instead of 

```c++
WINRT_PROPERTY(bool, Deleted, false);
WINRT_PROPERTY(OriginTag, Origin, OriginTag::None);
WINRT_PROPERTY(guid, Updates);
```

you'd do 

```c++
til::property<bool> Deleted{ false };
til::property<OriginTag> Origin{ OriginTag::None };
til::property<guid> Updates;
```

.... and then I just kinda kept doing that. So I did that for `til::event`.

**AND THEN LAST WEEK**

Raymond Chen was like: ["this is a good idea"](https://devblogs.microsoft.com/oldnewthing/20230317-00/?p=107946)

So here it is. 

## Validation Steps Performed
Added some simple tests.

Co-authored-by: Leonard Hecker <lhecker@microsoft.com>
2023-05-03 12:41:36 -05:00
Mike Griese
0d6642ac6d
(A better) Refactoring of how connection restarting is handled (#15240)
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 #14060

Closes #14327

Obsoletes #14548
2023-04-28 20:01:12 +00:00
Leonard Hecker
adbe4a0d0c
Fix missing call to UpdateViewport::UpdateViewport during tearout (#15175)
This bug causes AtlasEngine to render buffer contents with an incorrect
`cellCount`, which may either cause it to draw the contents only
partially, or potentially access the TextBuffer contents out of bounds.

`EnablePainting` sets the `_viewport` to the current viewport for some
unfortunate (and quite buggy/incorrect) caching purposes, which causes
`_CheckViewportAndScroll()` to think that the viewport hasn't changed
in the new window. We can ensure `_CheckViewportAndScroll()` works
by also setting `_forceUpdateViewport` to `true`.

Part of #14957

## PR Checklist
* Tear out a tab from a smaller window to a larger window
* Renderer contents adept to the larger window size 

---------

Co-authored-by: Mike Griese <migrie@microsoft.com>
Co-authored-by: Dustin L. Howett <duhowett@microsoft.com>
2023-04-25 16:32:44 -05:00
Mike Griese
06dc975a0e
Switch to function pointers (#15233)
Apparently, `std::function` is bad and we should feel bad. I friggen
hate the c++ function pointer syntax, but [I do what I'm
told](https://getyarn.io/yarn-clip/85c318d8-f4a7-4da6-ae20-23d7b737e71c)

I missed this comment in #15020. Sorry!
2023-04-25 20:25:30 +00:00
Mike Griese
0d1540bbd2
Add buttons for selecting commands, output to context menu (#15020)
Adds a "Select command" and a "Select output" entry to the right-click
context menu when the user has shell integration enabled. This lets the
user quickly right-click on a command and select the entire commandline
or all of its output.

This was a "I'm waiting for reviews" sorta idea. Seemed like a
reasonable combination of features. Related to #13445, #11000.

Tested manually.

---------

Co-authored-by: Dustin L. Howett <duhowett@microsoft.com>
2023-04-25 14:43:49 +00:00
Mike Griese
0e86ce559e
Add the ability to select a whole command (or its output) (#14807)
Adds two new commands, `selectOutput` and `selectCommand`. These don't
do much without shell integration enabled, unfortunately. If you do
enable it, however, you can use these commands to quickly navigate the
history to select whole commands (or their output).

Some sample JSON:

```json
        { "keys": "ctrl+shift+<", "command": { "action": "selectCommand", "direction": "prev" } },
        { "keys": "ctrl+shift+>", "command": { "action": "selectCommand", "direction": "next" } },
        { "keys": "ctrl+shift+[", "command": { "action": "selectOutput", "direction": "prev" } },
        { "keys": "ctrl+shift+]", "command": { "action": "selectOutput", "direction": "next" } },
```

**Demo gifs** in
https://github.com/microsoft/terminal/issues/4588#issuecomment-1352042789

closes #4588

Tested manually. 

<details>
<summary>CMD.exe user? It's dangerous to go alone! Take this.</summary>

Surely, there's a simpler way to do it, this is adapted from my own
script.

```cmd
prompt $e]133;D$e\$e]133;A$e\$e\$e]9;9;$P$e\$e[30;107m[$T]$e[97;46m$g$P$e[36;49m$g$e[0m$e[K$_$e[0m$e[94m%username%$e[0m@$e[32m%computername%$e[0m$G$e]133;B$e\
```

</details>
2023-04-20 07:34:58 -05: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
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
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
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
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
Dustin L. Howett
2cd280eeef
Move to CppWinRT 2.0.230207.1 (#14869)
Interesting things we could do after this:
- remove all `InitializeComponent` calls - they do it automatically
- have some Clang support (!)
- use `std::optional`<->`IReference` automatic binding
- use `std::format` support (!) for json/uri/hostname/http stuff/all
`IStringable`s
- potentially move to `/await:strict` for C++20 coroutines

I've also fixed up a couple ambiguities introduced by this change.
2023-02-17 16:19:47 -08:00
Leonard Hecker
b6e6dd861d
Implement cell size customizations (#14255)
Does what it says in the title. After this commit you can customize the height
and width of the terminal's cells. This commit supports parts of CSS'
`<length-percentage>` data type: Font-size relative sizes as multiples (`1.2`),
percentage (`120%`), or advance-width relative (`1.2ch`), as well as absolute
sizes in CSS pixels (`px`) or points (`pt`).

This PR is neither bug free in DxEngine, nor in AtlasEngine.
The former fails to implement glyph advance corrections (for instance #9381),
as well as disallowing glyphs to overlap rows. The latter has the same
overlap issue, but more severely as it tries to shrink glyphs to fit in.

Closes #3498
Closes #14068

## Validation Steps Performed
* Setting `height` to `1` creates 12pt tall rows 
* Setting `height` to `1ch` creates square cells 
* Setting `width` to `1` creates square cells 
* Setting `width` or `height` to `Npx` or `Npt` works 
* Trailing zeroes are trimmed properly during serialization 
* Patching the PR to allow >100 line heights and entering "100.123456"
  displays 6 fractional digits 
2023-02-14 22:42:14 +01:00
grammar-police
06baead9ea
Minor grammar fix (#14614)
`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 &mdash; the adjectives do not _necessarily_ apply in that order, but do _possibly_ apply in that order.
2023-01-09 19:25:03 +00:00
Mike Griese
a5c5b8a50e
Enable vintage opacity on Windows 10 (#14481)
This reverts #11372 and #11285, and brings #11180 to everyone, now that MSFT:37879806 has been serviced to everyone in [KB5011831](https://support.microsoft.com/en-gb/topic/april-25-2022-kb5011831-os-builds-19042-1682-19043-1682-and-19044-1682-preview-fe4ff411-d25a-4185-aabb-8bc66e9dbb6c)[1].

I tested this on my home Win10 laptop that's super old and doesn't have a functioning clock, but it does have that update at the very least. 

I don't think we had an issue tracking this?

[1]: I'm pretty sure about this at least
2022-12-09 20:50:56 +00:00
Steve Otteson
c0e4689e77
When the terminal has exited, ctrl+D to close pane, Enter to restart terminal (#14060)
When a terminal process exits (successful or not) and the profile isn't
set to automatically close the pane, a new message is displayed:

You can now close this terminal with ^D or Enter to restart.

Ctrl+D then is able to close the pane and Enter restarts it.

I originally tried to do this at the ConptyConnection layer by changing
the connection state from Failed to Closed, but then that didn't work
for the case where the process exited successfully but the profile isn't
set to exit automatically. So, I added an event to
ControlCore/TermControl that Pane watches. ControlCore watches to see if
the input is Ctrl+D (0x4) and if the connection is closed or failed, and
then raises the event so that Pane can close itself. As it turned out, I
think this is the better place to have the logic to watch for the Ctrl+D
key. Doing it at the ConptyConnection layer meant I had to parse out the
key from the escaped text passed to ConptyConnection::WriteInput.

## Validation Steps Performed
Tried adding lots of panes and then killing the processes outside of
Terminal. Each showed the new message and I could close them with Ctrl+D
or restart them with Enter. Also set a profile to never close
automatically to make sure Ctrl+D would work when a process exits
successfully.

Closes #12849 
Closes #11570
Closes #4379
2022-12-08 13:29:34 +00:00
Leonard Hecker
4d9a266c12
Merge IBaseData, IRenderData and IUiaData (#14427)
My goal is to make `IRenderData` "snapshottable", so that we
can render a frame of text without holding the console lock.
To facilitate this, this commit merges our 3 data interfaces
into one. It includes no actual changes apart from renames.
2022-12-05 19:38:31 +00:00
Leonard Hecker
4bbe3a388c
Clean up CodepointWidthDetector (#14396)
My long-term plan is to replace the `CodepointWidth` enum with a simple integer
return value that indicates the amount of columns a codepoint is wide.
This is necessary so that we can return 0 for ZWJs (zero width joiners).

This initial commit represents a cleanup effort around `CodepointWidthDetector`.
Since less code runs faster, this change has the nice side-effect of running
roughly 5-10% faster across the board. It also drops the binary size by ~1.2kB.

## Validation Steps Performed
* `CodepointWidthDetectorTests` passes 
* U+26bf (``"`u{26bf}"`` inside pwsh) is a wide glyph
  in OpenConsole and narrow one in Windows Terminal 
2022-12-01 22:23:25 +00:00
Mike Griese
37aa29545b
Implement the rest of the FTCS marks (#14341)
As noted in #11000.

This adds support for `FTCS_COMMAND_START`, `FTCS_COMMAND_EXECUTED` and `FTCS_COMMAND_FINISHED`, which allow a shell to more clearly markup parts of the buffer. 

As a trick, I'm also making the `experimental.autoMarkPrompts` setting act like a `FTCS_COMMAND_EXECUTED` if it comes after a `FTCS_COMMAND_START`. This lets the whole sequence work for cmd.exe (which wouldn't otherwise be possible).

* My cmd prompt
  ```bat
  PROMPT $e]133;D$e\$e]133;A$e\$e]9;9;$P$e\[$T]$e[97;46m%_seperator%$P$e[36;49m%_seperator%$e[0m$_$e[0m%_GITPROMPT%$e[94m%username%$e[0m@$e[32m%computername%$e[0m$G$e]133;B$e\
  ```
* pwsh profile, heavily cribbed from vscode
  ```pwsh

	$Global:__LastHistoryId = -1
	
	function Global:__Terminal-Get-LastExitCode {
	  if ($? -eq $True) {
	    return 0
	  }
	  # TODO: Should we just return a string instead?
	  # return -1
	  if ("$LastExitCode" -ne "") { return $LastExitCode }
	  return -1
	}
	
	function prompt {
	  # $gle = $LastExitCode
	
	
	  $gle = $(__Terminal-Get-LastExitCode);
	  $LastHistoryEntry = $(Get-History -Count 1)
	  # Skip finishing the command if the first command has not yet started
	  if ($Global:__LastHistoryId -ne -1) {
	    if ($LastHistoryEntry.Id -eq $Global:__LastHistoryId) {
	      # Don't provide a command line or exit code if there was no history entry (eg. ctrl+c, enter on no command)
	      $out += "`e]133;D`a"
	    } else {
	      # Command finished exit code
	      # OSC 633 ; D [; <ExitCode>] ST
	      $out += "`e]133;D;$gle`a"
	    }
	  }
	
	
	  $loc = $($executionContext.SessionState.Path.CurrentLocation);
	  # IMPORTANT: Make sure there's a printable charater _last_ in the prompt.
	  # Otherwise, PSReadline is gonna use the terminating `\` here and colorize
	  # that if it detects a syntax error
	  $out += "`e]133;A$([char]07)";
	  $out += "`e]9;9;`"$loc`"$([char]07)";
	  $out += "PWSH $loc$('>' * ($nestedPromptLevel + 1)) ";
	  $out += "`e]133;B$([char]07)";
	
	  $Global:__LastHistoryId = $LastHistoryEntry.Id
	
	  return $out
	}
  ```



* Doesn't close any issues, because this was always just an element in #11000
* I work here
* From FHL code
2022-12-01 22:22:07 +00:00
Leonard Hecker
0eff8c06e3
Clean up til::point/size/rect member usage (#14458)
This is a follow-up of #13025 to make the members of `til::point/size/rect`
uniform and consistent without the use of `unions`. The only file that has
any changes is `src/host/getset.cpp` where an if condition was simplified.

## Validation Steps Performed
* Host unit tests 
* Host feature tests 
* ControlCore feature tests 
2022-12-01 00:40:00 +00:00
Leonard Hecker
8f346a7158
Rewrite Utf16Parser (#14417)
This commit replaces `Utf16Parser` with `<til/unicode.h>` which includes:
* `til::utf16_iterator` as a replacement for `Utf16Parser::Parse`
* `til::utf16_next` as a replacement for `Utf16Parser::ParseNext`

This fixes 2 bugs with `Utf16Parser`:
* Swallowing invalid surrogate pairs instead of turning them into U+FFFD.
* `std::vector<std::vector<wchar_t>>`. It's now >12000% faster.

## Validation Steps Performed
* New unit tests pass 
* Searching for narrow/wide characters in conhost works 
2022-11-23 21:13:36 +00:00
Ian O'Neill
6b4b63b18a
Ensure reading the buffer content actually returns the content (#14379)
## Summary of the Pull Request
Ensures that reading the buffer content actually returns the content.

## References
Regressed in #13626.

## PR Checklist
* [x] Closes #14378
* [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [x] Tests added/passed

## Validation Steps Performed
Added a test.
2022-11-12 23:31:10 +00:00
Leonard Hecker
a01500f051
Rewrite ROW to be Unicode capable (#13626)
This commit is a from-scratch rewrite of `ROW` with the primary goal to get
rid of the rather bodgy `UnicodeStorage` class and improve Unicode support.

Previously a 120x9001 terminal buffer would store a vector of 9001 `ROW`s
where each `ROW` stored exactly 120 `wchar_t`. Glyphs exceeding their
allocated space would be stored in the `UnicodeStorage` which was basically
a `hashmap<Coordinate, String>`. Iterating over the text in a `ROW` would
require us to check each glyph and fetch it from the map conditionally.
On newlines we'd have to invalidate all map entries that are now gone,
so for every invalidated `ROW` we'd iterate through all glyphs again and if
a single one was stored in `UnicodeStorage`, we'd then iterate through the
entire hashmap to remove all coordinates that were residing on that `ROW`.
All in all, this wasn't the most robust nor performant code.

The new implementation is simple (from a design perspective):
Store all text in a `ROW` in a regular string. Grow the string if needed.
The association between columns and text works by storing character offsets
in a column-wide array. This algorithm is <100 LOC and removes ~1000.

As an aside this PR does a few more things that go hand in hand:
* Remove most of `ROW` helper classes, which aren't needed anymore.
* Allocate backing memory in a single `VirtualAlloc` call.
* Rewrite `IsCursorDoubleWidth` to use `DbcsAttrAt` directly.
  Improves overall performance by 10-20% and makes this implementation
  faster than the previous NxM storage, despite the added complexity.

Part of #8000

## Validation Steps Performed
* Existing and new unit and feature tests complete 
* Printing Unicode completes without crashing 
* Resizing works without crashing 
2022-11-11 20:34:58 +01:00
Leonard Hecker
b4d37d8c70
Add recursive_ticket_lock and use it for Terminal (#13746)
My hope with this commit is to make our code more robust against accidental
recursive locking, as well as making it easier to write code with confidence,
with only a slight performance trade-off.

## Validation Steps Performed
* Playing Pac Man music through MIDI 
* Windows Terminal runs happily ever after 
2022-10-31 23:07:59 +00:00
Leonard Hecker
b4fce27203
Skip DECPS/MIDI output on Ctrl+C/Break (#14214)
Silent MIDI notes can be used to seemingly deny a user's input for long
durations (multiple minutes). This commit improves the situation by ignoring
all DECPS sequences for a second when Ctrl+C/Ctrl+Break is pressed.

Additionally it fixes a regression introduced in 666c446:
When we close a tab we need to unblock/shutdown `MidiAudio` early,
so that `ConptyConnection::Close()` can run down as fast as possible.

## Validation Steps Performed
* In pwsh in Windows Terminal 1.16 run ``while ($True) { echo "`e[3;8;3,~" }``
  * Ctrl+C doesn't do anything 
  * Closing the tab doesn't do anything 
* With these modifications in Windows Terminal:
  * Ctrl+C stops the output 
  * Closing the tab completes instantly 
* With these modifications in OpenConsole:
  * Ctrl+C stops the output 
  * Closing the window completes instantly 
2022-10-31 17:18:16 -05:00
Jeroen B
8ea3cb9972
Disable acrylic material (temporarily) when opacity is set to 100% (#14193)
If the opacity is set to 100%, the background becomes solid instead of 'fully opaque acrylic'. If the opacity is below 100% the acrylic material is re-enabled (depending on the user's settings).

## Validation Steps Performed

I updated two unit tests to reflect the change in behavior and manually tested the transition from <100% opacity to 100% opacity (and vice versa) on win11.

Steps:
1. Start with 100% opacity and acrylic material enabled.
2. Decrease opacity and observe acrylic effect.
3. Increase opacity back to 100% and disable the acrylic effect.
4. Decrease opacity and notice that acrylic effect is no longer there.

Closes #12880
2022-10-26 23:19:36 +00:00
Dustin L. Howett
07201d6cd1
Add a maximum OSC 8 URI length of 2MB following iTerm2 (#14198)
c0b2f488c1

Unlike iTerm2, we're not planning on making it configurable.

This commit also adds a max length of 1024 characters on the "display URI" that we pass up to XAML, so as to not inundate the UI.

Fixes #14200
2022-10-12 22:16:38 +00:00
Leonard Hecker
c51bb3a7a6
Add support for fractional font sizes (#14013)
After this commit a user may specify fractional font sizes.
Support was only implemented for AtlasEngine however.
DxEngine continues to use rounded (integer) font sizes.

Closes #6678

## Validation Steps Performed
* Install a bitmap font that requires fractional font sizes
  (e.g. Terminus TTF, https://files.ax86.net/terminus-ttf/)
* Set font size to something integer (e.g. 14pt)
  Glyphs are blurry 
* Set font size to something fractional (e.g. 13.5pt)
  Glyphs are crisp 
2022-09-16 22:37:56 +00:00
Carlos Zamora
1ef4a42762
Polish MarkMode interactions with ExpandSelectionToWord and existing selection (#13893)
- fix: if a selection exists, mark mode should promote the existing selection instead of creating one at the cursor
- fix: mark mode --> move to middle of a word --> ExpandSelectionToWord --> Shift+Right/Left had some weird behavior. Fix that
- fix: Ctrl+enter on random selection clears selection. It should try to treat selection as a URL.

## References
#13854

NOTE: 3b53f3c can be serviced
2022-09-07 16:07:52 +00:00
Leonard Hecker
666c446bc3
Fix a ControlCore race condition on connection close (#13882)
As noted by the `winrt::event` documentation:
> [...] But for asynchronous events, even after revoking [...], an in-flight
> event might reach your object after it has started destructing.

This is because while adding/removing/calling event handlers might be
thread-safe, there's no guarantee that they run mutually exclusive.

This commit fixes the issue by reverting 6f0f245. Since we never checked
the result of closing a terminal connection anyways, this commit simply drops
the wait on the connection being teared down to ensure #1996 doesn't regress.

Closes #13880

## Validation Steps Performed
* Open tab, close tab, open tab, close tab, open tab, close tab
  * ConPTY 
  * Azure 
* Closing a tab with a huge amount of panes 
* Opening a bunch of tabs and then closing the window 
* Closing a tab while it's busy with VT 
* `wtd -w 0 nt cmd /c exit` 
* `wtd -w -1 cmd /c exit`
  * No WerFault spawns 
2022-09-06 21:36:59 +00:00
Leonard Hecker
813286c523
AtlasEngine: Fix various bugs found in testing (#13906)
In testing the following issues were found in AtlasEngine and fixed:
1. "Toggle terminal visual effects" action not working
2. `d2dMode` failed to work with transparent backgrounds
3. `GetSwapChainHandle()` is thread-unsafe due to it being called outside
  of the console lock and with single-threaded Direct2D enabled
4. 2 swap chain buffers are less performant than 3
5. Flip-Discard and `Present()` is less energy efficient than
  Flip-Sequential and `Present1()`
6. `d2dMode` used to copy the front to back buffer for partial rendering,
  but always redraw the entire dirty region anyways
7. Added support for DirectX 9 hardware
8. If custom shaders are used not all pixels would be presented

Closes #13906

## Validation Steps Performed
1. Toggling visual effects runs retro shader 
   With a custom shader set, it toggles the shader 
   Toggling `experimental.rendering.software` toggles the shader 
2. `"backgroundImage": "desktopWallpaper"` works with D2D  and D3D 
3. Adding a `Sleep(3000)` in `_AttachDxgiSwapChainToXaml` doesn't break
   Windows 10  nor Windows 11 
4. Screen animations run at 144 FPS  even while moving the window 
5. No weird artefacts during cursor movement or scrolling 
6. No weird artefacts during cursor movement or scrolling 
7. Forcing DirectX 9.3 in `dxcpl` runs fine 
2022-09-02 22:10:09 +00:00
Dan Thompson
d11ea72639
Implement EnableColorSelection (#13429)
## Summary of the Pull Request

As described in #9583, this change implements the legacy conhost "EnableColorSelection" feature.

## Detailed Description of the Pull Request / Additional comments

@zadjii-msft was super nice and provided the outline/plumbing (WinRT classes and such) as a hackathon-type project (thank you!)--a "SelectionColor" runtimeclass, a ColorSelection method on the ControlCore runtimeclass, associated plumbing through the layers; plus the action-and-args plumbing to allow hooking up a basic "ColorSelection" action, which allows you to put actions in your settings JSON like so:

```json
{
    "command":
    {
        "action": "experimental.colorSelection",
        "foreground": "#0f3"
    },
    "keys": "alt+4"
},
```

On top of that foundation, I added a couple of things:
* The ability to specify indexes for colors, in addition to RGB and RRGGBB colors.
  - It's a bit hacky, because there are some conversions that fight against sneaking an "I'm an index" flag in the alpha channel.
* A new "matchMode" parameter on the action, allowing you to say if you want to only color the current selection ("0") or all matches ("1").
  - I made it an int, because I'd like to enable at least one other "match mode" later, but it requires me/someone to fix up search.cpp to handle regex first.
  - Search used an old UIA "ColorSelection" method which was previously `E_NOTIMPL`, but is now wired up. Don't know what/if anything else uses this.
* An uber-toggle setting, "EnableColorSelection", which allows you to set a single `bool` in your settings JSON, to light up all the keybindings you would expect from the legacy "EnableColorSelection" feature:
    - alt+[0..9]: color foreground
    - alt+shift+[0..9]: color foreground, all matches
    - ctrl+[0..9]: color background
    - ctrl+shift+[0..9]: color background, all matches
 * A few of the actions cannot be properly invoked via their keybindings, due to #13124. `*!*` But they work if you do them from the command palette.
  * If you have "`EnableColorSelection : true`" in your settings JSON, but then specify a different action in your JSON that uses the same key binding as a color selection keybinding, your custom one wins, which I think is the right thing.
* I fixed what I think was a bug in search.cpp, which also affected the legacy EnableColorSelection feature: due to a non-inclusive coordinate comparison, you were not allowed to color a single character; but I see no reason why that should be disallowed. Now you can make all your `X`s red if you like.

"Soft" spots:
* I was a bit surprised at some of the helpers I had to provide in textBuffer.cpp. Perhaps there are existing methods that I didn't find?
* Localization? Because there are so many (40!) actions, I went to some trouble to try to provide nice command/arg descriptions. But I don't know how localization works…


<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist
* [x] Closes #9583
* [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [ ] Tests added/passed *(what would be the right place to add tests for this?)*
* [ ] 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. *(is this needed?)*
* [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #xxx

## Validation Steps Performed
Just manual testing.
2022-08-31 23:54:29 +00:00
Carlos Zamora
11e7bbc1f3
Introduce ExpandSelectionToWord action (#13765)
## Summary of the Pull Request
Introduces a new action `expandSelectionToWord()` which expands the beginning and end of the selection to encompass the word(s) it's on. This was implemented as a conditional keybinding where the key chord is passed through to the terminal if no selection is active (similar to `copy()`).
It is not bound to anything by default.

## PR Checklist
* [x] Closes #8274
* [x] Schema updated.

## Validation Steps Performed
- Scenario in #8274:
	- search for some text in the find dialog
	- ESC to close the dialog
	- execute `expandSelectionToWord()`
	- the new selection encompasses the whole word
- mark mode
	- move onto a word
	- execute `expandSelectionToWord()`
- mouse selection (same as above)
- select a portion of two words --> new selection fully encompasses both words
2022-08-31 19:06:05 +00:00
Leonard Hecker
12122b2bf9
Fix a race condition in UpdatePatternLocations (#13859)
Since locking the console can take a non-trivial amount of time,
the main thread might have already released the ControlCore instance, while the
`UpdatePatternLocations` background thread is holding the last active reference.
If the function call goes out of scope, we destroy the instance, which might
not be safe, considering its members are usually only used by the main thread.
This commit fixes the issue by only holding a reference of the `Terminal`.

## Validation Steps Performed
* Patterns are recognized 
2022-08-30 20:20:05 +00:00
Mike Griese
a85d9e69ed
Attempt to fix the _refreshSizeUnderLock crash (#13857)
See https://github.com/microsoft/terminal/issues/12176#issuecomment-1199488906, and MSFT:39723014.

I have literally no idea how to repro this one, or debug it. The dump I looked at looked like there was a `SwapChainScaleChanged` that was being dispatched as the app was tearing down. The `ControlCore` had started closing, but the `TermControl` hadn't yet. Apparently, just none of the `_refreshSizeUnderLock` callers checked if we were already closing.

All the callers appear to be on the main thread.

Closes #12176

Since there's no real way for me to repro this manually, I'm thinking we fire this fix off to the OS terminal build, where we'll pretty quickly be able to see if this fixed it or not.
2022-08-29 21:42:17 +00:00
Carlos Zamora
4488a25971
[Follow-up] Polish keyboard navigation to hyperlinks (#13494)
## Summary of the Pull Request
Polishes #13405 with some additional feedback found in testing and post-mortem reviews. Such feedback includes:
- [x] ControlInteractivity vs ControlCore split ([link](https://github.com/microsoft/terminal/pull/13405#discussion_r919365435))
- [x] clearing the selection should be under lock when copying text via "Enter"
- [x] move mark mode keybindings into a helper function
- [x] decide if "Enter" should be configurable or non-configurable ([link](https://github.com/microsoft/terminal/pull/13405#discussion_r919379305))
- [x] rename `_isTargetingUrl`
- [x] bugfix: ctrl+enter when the link is outside of the viewport

## References
Original PR: #13405
Relevant issue: #6649
Epic: #4993
2022-08-25 18:53:45 +00:00
Carlos Zamora
70313db246
Make Mark Mode keybindings precede custom keybindings (#13659)
## Summary of the Pull Request
This PR moves the key handling for mark mode into a helper method that is then called before an action/key binding is attempted. 

## References
Epic: #4993 
Closes #13533

## Validation Steps Performed
- Add custom keybinding to "down" arrow key
- in mark mode --> selection updates appropriately
- out of mark mode --> keybinding executed
2022-08-22 20:39:23 +00:00
Dustin L. Howett
2dedc9af7f
Use the viewport-relative cursor pos for CCore.CursorPosition (#13785)
In #13024, we removed `Terminal::GetCursorPosition` from TerminalCore.
This has been widely regarded as a good move.

Now, you might rightly be wondering: why didn't compilation immediately
fail? Well. It turns out that there were _two_ copies of
`GetCursorPosition`. One for `const Terminal`, and one for `Terminal`.
This is important.

`Terminal::GetCursorPosition()` returned the cursor position relative to
the viewport. `Terminal::GetCursorPosition() const`, however, returns
the cursor position in absolute.

We removed the non-`const` one. Fortunately, thanks to the lookup rules
for `const`-qualified members, this didn't matter. Code that called
`GetCursorPosition()` still called `GetCursorPosition()`, and everything
was fine.

Except that part about the relative coordinates. That was not fine.

The TSF control is the _only_ consumer of `ControlCore.CursorPosition`,
and that was the _only_ consumer of relative-`GetCursorPosition()`.

This commit restores equilibrium by introducing a new
`GetViewportRelativeCursorPosition()` member to `Terminal` and switching
over the only consumer of relative cursor position to use it.

Closes #13769.
2022-08-22 11:58:40 -05:00
Carlos Zamora
fed9b0044d
Enable AtlasEngine by default in Preview (#13752)
Repurpose `Feature_AtlasEngine` to enable the atlas engine by default in Dev and Preview builds.
Introduce `Feature_ConhostAtlasEngine` to solely control atlas engine inclusion in conhost.

Closes #13745
2022-08-16 18:53:38 +00:00
Leonard Hecker
23e4d313d5
Call UpdatePatternLocations from a background thread (#13758)
We have a number of theories why #12607 is happening, one of which is that
some GPU drivers somehow rely on Win32 messages or similar which we process
on the main thread. If we then try to acquire the console lock on the main
thread, while the GPU-driver thread itself is holding that lock, we've got
ourselves a deadlock. This PR makes this less likely by running the repeat
offender `UpdatePatternLocations` on a background thread instead.
We have a number of other locations which acquire the console lock on the
main thread and a thorough bug fix must be done in a different way.

## Validation Steps Performed
* After pasting an URL it gets underlined on hover 
2022-08-16 18:30:03 +00:00