Commit graph

219 commits

Author SHA1 Message Date
Leonard Hecker 4099aacacb
Fix #5784: Key bindings won't consume dead keys (#7686)
Let's assume the user has bound the dead key ^ to a sendInput command
that sends "b".  If the user presses the two keys ^a it'll produce "bâ",
despite us marking the key event as handled.  We can use `ToUnicodeEx`
to clear such dead keys from the keyboard state and should make use of
that for keybindings.  Unfortunately `SetKeyboardState` cannot be used
for this purpose as it doesn't clear the dead key state.

Validation
* Enabled a German keyboard layout
* Added the following two keybindings:
  { "command": { "action": "sendInput", "input": "x" }, "keys": "q" },
  { "command": { "action": "sendInput", "input": "b" }, "keys": "^" }
* Pressed the following keys → ensured that the given text is printed:
  * q → x
  * ´ → nothing
  * a → á
  * ^ → b
  * a → a (previously this would print: â)
  * ´ → nothing
  * ^ → b
  * a → a (unfortunately we cannot specifically clear only ^)

Closes #5784
2020-10-19 16:55:56 -07:00
Don-Vito 60d681d564
7395: do not clear text selection upon PrintScreen (#7883)
When handling SendKey, preserve selection upon PrintScreen (VK_SNAPSHOT)

Closes #7395
2020-10-15 17:01:01 -07:00
James Holderness 09cc5f492c
Add support for the BEL control in Windows Terminal (#7679)
This commit makes the Windows Terminal play an audible sound when the
`BEL` control character is output.

The `BEL` control was already being forwarded through conpty, so it was
just a matter of hooking up the `WarningBell` dispatch method to
actually play a sound. I've used the `PlaySound` API to output the sound
configured for the "Critical Stop" system event (aka _SystemHand_),
since that is the sound used in conhost.

## Validation

I've manually confirmed that the terminal produces the expected sound
when executing `echo ^G` in a cmd shell, or `printf "\a"` in a WSL bash
shell.

References:
* There is a separate issue (#1608) to deal with configuring the `BEL`
  to trigger visual forms of notification.
* There is also an issue (#2360) requesting an option to disable the
  `BEL`.

Closes #4046
2020-09-30 18:00:06 -07:00
James Holderness d1671a0acd
Add support for the "blink" graphic rendition attribute (#7490)
This PR adds support for the _blink_ graphic rendition attribute. When a
character is output with this attribute set, it "blinks" at a regular
interval, by cycling its color between the normal rendition and a dimmer
shade of that color.

The majority of the blinking mechanism is encapsulated in a new
`BlinkingState` class, which is shared between the Terminal and Conhost
implementations. This class keeps track of the position in the blinking
cycle, which determines whether characters are rendered as normal or
faint. 

In Windows Terminal, the state is stored in the `Terminal` class, and in
Conhost it's stored in the `CONSOLE_INFORMATION` class. In both cases,
the `IsBlinkingFaint` method is used to determine the current blinking
rendition, and that is passed on as a parameter to the
`TextAttribute::CalculateRgbColors` method when these classes are
looking up attribute colors.

Prior to calculating the colors, the current attribute is also passed to
the `RecordBlinkingUsage` method, which keeps track of whether there are
actually any blink attributes in use. This is used to determine whether
the screen needs to be refreshed when the blinking cycle toggles between
the normal and faint renditions.

The refresh itself is handled by the `ToggleBlinkingRendition` method,
which is triggered by a timer. In Conhost this is just piggybacking on
the existing cursor blink timer, but in Windows Terminal it needs to
have its own separate timer, since the cursor timer is reset whenever a
key is pressed, which is not something we want for attribute blinking.

Although the `ToggleBlinkingRendition` is called at the same rate as the
cursor blinking, we actually only want the cells to blink at half that
frequency. We thus have a counter that cycles through four phases, and
blinking is rendered as faint for two of those four. Then every two
cycles - when the state changes - a redraw is triggered, but only if
there are actually blinking attributes in use (as previously recorded).

As mentioned earlier, the blinking frequency is based on the cursor
blink rate, so that means it'll automatically be disabled if a user has
set their cursor blink rate to none. It can also be disabled by turning
off the _Show animations in Windows_ option. In Conhost these settings
take effect immediately, but in Windows Terminal they only apply when a
new tab is opened.

This PR also adds partial support for the `SGR 6` _rapid blink_
attribute. This is not used by DEC terminals, but was defined in the
ECMA/ANSI standards. It's not widely supported, but many terminals just
it implement it as an alias for the regular `SGR 5` blink attribute, so
that's what I've done here too.

## Validation Steps Performed

I've checked the _Graphic rendition test pattern_ in Vttest, and
compared our representation of the blink attribute to that of an actual
DEC VT220 terminal as seen on [YouTube]. With the right color scheme
it's a reasonably close match.

[YouTube]: https://www.youtube.com/watch?v=03Pz5AmxbE4&t=1m55s

Closes #7388
2020-09-21 23:21:33 +00:00
PankajBhojwani be50e563e6
Display URI tooltip, render dashed/solid underline for links (#7420)
- Render hyperlinks with a dashed underline
- Render hovered hyperlinks with a solid underline
- Show URI tooltip on hover

TermControl now has a canvas that contains a tiny border to which a
tooltip is attached. When we hover over hyperlinked text, we move the
border to the mouse location and update the tooltip content with the
URI. 

Introduced a new underline type (HyperlinkUnderline), supports rendering
for it, and uses it to render hyperlinks. HyperlinkUnderline is usually
a dashed underline, but when a link is hovered, all text with the same
hyperlink ID is rendered with a solid underline. 

References #5001
2020-09-10 14:59:56 -07:00
PankajBhojwani 614507b95b
OSC 8 support for conhost and terminal (#7251)
<!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? -->
## Summary of the Pull Request
Conhost can now support OSC8 sequences (as specified [here](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda)). Terminal also supports those sequences and additionally hyperlinks can be opened by Ctrl+LeftClicking on them. 

<!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> 
## References
#204 

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist
* [X] Closes #204 
* [ ] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [ ] Tests added/passed
* [ ] Documentation updated. If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/terminal) and link it here: #xxx
* [ ] Schema updated.
* [ ] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #xxx

<!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments
Added support to:

- parse OSC8 sequences and extract URIs from them (conhost and terminal)
- add hyperlink uri data to textbuffer/screeninformation, associated with a hyperlink id (conhost and terminal)
- attach hyperlink ids to text to allow for uri extraction from the textbuffer/screeninformation (conhost and terminal)
- process ctrl+leftclick to open a hyperlink in the clicked region if present

<!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
Open up a PowerShell tab and type
```PowerShell
${ESC}=[char]27
Write-Host "${ESC}]8;;https://github.com/microsoft/terminal${ESC}\This is a link!${ESC}]8;;${ESC}\"
```
Ctrl+LeftClick on the link correctly brings you to the terminal page on github

![hyperlink](https://user-images.githubusercontent.com/26824113/89953536-45a6f580-dbfd-11ea-8e0d-8a3cd25c634a.gif)
2020-09-03 13:52:39 -04:00
Dustin L. Howett a5bed25417
TermControl: set the scrollbar jump distance to one screenful (#7385)
Most applications with scrollable content seem to define the "large
jump" distance as about a screenful of content. You can see this in long
pages in Settings and documents in Notepad.

We just weren't configuring ScrollBar here.

Fixes #7367
2020-08-24 15:54:02 -07:00
Carlos Zamora 24b8c13bd0
Add copyFormatting keybinding arg and array support (#6004)
Adds array support for the existing `copyFormatting` global setting.
This allows users to define which formats they would specifically like
to be copied.

A boolean value is still accepted and is translated to the following:
- `false` --> `"none"` or `[]`
- `true` --> `"all"` or `["html", "rtf"]`

This also adds `copyFormatting` as a keybinding arg for `copy`. As with
the global setting, a boolean value and array value is accepted.

CopyFormat is a WinRT enum where each accepted format is a flag.
Currently accepted formats include `html`, and `rtf`. A boolean value is
accepted and converted. `true` is a conjunction of all the formats.
`false` only includes plain text.

For the global setting, `null` is not accepted. We already have a
default value from before so no worries there.

For the keybinding arg, `null` (the default value) means that we just do
what the global arg says to do. Overall, the `copyFormatting` keybinding
arg is an override of the global setting **when using that keybinding**.

References #5212 - Spec for formatted copying
References #2690 - disable html copy

Validated behavior with every combination of values below:
- `copyFormatting` global: { `true`, `false`, `[]`, `["html"]` }
- `copyFormatting` copy arg:
  { `null`, `true`, `false`, `[]`, `[, "html"]`}

Closes #4191
Closes #5262
2020-08-14 18:02:24 -07:00
Dustin L. Howett aecd99e0ca
Pass the scancode in our tunneled DirectKey event (#7298)
#7145 introduced a check so that we wouldn't dispatch keys unless they
actually had a scancode. Our synthetic events actually _didn't_ have
scancodes. Not because they couldn't--just because they didn't.

Fixes #7297
2020-08-14 23:44:39 +00:00
Leonard Hecker a2721c1043
Fixed #3799: Introduce sendInput command (#7249)
## Summary of the Pull Request

This PR enables users to send arbitrary text input to the shell via a keybinding.

## PR Checklist
* [x] Closes #3799
* [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [ ] Tests added/passed
* [ ] Documentation updated. If checked, please file a pull request on [our docs repo](https://github.com/MicrosoftDocs/terminal) and link it here: #xxx
* [x] Schema updated.
* [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #3799

## Detailed Description of the Pull Request / Additional comments

## Validation Steps Performed

Added the following keybindings:
```json
{ "keys": "p", "command": { "action": "sendInput", "input": "foobar" } },
{ "keys": "q", "command": { "action": "sendInput", "input": "\u001b[A" } },
```
Ensured that when pressing <kbd>P</kbd> "foobar" is echoed to the shell and when pressing <kbd>Q</kbd> the shell history is being navigated backwards.
2020-08-12 13:46:53 +00:00
Mike Griese aee803e694
Add support for changing the active color scheme with an action (#6993)
## Summary of the Pull Request

Adds the `setColorScheme` action, to change the color scheme of the active control to one given by the `name` parameter. `name` is required. If `name` is not the name of a color scheme, the action does nothing.

## References

* Being done as a stepping stone to #6689 

## PR Checklist
* [x] Closes #5401
* [x] I work here
* [ ] Tests added/passed
* [n/a] Requires documentation to be updated

## Detailed Description of the Pull Request / Additional comments

Technically, the action is being done by changing the settings of the current `TerminalSettings` of the `TermControl`. Frankly, it should be operating on a copy of the `TermControl`'s `IControlSettings`, then updating the control's settings, or the Control should just listen for changes to it's setting's properties, and update in real time (without a manual call to `UpdateSettings`. However, both those paths are somewhere unknowable beyond #6904, so we'll just do this for now.

## Validation Steps Performed

* tested manually with a scheme that exists
* tested manually with a scheme that doesn't exist
2020-08-10 16:21:56 +00:00
Carlos Zamora 20a288020e
Pass mouse button state into HandleMouse instead of asking win32 (#6765)
MouseInput was directly asking user32 about the state of the mouse buttons,
which was somewhat of a layering violation. This commit makes all callers
have to pass the mouse state in themselves.

Closes #4869
2020-08-07 16:21:09 -07:00
Mike Griese 4e0f31337d
Add support for per-profile tab colors (#7162)
This PR adds support for per-profile tab colors, in accordance with
#7134. This adds a single `tabColor` property, that when set, specifies
the background color for profile's tab. This color can be overridden by
the color picker, and clearing the color with the color picker will
revert to this default color set for the tab.

* Full theming is covered in #3327 & #5772 

Validation: Played with setting this color, both on launch and via
hot-reload

Specified in #7134
Closes #1337
2020-08-07 16:07:42 -07:00
Carlos Zamora 1c6aa4d109
Move ICore/ControlSettings to TerminalControl project (#7167)
## Summary of the Pull Request
Move `ICoreSettings` and `IControlSettings` from the TerminalSettings project to the TerminalCore and TerminalControl projects respectively. Also entirely removes the TerminalSettings project.

The purpose of these interfaces is unchanged. `ICoreSettings` is used to instantiate a terminal. `IControlSettings` (which requires an `ICoreSettings`) is used to instantiate a UWP terminal control.

## References
Closes #7140 
Related Epic: #885 
Related Spec: #6904 

## PR Checklist
* [X] Closes #7140 
* [X] CLA signed
* [X] Tests ~added~/passed (no additional tests necessary)
* [X] ~Documentation updated~
* [X] ~Schema updated~

## Detailed Description of the Pull Request / Additional comments
A lot of the work here was having to deal with winmd files across all of these projects. The TerminalCore project now outputs a Microsoft.Terminal.TerminalControl.winmd. Some magic happens in TerminalControl.vcxproj to get this to work properly.

## Validation Steps Performed
Deployed Windows Terminal and opened a few new tabs.
2020-08-07 14:46:52 +00:00
Carlos Zamora eb8bb09e5b
Move TerminalSettings object to TermApp Project (#7163)
Move TerminalSettings object from TerminalSettings project
(Microsoft.Terminal.Settings) to TerminalApp project. `TerminalSettings`
specifically operates as a bridge that exposes any necessary information
to a TerminalControl.

Closes #7139 
Related Epic: #885
Related Spec: #6904

## PR Checklist
* [X] Closes #7139 
* [X] CLA signed
* [X] Tests ~added~/passed (no additional tests necessary)
* [X] ~Documentation updated~
* [X] ~Schema updated~

## Validation Steps Performed
Deployed Windows Terminal and opened a few new tabs.
2020-08-03 22:54:22 +00:00
Dustin L. Howett dd0f7b701a
Send ENHANCED_KEY in Win32 input mode in the wpf/uwp controls (#7106)
When we added support for win32 input mode, we neglected to pass
`ENHANCED_KEY` through the two surfaces that would generate events. This
broke arrow keys in much the same way was #2397, but in a different
layer.

While I was working on the WPF control, I took a moment to refactor the
message cracking out into a helper. It's a lot easier on the eyes than
four lines of bit shifting repeated three times.

Fixes #7074
2020-07-31 17:16:27 +00:00
Mike Griese d0ff5f6b5e
Add support for running a wt commandline in the curent window WITH A KEYBINDING (#6537)
## Summary of the Pull Request

Adds a execute commandline action (`wt`), which lets a user bind a key to a specific `wt` commandline. This commandline will get parsed and run _in the current window_. 

## References

* Related to #4472 
* Related to #5400 - I need this for the commandline mode of the Command Palette
* Related to #5970

## PR Checklist
* [x] Closes oh, there's not actually an issue for this.
* [x] I work here
* [x] Tests added/passed
* [ ] Requires documentation to be updated - yes it does

## Detailed Description of the Pull Request / Additional comments

One important part of this change concerns how panes are initialized at runtime. We've had some persistent trouble with initializing multiple panes, because they rely on knowing how big they'll actually be, to be able to determine if they can split again. 

We previously worked around this by ignoring the size check when we were in "startup", processing an initial commandline. This PR however requires us to be able to know the initial size of a pane at runtime, but before the parents have necessarily been added to the tree, or had their renderer's set up.

This led to the development of `Pane::PreCalculateCanSplit`, which is very highly similar to `Pane::PreCalculateAutoSplit`. This method attempts to figure out how big a pane _will_ take, before the parent has necessarily laid out. 

This also involves a small change to `TermControl`, because if its renderer hasn't been set up yet, it'll always think the font is `{0, fontHeight}`, which will let the Terminal keep splitting in the x direction. This change also makes the TermControl set up a renderer to get the real font size when it hasn't yet been initialized.

## Validation Steps Performed

This was what the json blob I was using for testing evolved into

```json
        {
            "command": {
                "action":"wt",
                "commandline": "new-tab cmd.exe /k #work 15 ; split-pane cmd.exe /k #work 15 ; split-pane cmd.exe /k media-commandline ; new-tab powershell dev\\symbols.ps1 ; new-tab -p \"Ubuntu\" ; new-tab -p \"haunter.gif\" ; focus-tab -t 0",

            },
            "keys": ["ctrl+shift+n"]
        }
```

I also added some tests.

# TODO
* [x] Creating a `{ "command": "wt" }` action without a commandline will spawn a new `wt.exe` process?
  - Probably should just do nothing for the empty string
2020-07-17 21:05:29 +00:00
Dustin L. Howett 06b50b47ca
Remove the rowsToScroll setting and just always use the system setting (#6891)
This parameter was added as a workaround for our fast trackpad
scrolling. Since that was fixed before 1.0 shipped, in #4554, it has
been largely vestigial. There is no reason for us to keep it around any
longer.

It was also the only "logic" in TerminalSettings, which is otherwise a
library that only transits data between two other libraries.

I have not removed it from the schema, as I do not want to mark folks'
settings files invalid to a strict schema parser.

While I was in the area, I added support for "scroll one screen at a
time" (which is represented by the API returning WHEEL_PAGESCROLL),
fixing #5610. We were also storing it in an int (whoops) instead of a
uint.

Fixes #5610
2020-07-14 01:38:11 +00:00
Carlos Zamora 63fbd9f1fc
Allow starting selections from padding area (#6343)
WinUI's `Margin` and `Padding` work very similarly. `Margin` distances
ourselves from our parent. Whereas `Padding` distances our children from
ourselves.

Terminal's `padding` setting is actually implemented by defining
`Margin` on the SwapChainPanel. This means that the "padding" that is
created is actually belongs to SwapChainPanel's parent: Grid (not to be
confused with its parent, "RootGrid").

When a user clicks on the padded area, input goes to Grid. But there's a
twist: you can't actually hit Grid. To be able to hit Grid, you can't
just set IsHitTestVisible. You need to set it's Visibility to Visible,
and it's Background to Transparent (not null) [2].

## Validation Steps Performed

- [X] Start a selection from the padding area
- [X] Click on a SearchBox if one is available
   - The SearchBox gets first dibs on the hit test so none gets through
     to the SwapChainPanel

## References
[1] https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.uielement.ishittestvisible
[2] https://docs.microsoft.com/en-us/windows/uwp/xaml-platform/events-and-routed-events-overview#hit-testing-and-input-events

Closes #5626
2020-07-07 23:42:42 +00:00
Mike Griese 396cbbb151
Add a ShortcutAction for toggling retro terminal effect (#6691)
Pretty straightforward. `toggleRetroEffect` will work to toggle the
retro terminal effect on/off. 

* Made possible by contributions from #6551, _and viewers like you_
2020-07-01 23:17:43 +00:00
uzxmx b24579d2b0
Add support for OSC 52 (copy-to-clipboard) (#5823)
With this commit, terminal will be able to copy text to the system
clipboard by using OSC 52 MANIPULATE SELECTION DAATA.

We chose not to implement the clipboard querying functionality offered
by OSC 52, as sending the clipboard text to an application without the
user's knowledge or consent is an immense security hole.

We do not currently support the clipboard specifier Pc to specify which
clipboard buffer should be filled

# Base64 encoded `foo`
$ echo -en "\e]52;;Zm9v\a"

# Multiple lines
# Base64 encoded `foo\r\nbar`
$ echo -en "\e]52;;Zm9vDQpiYXI=\a"

Closes #2946.
2020-06-30 01:55:40 +00:00
Carlos Zamora 9215b5282d
Implement Shift+MultiClick Selection Expansion (#6322)
This pull request implements shift+double/triple click. Proper behavior
(as described in #4557) is to only expand one selection point, not both.

Adding the `bool targetStart` was a bit weird. I decided on this being
the cleanest approach though because I still want `PivotSelection` to be
its own helper function. Otherwise, the concept of "pivoting" gets kinda
messy.

## Validation Steps Performed
Manual testing as described on attached issue.
Tests were added for Shift+Click and pivoting the selection too.

Closes #4557
2020-06-25 00:47:13 +00:00
greg904 58f5d7c72e
Update _TerminalCursorPositionChanged to use ThrottledFunc (#6492)
* Update _TerminalCursorPositionChanged to use ThrottledFunc.
* Rename previous ThrottledFunc to ThrottledArgFunc because now
  ThrottledFunc is for functions that do not take an argument.
* Update ThrottledFunc and ThrottledArgFunc to accept a CoreDispatcher
  on which the function should be called for convenience.
* Don't use coroutines/winrt::fire_and_forget in
  ThrottledFunc/ThrottledArgFunc because they are too slow (see PR).

_AdjustCursorPosition went from 17% of samples to 3% in performance
testing.
2020-06-23 14:05:40 -07:00
Michael Niksa b91430b64d
Enable hot reload of renderer settings that aren't already hot reload capable (#6551)
## Summary of the Pull Request

## PR Checklist
* [x] Closes #3927
* [x] I work here.
* [x] Tested manually.
* [x] Requires documentation to be updated: (generate doc bug here)
* [x] Am core contributor.

## Detailed Description of the Pull Request / Additional comments
- I found four settings that weren't hot reloadable with the 3927 comment above them:
1. Experimental retro terminal effect
2. Experimental software rendering
3. Experimental full repaint rendering
4. Antialiasing settings for text

I made them all hot reloadable by telling the `TermControl` to propagate them on settings change to the `DxEngine`.
Then I set up the `DxEngine` inside the setters to only set them if they changed. And if they do change, to trigger a full repaint and/or a complete drop and recreate of the entire DX device chain (as would happen if it were lost for another reason like a user-mode graphics failure, disconnected display, etc.)
I made the boolean an atomic because the settings can be coming in off of another thread (the XAML eventing one) and the renderer is picking the status up on its thread at the top of the BeginPaint frame.

## Validation Steps Performed
- [x] Opened it up and toggled all the settings while staring at PowerShell
- [x] Opened it up and toggled all the settings while staring at something intensive like a `cacafire` fire
2020-06-19 21:09:37 +00:00
Leonard Hecker 4eaa0b83c7
Use early returns in TermControl::_KeyHandler (#6575)
## Summary of the Pull Request

This PR changes `TermControl::_KeyHandler` to use early returns, which you can think of as "guard clauses".
This has the benefit of a reduced nesting level, easier to understand control flow and opens op the way to more complex conditions.

## PR Checklist
* [ ] Closes #xxx
* [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [x] Tests added/passed
* [ ] Requires documentation to be updated
* [ ] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #xxx

## Validation Steps Performed

Everything still works as expected.
2020-06-18 22:24:12 +00:00
Mike Griese 332d1744d9
Fix sending a NUL on alt key up (#6516)
## Summary of the Pull Request

Make sure to set the scancode for the manual alt-up's we're sending. If you don't, then terminalInput in the conpty is going to treat that keypress as an actual NUL, and send that to the connected client.

## References
* regressed in #6421 

## PR Checklist
* [x] Closes #6513
* [x] I work here
* [ ] Tests added/passed
* [n/a] Requires documentation to be updated

## Validation Steps Performed
Tested `showkeys -a`
2020-06-15 19:54:51 +00:00
greg904 25df527743
Throttle scrollbar updates in TermControl to ~one per 8ms (#4608)
In addition to the below (original) description, this commit introduces
a ThrottledFunc template that can throttle _any_ function. It applies
that type to muffle updates to the scrollbar.

---

Redo #3531 but without the bug that it caused (#3622) which is why it
was reverted.

I'm sorry if I explain this badly. If you don't understand a part, make
sure to let me know and I will explain it better.

### Explanation

How it worked before: `Terminal` signals that viewport changed ->
`TermControl::_TerminalScrollPositionChanged` gets called on the
terminal thread -> it dispatches work for later to be ran the UI thread
to updates the scrollbar's values

Why it's bad:
* If we have many viewport changes, it will create a long stack of
  operations to run. Instead, we should just update the scroll bar with
  the most recent information that we know.
* Imagine if the rate that the work gets pushed on the UI thread is
  greater than the rate that it can handle: it might freeze?
* No need to be real time, we can wait just a little bit (8ms) to
  accumulate viewport changes before we actually change the scroll bar's
  value because it appears to be expensive (see perf below).

Now: `Terminal` signals that viewport changed ->
`TermControl::_TerminalScrollPositionChanged` gets called on the
terminal thread -> it tells the `ScrollBarUpdater` about a new update ->
the `ScrollBarUpdater` only runs one job (I don't know if that's the
right term) on the UI thread at a time. If a job is already running but
hasn't updated the scroll bar yet, it changes the setting in the already
existing job to update the scroll bar with the new values. A job "waits"
some time before doing the update to throttle updates because we don't
need real time scroll bar updates. -> eventually, it updates the scroll
bar If the user scrolls when a scroll bar update is pending, we keep the
scroll bar's Maximum and Minimum but let the user choose its new Value
with the `CancelPendingValueChange` method.

### Note

Also I changed a little bit the code from the Terminal to notify the
TermControl less often when possible.

I tried to scroll with the scroll bar, with the mouse wheel. I tried to
scroll while content is being outputted.

I tried to reproduce the crash from #2248 without success (good).

Co-authored-by: Leonard Hecker <leonard@hecker.io>

Closes #3622
2020-06-12 12:51:37 -07:00
Mike Griese e8ece1645c
Pass <Alt> to the application (#6461)
For mysterious reasons lost to the sands of time, XAML will _never_ pass
us a VK_MENU event. This is something that'll probably get fixed in
WinUI 3, but considering we're stuck on system XAML for the time being,
the only way to work around this bug is to pass the event through
manually. This change generalizes the F7 handler into a "direct key
event" handler that uses the same focus and tunneling method to send
different key events, and then uses it to send VK_MENU.

## Validation Steps Performed

Opened the debug tap, verified that I was seeing alt key ups.
Also used some alt keybindings to make sure I didn't break them.

Closes #6421
2020-06-11 15:41:16 -07:00
Mike Griese 7b791f572d
Don't send a manual F7 keyup (#6442)
## Summary of the Pull Request

When someone asked "Do we need to send a F7 keyup too" in #6309, the right answer was actually _no_. Turns out that while XAML will eat the F7 key**down**, it _won't_ eat the F7 key**up**. 

## References

* regressed in #6309

## PR Checklist
* [x] Closes #6438 
* [x] I work here
* [ ] Tested manually
* [n/a] Requires documentation to be updated

## Validation Steps Performed

* Checked this with the debug tap
2020-06-09 23:16:38 +00:00
Mike Griese e03e46b69e
Don't snap on input nor dismiss selection for just a modifier key (#6431)
Does what it says on the label. Pure modifier keys weren't making it
this far at all prior to #6309. This PR changes these methods to make
sure that we only dismiss a selection or snap on input when the key
pressed isn't a modifier key.

## References

* regressed in #6309

## PR Checklist
* [x] Closes #6423
* [x] I work here
* [ ] Tests added/passed
* [n/a] Requires documentation to be updated

## Validation Steps Performed

* Tried to repro this in the Terminal, couldn't anymore.
2020-06-09 21:49:39 +00:00
greg904 f9b1238f30
Set tab title as early as possible (#6433)
When opening a new tab, it takes a few milliseconds before title to
appears. This PR makes it instantaneous.

* Updated the Terminal so that it can load the title from the settings
  before it is initialized.
* Load terminal settings in TermControl constructor before the terminal
  is initialized (see above).
* Update Tab so that it sets the TabViewItem's title in the constructor
  (in Tab::_MakeTabViewItem) instead of waiting for the VT sequence to
  set the title (from what I understand).

NOTE 1: there is a similar problem with the tabview icon which is not
fixed by this PR.

NOTE 2: This is only a problem with animations disabled because
otherwise the title fades in so there is enough time for it to be set
when it becomes visible.

## Validation

I ran the terminal and opened a new tab. The title appears instantly.
2020-06-09 21:47:13 +00:00
Mike Griese f32761849f
Add support for win32-input-mode to conhost, ConPTY, Terminal (#6309)
Adds support for `win32-input-mode` to conhost, conpty, and the Windows
Terminal.

* The shared `terminalInput` class supports sending these sequences when
  a VT client application requests this mode.
* ConPTY supports synthesizing `INPUT_RECORD`s from the input sent to it
  from a terminal
* ConPTY requests this mode immediately on startup (if started with a
  new flag, `PSEUDOCONSOLE_WIN32_INPUT_MODE`)
* The Terminal now supports sending this input as well, when conpty asks
  for it.

Also adds a new ConPTY flag `PSEUDOCONSOLE_WIN32_INPUT_MODE` which
requests this functionality from conpty, and the Terminal requests this
by default.

Also adds `experimental.input.forceVT` as a global setting to let a user
opt-out of this behavior, if they don't want it / this ends up breaking
horribly.

## Validation Steps Performed
* played with this mode in vtpipeterm
* played with this mode in Terminal
* checked a bunch of scenarios, as outlined in a [comment] on #4999

[comment]: https://github.com/microsoft/terminal/issues/4999#issuecomment-628718631

References #4999: The megathread
References #5887: The spec

Closes #879
Closes #2865
Closes #530 
Closes #3079
Closes #1119
Closes #1694 
Closes #3608 
Closes #4334
Closes #4446
2020-06-08 22:31:28 +00:00
Michael Niksa 8265d941b7
Add font weight options (#6048)
## Summary of the Pull Request
Adds the ability to specify the font weight in the profiles, right next to the size and the font face.

## PR Checklist
* [x] Closes #1751 
* [x] I work here.
* [x] Tested manually, see below.
* [x] Added documentation to the schema 
* [x] Requires docs.microsoft.com update, filed as https://github.com/MicrosoftDocs/terminal/issues/26
* [x] I'm a core contributor.

## Detailed Description of the Pull Request / Additional comments
- Weights can be specified according to the OpenType specification values. We accept either the friendly name or the numerical value that applies to each weight.
- Weights are carried through per-profile and sent into the renderer.
- Weights are carried through to the TSF/IME overlay.
- The names are restricted to the set seen at https://docs.microsoft.com/en-us/uwp/api/windows.ui.text.fontweights.
- There are alternate names at https://docs.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_weight for the same values (ultra-black is just an alias for extra-black at 950).

## Validation Steps Performed
- Cascadia Code normal
![image](https://user-images.githubusercontent.com/18221333/82480181-46117380-9a88-11ea-9436-a5fe4ccd4350.png)

- Cascadia Code bold
![image](https://user-images.githubusercontent.com/18221333/82480202-4f9adb80-9a88-11ea-9e27-a113b41387f5.png)

- Segoe UI Semilight
![image](https://user-images.githubusercontent.com/18221333/82480306-73f6b800-9a88-11ea-93f7-d773ab7ccce8.png)

- Segoe UI Black
![image](https://user-images.githubusercontent.com/18221333/82480401-9688d100-9a88-11ea-957c-0c8e03a8cc29.png)

- Segoe UI 900 (value for Black)
![image](https://user-images.githubusercontent.com/18221333/82480774-26c71600-9a89-11ea-8cf6-aaeab1fd0747.png)
2020-05-20 20:17:17 +00:00
Dustin L. Howett (MSFT) b46d393061
Switch the Cascadia projects to til::color where it's easily possible to do so (#5847)
This pull request moves swaths of Cascadia to use `til::color` for color
interop. There are still some places where we use `COLORREF`, such as in
the ABI boundaries between WinRT components.

I've also added two more til::color helpers - `with_alpha`, which takes
an existing color and sets its alpha component, and a
`Windows::UI::Color` convertor pair.

Future direction might include a `TerminalSettings::Color` type at the
idl boundary so we can finally stop using UInt32s (!) for color.

## Validation Steps Performed
Tested certain fragile areas:
* [x] setting the background with OSC 11
* [x] setting the background when acrylic is in use (which requires
  low-alpha)
2020-05-15 22:43:00 +00:00
Mike Griese 88ed94d2ac
Implement drag-drop paste for text (#5865)
## Summary of the Pull Request

Implements drag-dropping text onto a `TermControl`, in addition to the already supported drag-drop of files.

## References
* [StandardDataFormats](https://docs.microsoft.com/en-us/uwp/api/windows.applicationmodel.datatransfer.standarddataformats?view=winrt-18362)
* [StandardDataFormats::Text](https://docs.microsoft.com/en-us/uwp/api/windows.applicationmodel.datatransfer.standarddataformats.text?view=winrt-18362#Windows_ApplicationModel_DataTransfer_StandardDataFormats_Text)
* [GetTextAsync](https://docs.microsoft.com/en-us/uwp/api/windows.applicationmodel.datatransfer.datapackageview.gettextasync?view=winrt-18362)

## PR Checklist
* [x] Closes #5863
* [x] I work here
* [ ] Tests added/passed
* [n/a] Requires documentation to be updated

## Detailed Description of the Pull Request / Additional comments

Oh I also changed "Copy path to file" to "Paste path to file". I thought that actually made more sense here

## Validation Steps Performed
* Tested manually that text and files still work.
2020-05-12 14:46:47 -07:00
Dustin L. Howett (MSFT) fcd5bb39f0
Stop trying to set selection endpoints when there's no selection (#5855)
It turns out that we weren't really adequately guarding calls to
SetSelectionEnd and friends.

We're clearing the active selection when the window resizes, but we're
doing so by nulling out the std::optional<Selection> it lives in. Later,
though, when we set the selection endpoint we're using "_selection->".

Optional's operator-> has undefined behavior when the optional doesn't
have a value in it.

In our case, it looks like it was returning whatever the value was prior
to it being emptied out. PivotSelection would attempt to access an
out-of-bounds coordinate when the buffer got smaller during a resize.

The solution is to guard both levels of selection endpoint manipulation
in a check for an active selection.

Apparently, this accounts for somewhere between 7% and 14% of our
crashes on 1.0RC1.

Repro was:
Use Win+Arrow to snap the window while in the middle of a selection.
2020-05-12 11:23:10 -07:00
Michael Niksa d01317c9db
Add renderer settings to mitigate blurry text for some graphics devices
## Summary of the Pull Request
Adds user settings to adjust rendering behavior to mitigate blurry text on some devices.

## References
- #778 introduced this, almost certainly.

## PR Checklist
* [x] Closes #5759, mostly
* [x] I work here.
* [ ] We need community verification that this will help.
* [x] Updated schema and schema doc.
* [x] Am core contributor. Discussed in Monday sync meeting and w/ @DHowett-MSFT. 

## Detailed Description of the Pull Request / Additional comments
When we switched from full-screen repaints to incremental rendering, it seems like we exposed a situation where some display drivers and hardware combinations do not handle scroll and/or dirty regions (from `IDXGISwapChain::Present1`) without blurring the data from the previous frame. As we're really close to ship, I'm offering two options to let people in this situation escape it on their own. We hope in the future to figure out what's actually going on here and mitigate it further in software, but until then, these escape hatches are available.

1. `experimental.rendering.forceFullRepaint` - This one restores the pre-778 behavior to the Terminal. On every single frame paint, we'll invalidate the entire screen and repaint it.
2. `experimental.rendering.software` - This one uses the software WARP renderer instead of using the hardware and display driver directly. The theory is that this will sidestep any driver bugs or hardware variations.

One, the other, or both of these may be field-applied by users who are experiencing this behavior. 

Reverting #778 completely would also resolve this, but it would give back our largest performance win in the whole Terminal project. We don't believe that's acceptable when seemingly a majority of the users are experiencing the performance benefit with no detriment to graphical display.

## Validation Steps Performed
- [x] Flipped them on and verified with the debugger that they are being applied to the rendering pipeline
- [ ] Gave a private copy to community members in #5759 and had them try whether one, the other, or both resolved their issue.
2020-05-11 14:54:03 -07:00
Leon Liang 17bd8b5750
Grab the write lock before updating the font (#5654)
## Summary of the Pull Request
Based on the discussion in #5479, it seems that the crash is caused by a race condition due to not obtaining the write lock before calling `TriggerFontChange`.

I'm not totally sure if my approach is the right one, but I've taken the lock out of `_RefreshSize` since it seems like all calls of `_RefreshSize` come after a `TriggerFontChange`/`UpdateFont`. Then I just 
made sure all calls of `TriggerFontChange`/`UpdateFont` are preceded with a `LockForWriting`.

## PR Checklist
* [x] Closes #5479
* [x] CLA signed.
* [x] Tests added/passed

## Validation Steps Performed
Scrolling to change my font size does not kill the Terminal anymore! 🙌
2020-04-30 00:05:29 +00:00
Mike Griese ea02128f11
Remove the title tag from the generated HTML (#5595)
Web apps apparently will paste the <title> as plaintext before the
actual HTML content from the clipboard. Since this seems to be
widespread behavior across web apps, this isn't just a bug in _some
app_, this is a bug on us. We shouldn't emit the title. 

This PR removes the title tag from the generated HTML.

Closes #5347
2020-04-29 16:41:56 -07:00
Carlos Zamora 6d4107206a
Notify UIA when Search finds something (#5478)
## Summary of the Pull Request
Before this, if the Search Box was open, new selections would not notify automation clients. This was because the UiaEngine (responsible for notifying automation clients) would remain disabled. Now we're enabling it before the early exit in TermControl's FocusHandler

## PR Checklist
* [X] Will close issue #5421 upon verification

## Validation Steps Performed
Verified using NVDA.
Narrator's behavior is not impacted, for some reason.
2020-04-29 10:36:45 -07:00
Michael Niksa 98ac196cec
Lock when changing selection endpoint on wheel/auto-scroll (#5551)
Takes the lock inside two routines in `TermControl` that were changing
the selection endpoint while a rendering frame was still drawing,
resulting in several variants of graphical glitches from double-struck
selection boxes to duplicated line text.

## References
- Introduced with #5185

## PR Checklist
* [x] Closes #5471 
* [x] Already signed life away to company.
* [x] Manual tests passed since it's visual.
* [x] No extra doc besides the comments.
* [x] Am core contributor: Roar.

The renderer base and specific renderer engine do a lot of work to
remember the previous selection and compensate for scrolling regions and
deltas between frames. However, all that work doesn't quite match up
when the endpoints are changed out from under it. Unfortunately,
`TermControl` doesn't have a robust history of locking correctly in step
with the renderer nor does the renderer's `IRenderData` currently
provide any way of 'snapping' state at the beginning of a frame so it
could work without a full lock. So the solution for now is for the
methods that scroll the display in `TermControl` to take the lock that
is shared with the renderer's frame painter so they can't change out of
sync.

## Validation Steps Performed
- Opened terminal with Powershell core.
  Did ls a bunch of times.
  Clicked to make selection and held mouse button while wheeling around.
- Opened terminal with Powershell core.;
  Did ls a bunch of times.
  Clicked to make selection and dragged mouse outside the window to make
  auto scroll happen.
- Opened terminal with Powershell core.
  Did ls a bunch of times.
  Clicked to make selection and released. Wheeled around like a crazy
  person to make sure I didn't regress that.
2020-04-24 15:14:43 -07:00
Mike Griese c803893c22
Use grayscale AA always on non-opaque backgrounds (#5277)
## Summary of the Pull Request

When we're on acrylic, we can't have cleartype text unfortunately. This PR changes the DX renderer to force cleartype runs of text that are on a non-opaque background to use grayscale AA instead.

## References

Here are some of the URLS I was referencing as writing this:

* https://stackoverflow.com/q/23587787
* https://docs.microsoft.com/en-us/windows/win32/direct2d/supported-pixel-formats-and-alpha-modes#cleartype-and-alpha-modes
* https://devblogs.microsoft.com/oldnewthing/20150129-00/?p=44803
* https://docs.microsoft.com/en-us/windows/win32/api/d2d1/ne-d2d1-d2d1_layer_options
* https://docs.microsoft.com/en-us/windows/win32/direct2d/direct2d-layers-overview#d2d1_layer_parameters1-and-d2d1_layer_options1
* https://docs.microsoft.com/en-us/windows/win32/api/dcommon/ne-dcommon-d2d1_alpha_mode?redirectedfrom=MSDN#cleartype-and-alpha-modes
* https://stackoverflow.com/a/26523006

Additionally:
* This was introduced in #4711 

## PR Checklist
* [x] Closes #5098
* [x] I work here
* [ ] Tests added/passed
* [n/a] Requires documentation to be updated

## Detailed Description of the Pull Request / Additional comments

Basically, if you use cleartype on a light background, what you'll get today is the text foreground color _added_ to the background. This will make the text look basically invisible. 

So, what I did was use some trickery with `PushLayer` to basically create a layer where the text would be forced to render in grayscale AA. I only enable this layer pushing business when both:
  * The user has enabled cleartype text
  * The background opacity < 1.0

This plumbs some information through from the TermControl to the DX Renderer to make this smooth.

## Validation Steps Performed

Opened both cleartype and grayscale panes SxS, and messed with the opacity liberally.
2020-04-24 17:16:34 +00:00
Michael Niksa 8ea9b327f3
Adjusts High DPI scaling to enable differential rendering (#5345)
## Summary of the Pull Request
- Adjusts scaling practices in `DxEngine` (and related scaling practices in `TerminalControl`) for pixel-perfect row baselines and spacing at High DPI such that differential row-by-row rendering can be applied at High DPI.

## References
- #5185 

## PR Checklist
* [x] Closes #5320, closes #3515, closes #1064
* [x] I work here.
* [x] Manually tested.
* [x] No doc.
* [x] Am core contributor. Also discussed with some of them already via Teams.

## Detailed Description of the Pull Request / Additional comments

**WAS:**
- We were using implicit DPI scaling on the `ID2D1RenderTarget` and running all of our processing in DIPs (Device-Independent Pixels). That's all well and good for getting things bootstrapped quickly, but it leaves the actual scaling of the draw commands up to the discretion of the rendering target.
- When we don't get to explicitly choose exactly how many pixels tall/wide and our X/Y placement perfectly, the nature of floating point multiplication and division required to do the presentation can cause us to drift off slightly out of our control depending on what the final display resolution actually is.
- Differential drawing cannot work unless we can know the exact integer pixels that need to be copied/moved/preserved/replaced between frames to give to the `IDXGISwapChain1::Present1` method. If things spill into fractional pixels or the sizes of rows/columns vary as they are rounded up and down implicitly, then we cannot do the differential rendering.

**NOW:**
- When deciding on a font, the `DxEngine` will take the scale factor into account and adjust the proposed height of the requested font. Then the remainder of the existing code that adjusts the baseline and integer-ifies each character cell will run naturally from there. That code already works correctly to align the height at normal DPI and scale out the font heights and advances to take an exact integer of pixels.
- `TermControl` has to use the scale now, in some places, and stop scaling in other places. This has to do with how the target's nature used to be implicit and is now explicit. For instance, determining where the cursor click hits must be scaled now. And determining the pixel size of the display canvas must no longer be scaled.
- `DxEngine` will no longer attempt to scale the invalid regions per my attempts in #5185 because the cell size is scaled. So it should work the same as at 96 DPI.
- The block is removed from the `DxEngine` that was causing a full invalidate on every frame at High DPI.
- A TODO was removed from `TermControl` that was invalidating everything when the DPI changed because the underlying renderer will already do that.

## Validation Steps Performed
* [x] Check at 150% DPI. Print text, scroll text down and up, do selection.
* [x] Check at 100% DPI. Print text, scroll text down and up, do selection.
* [x] Span two different DPI monitors and drag between them.
* [x] Giant pile of tests in https://github.com/microsoft/terminal/pull/5345#issuecomment-614127648

Co-authored-by: Dustin Howett <duhowett@microsoft.com>
Co-authored-by: Mike Griese <migrie@microsoft.com>
2020-04-22 14:59:51 -07:00
Carlos Zamora 9dd5f6e8b9
Remove singleLine copy from Shift+Click, CopyOnSelect (#5346)
This fixes an issue where a shift+click selection with `copyOnSelect`
enabled would result in copying the content as a single line.

## Detailed Description of the Pull Request / Additional comments
I've been thinking a lot about this issue and how it relates to the
copy/paste discussions we've been having over the past few weeks.
Considering that the majority of users want regular copy, it makes sense
to default to that in this case too.

If a user wants to perform a special form of copy, it makes sense that
they should use their custom keybinding to accomplish that. This kind of
behavior aligns with that kind of philosophy.

## Validation Steps Performed

The following scenarios were tested with `copyOnSelect` enabled.
| scenario                                | behavior                      |
|-----------------------------------------|-------------------------------|
| Perform a shift+click selection         | content copied w/ newlines    |
| right-click                             | clipboard paste               |
| copy keybinding (`singleLine` disabled) | content copied w/ newlines    |
| copy keybinding (`singleLine` enabled)  | content copied as single line |

Closes #4737
2020-04-14 13:19:22 -07:00
Dustin L. Howett (MSFT) e61968ca87
Add support for renderer backoff, don't FAIL_FAST on 3x failures, add UI (#5353)
## Summary of the Pull Request
Renderer: Add support for backoff and auto-disable on failed retry

This commit introduces a backoff (150ms * number of tries) to the
renderer's retry logic (introduced in #2830). It also changes the
FAIL_FAST to a less globally-harmful render thread disable, so that we
stop blowing up any application hosting a terminal when the graphics
driver goes away.

In addition, it adds a callback that a Renderer consumer can use to
determine when the renderer _has_ failed, and a public method to kick it
back into life.

Fixes #5340.

This PR also wires up TermControl so that it shows some UI when the renderer tastes clay.

![image](https://user-images.githubusercontent.com/14316954/79266118-f073f680-7e4b-11ea-8b96-5588a13aff3b.png)

![image](https://user-images.githubusercontent.com/14316954/79266125-f36ee700-7e4b-11ea-9314-4280e9149461.png)

## PR Checklist
* [x] Closes #5340
* [x] cla
* [ ] Tests added/passed
* [ ] Requires documentation to be updated
* [x] I've discussed this with core contributors already.

## Validation Steps Performed

I tested this by dropping the number of retries to 1 and forcing a TDR while doing `wsl cmatrix -u0`. It picked up exactly where it left off.

As a bonus, you can actually still type into the terminal when it's graphically suspended (and `exit` still works.). The block is _entirely graphical_.
2020-04-14 20:11:47 +00:00
Michael Niksa 79684bf821
Render row-by-row instead of invalidating entire screen (#5185)
## Summary of the Pull Request
Adjusts DirectX renderer to use `til::bitmap` to track invalidation
regions. Uses special modification to invalidate a row-at-a-time to
ensure ligatures and NxM glyphs continue to work.

## References
Likely helps #1064

## PR Checklist
* [x] Closes #778
* [x] I work here.
* [x] Manual testing performed. See Performance traces in #778.
* [x] Automated tests for `til` changes.
* [x] Am core contributor. And discussed with @DHowett-MSFT.

## Detailed Description of the Pull Request / Additional comments
- Applies `til::bitmap` as the new invalidation scheme inside the
  DirectX renderer and updates all entrypoints for collecting
  invalidation data to coalesce into this structure.
- Semi-permanently routes all invalidations through a helper method
  `_InvalidateRectangle` that will expand any invalidation to cover the
  entire line. This ensures that ligatures and NxM glyphs will continue
  to render appropriately while still allowing us to dramatically reduce
  the number of lines drawn overall. In the future, we may come up with
  a tighter solution than line-by-line invalidation and can modify this
  helper method appropriately at that later date to further scope the
  invalid region.
- Ensures that the `experimental.retroTerminalEffects` feature continues
  to invalidate the entire display on start of frame as the shader is
  applied at the end of the frame composition and will stack on itself
  in an amusing fashion when we only redraw part of the display.
- Moves many member variables inside the DirectX renderer into the new
  `til::size`, `til::point`, and `til::rectangle` methods to facilitate
  easier management and mathematical operations. Consequently adds
  `try/catch` blocks around many of the already-existing `noexcept`
  methods to deal with mathematical or casting failures now detected by
  using the support classes.
- Corrects `TerminalCore` redraw triggers to appropriately communicate
  scrolling circumstances to the renderer so it can optimize the draw
  regions appropriately.
- Fixes an issue in the base `Renderer` that was causing overlapping
  scroll regions due to behavior of `Viewport::TrimToViewport` modifying
  the local. This fix is "good enough" for now and should go away when
  `Viewport` is fully migrated to `til::rectangle`.
- Adds multiplication and division operators to `til::rectangle` and
  supporting tests. These operates will help scale back and forth
  between a cell-based rectangle and a pixel-based rectangle. They take
  special care to ensure that a pixel rectangle being divided downward
  back to cells will expand (with the ceiling division methods) to cover
  a full cell when even one pixel inside the cell is touched (as is how
  a redraw would have to occur).
- Blocks off trace logging of invalid regions if no one is listening to
  optimize performance.
- Restores full usage of `IDXGISwapChain1::Present1` to accurately and
  fully communicate dirty and scroll regions to the underlying DirectX
  framework. This additional information allows the framework to
  optimize drawing between frames by eliminating data transfer of
  regions that aren't modified and shuffling frames in place. See
  [Remarks](https://docs.microsoft.com/en-us/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgiswapchain1-present1#remarks)
  for more details.
- Updates `til::bitmap` set methods to use more optimized versions of
  the setters on the `dynamic_bitset<>` that can bulk fill bits as the
  existing algorithm was noticeably slow after applying the
  "expand-to-row" helper to the DirectX renderer invalidation.
- All `til` import hierarchy is now handled in the parent `til.h` file
  and not in the child files to prevent circular imports from happening.
  We don't expect the import of any individual library file, only the
  base one. So this should be OK for now.

## Validation Steps Performed
- Ran `cmatrix`, `cmatrix -u0`, and `cacafire` after changes were made.
- Made a bunch of ligatures with `Cascadia Code` in the Terminal
  before/after the changes and confirmed they still ligate.
- Ran `dir` in Powershell and fixed the scrolling issues
- Clicked all over the place and dragged to make sure selection works.
- Checked retro terminal effect manually with Powershell.
2020-04-13 20:09:02 +00:00
Mike Griese 6f0f245dd0
Don't wait for a connection to finish when a control is closed (#5303)
## Summary of the Pull Request

When a pane is closed by a connection, we want to wait until the connection is actually `Closed` before we fire the actual `Closed` event. If the connection didn't close gracefully, there are scenarios where we want to print a message to the screen.

However, when a pane is closed by the UI, we don't really care to wait for the connection to be completely closed. We can just do it whenever. So I've moved that call to be on a background thread.

## PR Checklist
* [x] Closes #1996
* [x] I work here
* [ ] Tests added/passed
* [n/a] Requires documentation to be updated

## Detailed Description of the Pull Request / Additional comments
Previously we'd wait for the connection to close synchronously when closing tabs or panes. For misbehaving applications like `ssh.exe`, that could result in the `Close` needing to `WaitForSingleObject` _on the UI thread_. If the user closed the tab / pane either with a keybinding or with some other UI element, they don't really care to see the error message anymore. They just want the pane closed. So there's no need to wait for the actual connection to close - the app can just continue on with whatever it was doing.

## Validation Steps Performed
Messed around with closing tabs, panes, tabs with many panes, the entire window. Did this with keybindings, or by clicking on the 'x' on the tab, the 'x' on the window, or using middle-click.

I'm always scared of things like this, so there's a 50% chance this makes things horribly worse.
2020-04-09 23:27:56 +00:00
Dustin L. Howett (MSFT) 7936605cc9
Control: make sure we actually have a dispatcher in 100ms (#5292)
This fixes a silly regression introduced by 1299a839b. We would crash
when the connection updated the cursor as it was being torn down.
2020-04-09 12:08:06 -07:00
Dustin L. Howett (MSFT) 1299a839bd
Muffle updates to the cursor position to 1/~100ms (#5289)
This stops us from dispatching back-to-back terminal cursor position
updates to the TSF control before it has a chance to get back to us.

Fixes #5288.
2020-04-08 17:20:51 -07:00
Dustin L. Howett (MSFT) 5622f230a8
Control: Start the connection outside of lock (#5286)
When the connection printed text immediately, synchronously, as part of
Start() it would cause terminal to deadlock. We should start the
connection outside of lock.

The ConptyConnection would do this when it failed to launch something
(trivial repro: `wt -- xyz`).

The TelnetConnection would do this all the time, because local loopback
telnet is fast and easy.
2020-04-08 13:55:20 -07:00
Leonard Hecker a9c9714295
Delegate all character input to the character event handler (#4192)
My basic idea was that `WM_CHAR` is just the better `WM_KEYDOWN`.
The latter fails to properly support common dead key sequences like in
#3516.

As such I added some logic to `Terminal::SendKeyEvent` to make it return
false if the pressed key represents a printable character.
This causes us to receive a character event with a (hopefully) correctly
composed code unit, which then gets sent to `Terminal::SendCharEvent`.
`Terminal::SendCharEvent` in turn had to be modified to support
potentially pressed modifier keys, since `Terminal::SendKeyEvent` isn't
doing that for us anymore.
Lastly `TerminalInput` had to be modified heavily to support character
events with modifier key states. In order to do so I merged its
`HandleKey` and `HandleChar` methods into a single one, that now handles
both cases.
Since key events will now contain character data and character events
key codes the decision logic in `TerminalInput::HandleKey` had to be
rewritten.

## PR Checklist
* [x] CLA signed
* [x] Tests added/passed
* [x] I've discussed this with core contributors already.

## Validation Steps Performed

* See #3516.
* I don't have any keyboard that generates surrogate characters. Due to
  this I modified `TermControl::_SendPastedTextToConnection` to send the
  data to `_terminal->SendCharEvent()` instead. I then pasted the test
  string ""𐐌𐐜𐐬" and ensured that the new `TerminalInput::_SendChar`
  method still correctly assembles surrogate pairs.

Closes #3516
Closes #3554 (obsoleted by this PR)
Potentially impacts #391, which sounds like a duplicate of #3516
2020-04-07 19:09:28 +00:00
Dustin L. Howett (MSFT) e44dc2bcf8
Relax locking around the swapchain (#5225)
The terminal lock is really only for the terminal; since the renderer is
fully owned by the control, not the Terminal, and we'll only be
receiving swap chain events after we register them during
initialization, we don't need to lock before _or_ after firing off the
coroutine.

Fixes #5203.
2020-04-06 17:15:31 -07:00
Carlos Zamora 084b48a751
Rename copy keybinding arg (#5216)
## Summary of the Pull Request
`TrimWhitespace` is misleading. So it is now renamed as 'singleLine'. If true, it comes out as a single line! That makes more sense!

## PR Checklist
* [X] Closes #3824 

## Validation Steps Performed
Attempted the keybinding with both settings (and none set).
Attempted mouse copy with and without shift.
2020-04-02 23:10:28 +00:00
Mike Griese a12a6285f5
Manually pass mouse wheel messages to TermControls (#5131)
## Summary of the Pull Request

As we've learned in #979, not all touchpads are created equal. Some of them have bad drivers that makes scrolling inactive windows not work. For whatever reason, these devices think the Terminal is all one giant inactive window, so we don't get the mouse wheel events through the XAML stack. We do however get the event as a `WM_MOUSEWHEEL` on those devices (a message we don't get on devices with normally functioning trackpads).

This PR attempts to take that `WM_MOUSEWHEEL` and manually dispatch it to the `TermControl`, so we can at least scroll the terminal content.

Unfortunately, this solution is not very general purpose. This only works to scroll controls that manually implement our own `IMouseWheelListener` interface. As we add more controls, we'll need to continue manually implementing this interface, until the underlying XAML Islands bug is fixed. **I don't love this**. I'd rather have a better solution, but it seems that we can't synthesize a more general-purpose `PointerWheeled` event that could get routed through the XAML tree as normal. 

## References

* #2606 and microsoft/microsoft-ui-xaml#2101 - these bugs are also tracking a similar "inactive windows" / "scaled mouse events" issue in XAML

## PR Checklist
* [x] Closes #979
* [x] I work here
* [ ] Tests added/passed
* [n/a] Requires documentation to be updated

## Detailed Description of the Pull Request / Additional comments

I've also added a `til::point` conversion _to_ `winrt::Windows::Foundation::Point`, and some scaling operators for `point`

## Validation Steps Performed

* It works on my HP Spectre 2017 with a synaptics trackpad
  - I also made sure to test that `tmux` works in panes on this laptop
* It works on my slaptop, and DOESN'T follow this hack codepath on this machine.
2020-04-01 16:58:16 +00:00
Leon Liang ca6b54e652
Redraw TSFInputControl when Terminal cursor updates (#5135)
<!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? -->
## Summary of the Pull Request
This PR will allow TSFInputControl to redraw its Canvas and TextBlock in response to when the Terminal cursor position updates. This will fix the issue where during Korean composition, the first symbol of the next composition will appear on top of the previous composed character. Since the Terminal Cursor updates a lot, I've added some checks to see if the TSFInputControl really needs to redraw. This will also decrease the number of actual redraws since we receive a bunch of `LayoutRequested` events when there's no difference between them.

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist
* [x] Closes #4963
* [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [x] Tests added/passed

<!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
Startup, teardown, CJK IME gibberish testing, making sure the IME block shows up in the right place.
2020-03-30 23:21:47 +00:00
Dustin L. Howett (MSFT) 5bcf0fc3de
Rework TermControl's initialization (#5051)
This commit rewrites a large swath of TermControl's initialization code.

* `TermControl` now _always_ has a `_terminal`; it will never be null
* Event registration for `_terminal` and any other available-at-init
  fixtures has been moved into the constructor.
* Event handlers how more uniformly check `_closing` if they interact
  with the _terminal.
* Swap chain attachment has been cleaned up and no longer uses a
  coroutine when it's spawned from the UI thread.
   * We have to register the renderer's swapchain change notification
     handler after we set the swap chain, otherwise it'll call us back
     when it initializes itself.
* `InitializeTerminal` now happens under the `_terminal`'s write lock
   * Certain things that InitializeTerminal were calling themselves
     attempted to take the lock. They no longer do so.
* TermControlAutomationPeer cannot take the read lock, because setting
  the scrollbar's `Maximum` during `InitializeTerminal` will trigger
  vivification of the automation peer tree; if it attempts to take the
  lock it will deadlock during initialization.
* `BlinkCursor` was renamed to `CursorTimerTick` because it's the "Tick"
  handler for the "CursorTimer".
* `DragDropHandler` was converted into a coroutine instead of just
  _calling_ a coroutine.

Caveats:

Terminal may not have a `_buffer` until InitializeTerminal happens.
There's a nasty coupling between RenderTarget and TextBuffer that means
that we need to have a renderer before we have a buffer.

There's a second nasty coupling between RenderThread and Renderer: we
can't create a RenderThread during construction because it needs to be
given a renderer, and we can't create a Renderer during construction
because it needs a RenderThread. We don't want to kick off a thread
during construction.

Testing:

I wailed on this by opening and closing and resizing terminals and panes
and tabs, up to a hundred open tabs and one tab with 51 panes. I set one
tab to update the title as fast as it possibly could and tested
teardown, zoom, resize, mouse movement, etc. while this was all
happening.

Closes #4613.
2020-03-26 16:25:11 -07:00
Mike Griese b3fa88eaed
Process actions sync. on startup; don't dupe nonexistent profile (#5090)
This PR has evolved to encapsulate two related fixes that I can't really
untie anymore.

#2455 - Duplicating a tab that doesn't exist anymore

This was the bug I was originally fixing in #4429. 

When the user tries to `duplicateTab` with a profile that doesn't exist
anymore (like might happen after a settings reload), don't crash.

As I was going about adding tests for this, got blocked by the fact that
the Terminal couldn't open _any_ panes while the `TerminalPage` was size
0x0. This had two theoretical solutions: 

* Fake the `TerminalPage` into thinking it had a real size in the test -
  probably possible, though I'm unsure how it would work in practice.
* Change `Pane`s to not require an `ActualWidth`, `ActualHeight` on
  initialization. 

Fortuately, the second option was something else that was already on my
backlog of bugs. 

#4618 - `wt` command-line can't consistently parse more than one arg

Presently, the Terminal just arbitrarily dispatches a bunch of handlers
to try and handle all the commands provided on the commandline. That's
lead to a bunch of reports that not all the commands will always get
executed, nor will they all get executed in the same order. 

This PR also changes the `TerminalPage` to be able to dispatch all the
commands sequentially, all at once in the startup. No longer will there
be a hot second where the commands seem to execute themselves in from of
the user - they'll all happen behind the scenes on startup. 

This involved a couple other changes areound the `TerminalPage`
* I had to make sure that panes could be opened at a 0x0 size. Now they
  use a star sizing based off the percentage of the parent they're
  supposed to consume, so that when the parent _does_ get laid out,
  they'll take the appropriate size of that parent.
* I had to do some math ahead of time to try and calculate what a
  `SplitState::Automatic` would be evaluated as, despite the fact that
  we don't actually know how big the pane will be. 
* I had to ensure that `focus-tab` commands appropriately mark a single
  tab as focused while we're in startup, without roundtripping to the
  Dispatcher thread and back

## References

#4429 - the original PR for #2455
#5047 - a follow-up task from discussion in #4429
#4953 - a PR for making panes use star sizing, which was immensly
        helpful for this PR.

## Detailed Description of the Pull Request / Additional comments

`CascadiaSettings::BuildSettings` can throw if the GUID doesn't exist.
This wraps those calls up with a try/catch.

It also adds a couple tests - a few `SettingsTests` for try/catching
this state. It also adds a XAML-y test in `TabTests` that creates a
`TerminalPage` and then performs som UI-like actions on it. This test
required a minor change to how we generate the new tab dropdown - in the
tests, `Application::Current()` is _not_ a `TerminalApp::App`, so it
doesn't have a `Logic()` to query. So wrap that in a try/catch as well.

While working on these tests, I found that we'd crash pretty agressively
for mysterious reasons if the TestHostApp became focused while the test
was running. This was due to a call in
`TSFInputControl::NotifyFocusEnter` that would callback to
`TSFInputControl::_layoutRequested`, which would crash on setting the
`MaxSize` of the canvas to a negative value. This PR includes a hotfix
for that bug as well. 

## Validation Steps Performed

* Manual testing with a _lot_ of commands in a commandline
* run the tests
* Team tested in selfhost

Closes #2455
Closes #4618
2020-03-25 17:03:32 -07:00
Dustin L. Howett (MSFT) 499f24a29e
Rework and simplify selection in TermControl (#5096)
This commit rewrites selection handling at the TermControl layer.
Previously, we were keeping track of a number of redundant variables
that were easy to get out of sync.

The new selection model is as follows:

* A single left click will always begin a _pending_ selection operation
* A single left click will always clear a selection (#4477)
* A double left click will always begin a word selection
* A triple left click will always begin a line selection
* A selection will only truly start when the cursor moves a quarter of
  the smallest dimension of a cell (usually its width) in any direction
  _This eliminates the selection of a single cell on one click._
  (#4282, #5082)
* We now keep track of whether the selection has been "copied", or
  "updated" since it was last copied. If an endpoint moves, it is
  updated. For copy-on-select, it is only copied if it's updated.
  (#4740)

Because of this, we can stop tracking the position of the focus-raising
click, and whether it was part of click-drag operation. All clicks can
_become_ part of a click-drag operation if the user drags.

We can also eliminate the special handling of single cell selection at
the TerminalCore layer: since TermControl determines when to begin a
selection, TerminalCore no longer needs to know whether copy on select
is enabled _or_ whether the user has started and then backtracked over a
single cell. This is now implicit in TermControl.

Fixes #5082; Fixes #4477
2020-03-25 21:09:49 +00:00
Josh Soref 5de9fa9cf3
ci: run spell check in CI, fix remaining issues (#4799)
This commit introduces a github action to check our spelling and fixes
the following misspelled words so that we come up green.

It also renames TfEditSes to TfEditSession, because Ses is not a word.

currently, excerpt, fallthrough, identified, occurred, propagate,
provided, rendered, resetting, separate, succeeded, successfully,
terminal, transferred, adheres, breaks, combining, preceded,
architecture, populated, previous, setter, visible, window, within,
appxmanifest, hyphen, control, offset, powerpoint, suppress, parsing,
prioritized, aforementioned, check in, build, filling, indices, layout,
mapping, trying, scroll, terabyte, vetoes, viewport, whose
2020-03-25 11:02:53 -07:00
Mike Griese e05507982d
Make sure to account for the size the padding _will be_ scaled to (#5091)
* [x] Fixes #2061 for good this time
2020-03-23 22:24:33 +00:00
Leon Liang cddac25726
Ignore KeyDown events during Alt-Numpad Input (#4965)
## Summary of the Pull Request
Alt-Numpad# input would be escaping each numkey before sending it through. This would result in some weird behavior, for example, in powershell, where the first alt-numpad# would start digit argument and once the user releases alt, a character is sent through and digit argument would repeat that character X times. To resolve this, we simply need to ignore KeyDowns where Alt is held and a Numpad# is pressed. 

Once Alt is released, we'll receive a character through `TSFInputControl`, not `TermControl::CharacterHandler`. It seems that the `CoreTextEditContext` in `TSFInputControl` intercepts the character before it gets to `TermControl`. TSF will then send the received character through as normal.

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist
* [x] Closes #1401 
* [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [x] Tests added/passed

<!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
Testing various combinations of Alt-Numpad# consistently sends through only one instance of the expected symbols.
2020-03-18 17:58:10 +00:00
Mike Griese 38058a7a86
Add support for setting the cursor visibility in Terminal (#4902)
Adds support for setting the cursor visibility in Terminal. Visibility
is a property entirely independent from whether the cursor is "on" or
not. The cursor blinker _should_ change the "IsOn" property. It was
actually changing the "Visible" property, which was incorrect. This PR
additionally corrects the naming of the method used by the cursor
blinker, and makes it do the right thing.

I added a pair of tests, one taken straight from conhost. In
copy-pasting that test, I took it a step further and implemented
`^[[?12h`, `^[[?12l`, which enables/disables cursor blinking, for the
`TerminalCore`. THIS DOES NOT ADD SUPPORT FOR DISABLING BLINKING IN THE
APP. Conpty doesn't emit the blinking on/off sequences quite yet, but
when it _does_, the Terminal will be ready.

## References
* I'd bet this conflicts with #2892
* This isn't a solution for #1379
* There shockingly isn't an issue for cursor blink state via conpty...?

## PR Checklist
* [x] Closes #3093
* [x] Closes #3499
* [x] Closes #4644
* [x] I work here
* [x] Tests added/passed
* [n/a] Requires documentation to be updated
2020-03-13 17:39:42 +00:00
Carlos Zamora ae71dce2ca
Synthesize VT mouse events and add mouse support to Terminal (#4859)
## Summary of the Pull Request
Make TerminalControl synthesize mouse events and Terminal send them to
the TerminalInput's MouseInput module.

The implementation here takes significant inspiration from how we handle
KeyEvents.

## References
Closes #545 - VT Mouse Mode (Terminal)
References #376 - VT Mouse Mode (ConPty)

### TerminalControl
- `_TrySendMouseEvent` attempts to send a mouse event via TermInput.
  Similar to `_TrySendKeyEvent`
- Use the above function to try and send the mouse event _before_
  deciding to modify the selection

### TerminalApi
- Hookup (re)setting the various modes to handle VT Input
- Terminal is _always_ in VT Input mode (important for #4856)

### TerminalDispatch
- Hookup (re)setting the various modes to handle VT Input

### TerminalInput
- Convert the mouse input position from viewport position to buffer
  position
- Then send it over to the MouseInput in TerminalInput to actually do it
  (#4848)

## Validation Steps Performed
Tests should still pass.
2020-03-12 17:44:28 -07:00
Abhijeet Viswam e596943ed2
Make ctrl+shift+scroll toggle acrylic on/off at extrema (#4853)
If UseAcrylic is disabled, CTRL+SHIFT+SCROLL would enable it, without
having to change the setting in profile.json manually.

1. Set "useAcrylic" to false for the any profile in profile.json
2. Open terminal window for that profile.
3. CTRL+SHIFT+MouseScroll
   Acrylic background opacity should change according to mouse scroll

## PR Checklist
* [x] CLA signed.
* [x] Tested manually
* [x] Updated documentation

Closes #661
2020-03-11 10:48:58 -07:00
Leon Liang 61d635367b
Show InputPanel on focus and pointer press (#4867)
<!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? -->
## Summary of the Pull Request
I originally thought that setting `TSFInputControl::_editContext.InputPaneDisplayPolicy` to be Automatic would allow the InputPanel to show and hide automatically when `TSFInputControl` gains and loses focus. It doesn't seem to behave that way, so we'll show the InputPanel manually. 

I'll show the panel during `PointerPressedHandler` and during `GotFocusHandler`. A user will have the on-screen keyboard pop up when getting focus, but if they close the keyboard, they can simply re-tap on the terminal to bring it back up.

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist
* [x] Closes #3639
* [x] CLA signed.
* [x] Tests added/passed

## Validation Steps Performed
Played on my surfaces book with the on screen keyboard by closing/tapping on the terminal and using the search box.
2020-03-10 17:55:57 +00:00
Leon Liang dd8813e0be
Ignore right-click copy when copy on select is enabled (#4819)
<!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? -->
## Summary of the Pull Request
Right clicking on a focused tab while Copy On Select is active currently copies any active selection. This is because `PointerReleasedHandler` doesn't check for the mouse button that was released. 
During a mouse button release, only the left mouse button release should be doing anything.

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist
* [x] Closes #4740
* [x] CLA signed.
* [x] Tests added/passed

<!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
These are the scenarios I've tested. They're a combination of in focus/out of focus, Copy On Select on/off, left/right click pressed and their move and release variants.

From Out of Focus:
- Left Click = Focus
- Left Click Move = Focus + Selection
- Left Click Release
  - CoS on = Copy
  - CoS off = Nothing
- Shift Left Click = Focus
- Right Click 
  - Focus 
  - CoS on = Paste
  - CoS off = Copy if Active Selection, Paste if not.
- Right Click Move = Nothing
- Right Click Release = Nothing

From In Focus
- Left Click = Selection if CoS off
- Left Click Move = Selection
- Left Click Release
  - CoS on = Copy
  - CoS off = Nothing
- Shift Left Click = Set Selection Anchor
- Right Click 
  - CoS on = Paste
  - CoS off = Copy if Active Selection, Paste if not.
- Right Click Move = Nothing
- Right Click Release = Nothing
2020-03-10 14:59:16 +00:00
Carlos Zamora e79a421f3a
Abstract GetTextForClipboard() for UIA (#4578)
## Summary of the Pull Request
`GetTextForClipboard` already exists in the TextBuffer. It makes sense to use that for UIA as well. This changes the behavior or `GetText()` such that it does not remove leading/trailing whitespace anymore. That is more of an expected behavior.

## References
This also contributes to...
- #4509: UIA Box Selection
- #2447: UIA Signaling for Selection
- #1354: UIA support for Wide Glyphs
Now that the expansion occurs at before render-time, the selection anchors are an accurate representation of what is selected. We just need to move GetText to the TextBuffer. Then we can have those three issues just rely on code from the text buffer. This also means ConHost gets some of this stuff for free 😀

## Detailed Description of the Pull Request / Additional comments
- `TextBuffer::GetTextForClipboard()` --> `GetText()`
- `TextBuffer::GetText()` no longer requires GetForegroundColor/GetBackgroundColor. If either of these are not defined, we return a `TextAndColor` with only the `text` field populated.
- renamed a few parameters for copying text to the clipboard for clarity
- Updated `UiaTextRange::GetText()` to use `TextBuffer::GetText()`

## Validation Steps Performed
Manual tests for UIA using accessibility insights and Windows Terminal's copy action (w/ and w/out shift)

Added tests as well.
2020-03-09 08:17:34 -07:00
Mike Griese 852f0aac34
Fix a rampant crash in TSFInputControl when opening new tabs (#4830)
## Summary of the Pull Request

We're deref'ing a null `_terminal`. Don't do that. This is a _okay_ fix, mostly to stem the bleeding. @DHowett-MSFT's got a mind for a real fix to #4166, but this isn't it.

## PR Checklist
* [x] related to #4166
* [x] I work here
* [ ] Tests added/passed
* [n/a] Requires documentation to be updated
2020-03-07 03:20:04 +00:00
msftbot[bot] a3d68d2b21
Tunnel F7 keypresses directly into special handlers in TermControl (#4807)
The Xaml input stack doesn't allow an application to suppress the "caret
browsing" dialog experience triggered when you press F7.

The official recommendation from the Xaml team is to catch F7 before we
hand it off.

This commit introduces a special F7 handler and an ad-hoc implementation of event bubbling.
Runtime classes implementing a custom IF7Listener interface are
considered during a modified focus parent walk to determine who can
handle F7 specifically.

If the recipient control handles F7, we suppress the message completely.

This event bubbler has some minor issues -- the search box will not be
able to receive F7 because its parent control implements the handler.
Since search is already mostly a text box, it doesn't _need_ special
caret browsing functionality as far as I can tell.

TermControl implements its OnF7Pressed handler by synthesizing a
keybindings event and an event to feed into Terminal Core directly.

It's not possible to create a synthetic KeyPressRoutedEvent; if it were,
I would have just popped one into the traditional input queue. :)

Fixes #638.
2020-03-05 20:35:46 +00:00
msftbot[bot] c6879d75af
Make Korean IME input more consistent (#4796)
## Summary of the Pull Request
Korean IME was not working correctly due to way we were clearing the input buffer inside of `TSFInputControl`. We wanted to clear our input buffer and tell TSF to clear its input buffer as well when we receive a `CompositionCompleted` event. This works fine in some IME languages such as Chinese and Japanese. However, Korean IME composes characters differently in such a way where we can't tell TSF to clear their buffer during a `CompositionCompleted` event because it would clear the character that triggered the `CompositionCompleted` event in the first place.

The solution in this PR is to keep our `_inputBuffer` intact until the user presses <kbd>Enter</kbd> or <kbd>Esc</kbd>, in which case we clear our buffer and the TSF buffer. I've chosen these two keys because it seems to make sense to clear the buffer after text is sent to the terminal with <kbd>Enter</kbd>, and <kbd>Esc</kbd> usually means to cancel a current composition anyway.

This means we need to keep track of our last known "Composition Start Point", which is represented by `_activeTextStart`. Whenever we complete a composition, we'll send the portion of the input buffer between `_activeTextStart` and the end of the input buffer to the terminal. Then, we'll update `_activeTextStart` to be the end of the input buffer so that the next time we send text to the terminal, we'll only send the portion of our buffer that's "active".

## PR Checklist
* [x] Closes #4226
* [x] CLA signed
* [x] Tests added/passed

## Validation Steps Performed
Manual testing with Chinese, Japanese, and Korean IME.
2020-03-04 20:01:01 +00:00
Carlos Zamora a3eb427d8b
clear selection on viewport/font resize (#4777)
## Summary of the Pull Request
Match conhost behavior and clear selection on viewport/font resize.

## PR Checklist
* [X] Closes #1165 

## Validation Steps Performed
Retried attached bug repro steps
2020-03-02 20:45:31 +00:00
Carlos Zamora 0e672fac08
Move rect expansion to textbuffer; refactor selection code (#4560)
- When performing chunk selection, the expansion now occurs at the time
  of the selection, not the rendering of the selection
- `GetSelectionRects()` was moved to the `TextBuffer` and is now shared
  between ConHost and Windows Terminal
- Some of the selection variables were renamed for clarity
- Selection COORDs are now in the Text Buffer coordinate space
- Fixes an issue with Shift+Click after performing a Multi-Click
  Selection

## References
This also contributes to...
- #4509: UIA Box Selection
- #2447: UIA Signaling for Selection
- #1354: UIA support for Wide Glyphs

Now that the expansion occurs at before render-time, the selection
anchors are an accurate representation of what is selected. We just need
to move `GetText` to the `TextBuffer`. Then we can have those three
issues just rely on code from the text buffer. This also means ConHost
gets some of this stuff for free 😀

### TextBuffer
- `GetTextRects` is the abstracted form of `GetSelectionRects`
- `_ExpandTextRow` is still needed to handle wide glyphs properly

### Terminal
- Rename...
    - `_boxSelection` --> `_blockSelection` for consistency with ConHost
    - `_selectionAnchor` --> `_selectionStart` for consistency with UIA
    - `_endSelectionPosition` --> `_selectionEnd` for consistency with
      UIA
- Selection anchors are in Text Buffer coordinates now
- Really rely on `SetSelectionEnd` to accomplish appropriate chunk
  selection and shift+click actions

## Validation Steps Performed
- Shift+Click
- Multi-Click --> Shift+Click
- Chunk Selection at...
    - top of buffer
    - bottom of buffer
    - random region in scrollback

Closes #4465
Closes #4547
2020-02-27 16:42:26 -08:00
Carlos Zamora 74cd9db383
Define Automation Properties for TermControl (#4732)
Defines the following automation properties for a Terminal Control:
- [**Orientation**](https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.automation.peers.automationpeer.getorientationcore):
  - The orientation of the control
  - None --> Vertical
- [**Name**](https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.automation.peers.automationpeer.getnamecore):
  - The name as used by assistive technology and other Microsoft UI
    Automation clients. Generally presented by automation clients as the
    primary way to identify an element (along with the control type)
  - "" --> <profile name>
- [**HelpText**](https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.automation.peers.automationpeer.gethelptextcore):
  - The help text. Generally presented by automation clients if
    requested by the user. This would be something that you would normally
    expect to appear from tooltips.
  - "" --> <tab title>
- [**LiveSetting**](https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.automation.peers.automationpeer.getlivesettingcore):
  - reports the live setting notification behavior. A representation of
    how assertive this control should be when content changes.
  - none --> Polite

## Detailed Description of the Pull Request / Additional comments
ProfileName had to be added to the TerminalSettings (IControlSettings)
to pass that information along to the automation peer. In the rare event
that somebody purposefully decided to make their ProfileName empty, we
fallback to the tab title.


## Validation Steps Performed
Verified using Accessibility Insights and inspect.exe

This is are some examples of the information a general user can expect
to receive about a Terminal Control.

- Type: Terminal Control
- Name: Command Prompt
- Help Text (if requested): Command Prompt - ping bing.com

- Type: Terminal Control
- Name: Ubuntu
- Help Text (if requested): cazamor@PC-cazamor:/mnt/c/Users/cazamor$

Note, it is generally read by an automation client as follows:
"<type>, <name>"

References #2099 - Automation Properties for TerminalControl, Search Box
References #2142 - Localization

Closes #2142
2020-02-27 16:37:56 -08:00
Dustin L. Howett (MSFT) 1de07aa3ab
Convert TermControl to .xaml (#4729)
This commit removes all of the custom UI initialization code in
TermControl and replaces it with a xaml file. Some dead or reundant code
was removed as part of this refactoring.

It also fixes two (quasi-related) issues:

* The search box, on first launch, was offset by the scrollbar even if
  the scrollbar was invisible.
* The scrollbar state wasn't hot-reloadable.
2020-02-26 16:35:16 -08:00
Leon Liang 61e5917fe8
Allow IME input in Search Box (#4723)
## Summary of the Pull Request
Currently, when the user attempts to type using IME while the Search Box is focused, the input goes to the terminal instead. This is due to the fact that the `TSFInputControl` assumes it's in control whenever TermControl gets focus. So, it'll intercept IME input before the Search Box receives it. We simply need to modify `TermControl::GotFocus` to check if the SearchBox has focus. If it does, `TSFInputControl::NotifyFocusEnter` shouldn't be called.

As a small side fix, I've also disabled the terminal cursor blinking when the Search Box has focus.

Thinking a little further, if we have more features in the future that behave like search box (i.e. advanced tab switcher, or any other XAML controls that pop up) and require text input, we might need to create a sort of "AnyOtherTextControlInFocus" function to see if TSFInputControl should receive focus or not.

## PR Checklist
* [x] Closes #4434
* [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
Search works as expected with IME. Composition picker appears underneath Search Box when typing IME in the Search Box. Clicking outside of the Search Box still returns control to TSFInputControl/TermControl.

Terminal Cursor blinks when it has focus, and doesn't when the Search Box has focus.
2020-02-26 19:28:01 +00:00
Dustin L. Howett (MSFT) 0efdc8f004
TermControl: don't use narrow when narrow_cast will do (#4721)
This will help one cause of #4623, which looks like it may be caused by
floats being truncated when stuffed into LONGs for UIA purposes.
2020-02-25 17:10:07 -08:00
Mike Griese 8a5407c13a
Add support for cleartype text antialiasing (#4711)
## Summary of the Pull Request

I needed to do something to keep sane so today I day of learned about antialiasing. This PR adds the ability to specify the `"antialiasingMode"` as a setting.
* "antialiasingMode": "grayscale": the current behavior, `D2D1_TEXT_ANTIALIAS_MODE_GRAYSCALE`
* "antialiasingMode": "cleartype": use `D2D1_TEXT_ANTIALIAS_MODE_CLEARTYPE` instead


## PR Checklist
* [x] Closes #1298
* [x] I work here
* [ ] I didn't add tests 
* [x] Requires documentation to be updated

## Detailed Description of the Pull Request / Additional comments
Grayscale:
 
![image](https://user-images.githubusercontent.com/18356694/75173847-2373f680-56f5-11ea-8896-c1cf04c61d41.png)



Cleartype:
![image](https://user-images.githubusercontent.com/18356694/75173854-25d65080-56f5-11ea-9de1-e2d1c343cae5.png)

 


Side-by-side (can you tell which is which?) <!-- grayscale, cleartype -->
 
![image](https://user-images.githubusercontent.com/18356694/75173864-28d14100-56f5-11ea-8bdd-d47a60fbbe4d.png)
2020-02-25 22:19:57 +00:00
Carlos Zamora d0c8221c6e
Make ScreenInfoUiaProvider::GetSelection() Return One Selection (#4466)
## Summary of the Pull Request
We used to return multiple text ranges to represent one selection. We only support one selection at a time, so we should only return one range.

Additionally, I moved all TriggerSelection() calls to the renderer from Terminal to TermControl for consistency. This ensures we only call it _once_ when we make a change to our selection state.

## References
#2447 - helps polish Signaling for Selection
#4465 - This is more apparent as the problem holding back Signaling for Selection

## PR Checklist
* [x] Closes #4452 

Tested using Accessibility Insights.
2020-02-20 23:03:50 +00:00
Leon Liang 2dec894515
Fix duplicate copyOnSelect when clicking on an unfocused terminal (#4596)
## Summary of the Pull Request
Currently, clicking on an unfocused terminal with a selection active will trigger `copyOnSelect`. This is because the check for `copyOnSelect` and copying to the clipboard is bound to when the Pointer is released. This works fine for when a user performs a click-drag selection, but it inadvertently also triggers when the user performs a single click on an unfocused terminal. We expect `copyOnSelect` to trigger only on the first time a selection is completed. 

This PR will allow the user to single click on an unfocused terminal that has a selection active without triggering a copyOnSelect. It also ensures that any click-drag selection, whether it's on an unfocused or focused terminal, will trigger copyOnSelect.

## PR Checklist
* [x] Closes #4255

## Validation Steps Performed
Performed manual testing involving permutations of multiple panes, tabs, in focus, and out of focus.
2020-02-20 18:30:10 +00:00
James 8392d6b647 Fix touchpad and touchscreen scrolling (#4554)
Fixed inconsistent scrolling when using both touchscreen and precision
touchpad.

Scrolling jumpiness is caused by rounding errors. Instead of retrieving
the current scrolling value from `GetScrollOffset`, which is already
rounded in `int`, let the scrolling operation to operate on
`_scrollBar`'s `Value` directly (which uses `double`) in
`TermControl.cpp`.

TermControl now also respects WHEEL_DELTA, which it was previously
ignoring, to determine how many scroll wheel detents were used.

Testing scrolling on the following scenario manually:

- nonscrollable terminal (e.g. the window is large enough to contain the
  current buffer).
- scrolling to the topmost and bottom-most.
- scrolling TUI apps such as `nano` and `more` in WSL.
- after clearing the terminal, both in cmd and WSL.

... has the same behavior between using touchscreen or precision trackpad
and regular mouse wheel.

Closes #4554 (original pull request)
Closes #1066
Closes #4542
2020-02-18 19:01:58 -08:00
Leon Liang 38ebf48d79
throwing in the simplest fix i can think of while i ponder about what the real fix should be (#4559)
## Summary of the Pull Request
The issue seems to be how `SwapChainScaleChanged` gets fired and attempts to tell the renderer
to `UpdateDPI` when the renderer is gone. So, as a quick bandaid, we'll put a quick check to only do the thing if the renderer is alive.

## PR Checklist
* [x] Closes #4539
* [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
Held my new tab button for about thirty seconds then held the close tab button until all tabs closed without a crash.
2020-02-13 00:42:06 +00:00
Leon Liang 7836da07dd
Fix click-drag selection on an unfocused Terminal (#4506)
## Summary of the Pull Request
This PR tries to address some of the weird interactions with pointer pressed events when the Terminal isn't in focus. Here's the four things that have changed as part of this PR;

1. This PR will allow the user to be able to make a selection with a click-drag without having to first perform a single click on a tab/pane to bring it to focus. 
2. Another weird bug that's fixed in this PR is where trying to make a selection on an unfocused tab when it already has a selection active will simply extend the existing selection instead of making a new one.
3. Not related to the issue that his PR closes: a right click will now focus the tab/pane.

I've made sure that we still have the existing functionality where a single click on an unfocused tab/pane does not make a single-cell selection and just focuses the tab/pane.

## PR Checklist
* [x] Closes #4282
* [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
Played around with all sorts of selection when in-focus and out of focus with multiple panes and tabs.
Unit tests still pass as well.
2020-02-13 00:32:50 +00:00
Michael Niksa deef9f3cdc
Gather data on profile customization and tab settings to help us improve defaults (#4534)
## Summary of the Pull Request
This will collect some user choices related to profiles and tab settings to help us understand if and how we should change the in-built defaults.

## PR Checklist
* [x] Closes #3855
* [x] I work here.
* [x] Manual test only.
* [x] Meh, no doc update.
* [x] Am core contributor.

## Detailed Description of the Pull Request / Additional comments
The following data is collected with examples of the types of questions we intend to answer:
1. What is the name of the executable attached to the PTY? (What shells are popular? Should we focus our testing on them? Are there any common ones we are blind to that we should know about?)
- "Microsoft.Windows.Terminal.Connection" {e912fe7b-eeb6-52a5-c628-abe388e5f792}
- "ConPtyConnected" event
- "SessionGuid" value = WT_SESSION 
- "Client" value = Name of EXE
2. Is Acrylic used on a tab? And with what opacity? (Do people really want acrylic? Should it be default? What opacity is most pleasing in our context?)
- "Microsoft.Windows.Terminal.App" {24a1622f-7da7-5c77-3303-d850bd1ab2ed}
- "TabInformation" event
- "EventVer" value is now 1u
- "UseAcrylic" value is now TRUE/FALSE on the setting choice
- "TintOpacity" value is now Float on the setting choice
3. What font are people choosing? (Do people move away from Cascadia Code? Which ones are the most popular for us to validate when updating the renderer?)
- "Microsoft.Windows.Terminal.App" {24a1622f-7da7-5c77-3303-d850bd1ab2ed}
- "TabInformation" event
- "FontFace" value is now string font from settings
4. What keybindings do people choose to customize (Add or Remove)? (Are there extremely common keys that folks bind or unbind that we should have adjusted by default in a fresh install?)
- "Microsoft.Windows.Terminal.App" {24a1622f-7da7-5c77-3303-d850bd1ab2ed}
- "CustomKeybindings" event
- "Keybindings" value is the entire JSON segment that describes the user keybindings from `settings.json`.
5. Do people change their default profile from the PowerShell one we set? If so, to what? (Should we not set PowerShell as the default? Should we adjust the ranking of our dynamic generators to favor the most popular ones to bubble to the top?)
- "Microsoft.Windows.Terminal.App" {24a1622f-7da7-5c77-3303-d850bd1ab2ed}
- "CustomDefaultProfile" event
- "DefaultProfile" value is the GUID of the chosen profile

## Validation Steps Performed
1. Implemented the events
2. Launched the ETL channel viewer
3. Triggered the events
4. Saw the data come out
2020-02-12 20:02:48 +00:00
Dustin Howett 5bbf61af8c WHITESPACE ONLY: TermControl->CRLF 2020-02-12 11:06:46 -08:00
Dustin L. Howett (MSFT) af2d110e89
Don't say "drop files" for things that aren't files (#4541)
Fixes #4481.

## Validation Steps Performed
Dragged things.
2020-02-12 15:30:33 +00:00
greg904 4f6916c2da
Fix scrollbar doesn't update viewport after window resize (#3344)
<!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? -->
## Summary of the Pull Request

Fixes a bug where scrolling up/down doesn't update the viewport after the window is resized and in other cases. Also changes other things, please read the detailed description.

<!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> 
## References

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

<!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

There are two ways scroll can happen:
- the user scrolls using the scroll bar and the `Terminal` is notified
- the `Terminal` changed the viewport and the scroll bar is updated to reflect the change

The code to notify the `Terminal` that the user scrolled is in the event handler for when the scroll bar's value changes. However this poses a problem because it means that when the `Terminal` changes the viewport, the scroll bar is updated so it would then also notify the `Terminal` that the scroll changed. But it already knows because it's coming from itself!

To fix this, the `TermControl` class had a member called `_lastScrollOffset` that would be set when the `Terminal` decides to change the viewport so that the event handler for the scroll bar could check the new scroll value against `_lastScrollOffset` and if it matches, then everything is fine and there is nothing to update.

This is what happens when the `Terminal` changes the viewport:
1. set `_lastScrollOffset`
2. dispatch job on the UI thread: update the scrollbar which is going to call the event handler which is going to check for `_lastScrollOffset` and clear it

There are two bugs introduced by this approach:
1. (I am not sure about this.) The dispatcher appears to store jobs in a LIFO stack so it sometimes reorders the "update the scrollbar" jobs when there are too many. When I run `1..10000` on PowerShell, then I get this from the event handler (format: `_lastScrollOffset newValue`):
    ```
    8988 8988
    8989 8989
    8990 8990
    8992 8991
    8993 8992
    ...
    9001 8997
    9001 8998
    9001 8999
    9001 9000
    9001 9001
    9001 8985
    9001 8968
    9001 8953
    ...
    9001 7242
    9001 7226
    9001 7210
    ```
    This causes the following issues:
    1. `_lastScrollOffset` wouldn't be reset because it wouldn't be equal to the current scroll bar value (see example above) so the next scrolls wouldn't do anything as the event handler would still be waiting for an event with the good scroll bar value which would never happen because it happened earlier
    2. the `TermControl` would notify the `Terminal` about its own scroll
2. If the `Terminal` didn't actually changed its viewport but still called the `TermControl::_TerminalScrollPositionChanged` method, then it would set the `_lastScrollOffset` member as usual but the scroll bar value change event handler would not be called because it is only called when the value actually changes so the `_lastScrollOffset` member wouldn't be cleared and subsequent scroll bar value change events would be ignored because again the event handler would still be waiting for an event with the good scroll bar value which would never happen. This is actually the reason for #1494: when the window is resized, the `Terminal` will call `TermControl::_TerminalScrollPositionChanged` even if the scroll position didn't actually change (444de5b166/src/cascadia/TerminalCore/Terminal.cpp (L183)). Maybe this should also be fixed in another PR?

I replaced `_lastScrollOffset` by a flag `_isTerminalInitiatedScroll`. I set the flag just before and unset it just after the terminal changes the scrollbar on the UI thread to eliminate the race conditions and the bug when the scroll bar's value doesn't actually change.

Other changes:
- I also fixed a potential bug where if the user scrolls just after the terminal updates the viewport, it would en up ignoring the user scroll. To do this, when the user scrolls, I cancel any update with `_willUpdateScrollBarToMatchViewport`.
- I also removed the original `ScrollViewport` method because it was not used anywhere and I think it can potentially create confusion (and therefore bugs) because this method updates the viewport but not the scroll bar unlike `KeyboardScrollViewport` which functions as you would expect. I then renamed `KeyboardScrollViewport` into `ScrollViewport`. So, now, there is only one method to scroll the viewport from the `TermControl`. Please, tell me if this shouldn't be in this PR.
- I also removed `_terminal->UserScrollViewport(viewTop);` in the `KeyboardScrollViewport` method because it will be updated later anyways in the scroll bar's value change event handler because of the `_scrollBar.Value(viewTop);`.

<!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

I tested manually by doing this:
- For bug 1:
    1. Start the terminal
    2. Run the `1..30000` command in PowerShell and wait for it to end (maybe more if you have a fast  computer?)
    3. Hold left click on the scrollbar slider and start moving it
- For bug 2:
    1. Start the terminal
    2. Run the `1..100` command in PowerShell and wait for it to end
    3. Resize the window horizontally
    4. Hold left click on the scrollbar slider and start moving it

Without this patch, the viewport doesn't update.
With the patch, the viewport updates correctly.
2020-02-10 23:15:30 +00:00
Josh Soref a13ccfd0f5
Fix a bunch of spelling errors across the project (#4295)
Generated by https://github.com/jsoref/spelling `f`; to maintain your repo, please consider `fchurn`

I generally try to ignore upstream bits. I've accidentally included some items from the `deps/` directory. I expect someone will give me a list of items to drop, I'm happy to drop whole files/directories, or to split the PR into multiple items (E.g. comments/locals/public).

Closes #4294
2020-02-10 20:40:01 +00:00
Leon Liang 06e9605fc5
shift click selection end works, clear selection and discard key press for esc works (#4404)
This PR addresses the following two issues:

#4203: If a selection is active, a <kbd>shift</kbd>-LeftClick will set the SelectionEnd to where the pointer is.  
#3911: Currently, any keypress will clear selection, and will pass through to the terminal. This PR will make it so that if a selection is active, _any_ keypress will clear the selection and then any keypress _except_ <kbd>esc</kbd> will pass through to the terminal.

## PR Checklist
* [x] Closes #4203; Closes #3911
* [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
Played around a whole bunch with shift-clicking selections and regular clicking selections.
Also played around with selections and dismissing with all sorts of keypresses and keychords.
Tests all pass still!
2020-01-31 01:15:35 +00:00
Mike Griese 4ad77d9ff7
Add support for dragging and dropping paths onto the Terminal (#4323)
## Summary of the Pull Request

I took the code from conhost that handles this and just copy-pasted it into the terminal codebase.

## References

Original conhost code:
027f1228cb/src/interactivity/win32/windowproc.cpp (L854-L889)


## PR Checklist
* [x] Closes #904
* [x] I work here
* [ ] Tests added/passed
* [n/a] Requires documentation to be updated

## Detailed Description of the Pull Request / Additional comments

Okay it was a little more complicated than that. I had `IslandWindow` handle the drop, which then raises a generic event for `AppHost` to handle. `AppHost` handles this by writing the path as input to the terminal, traversing `AppLogic`, `TerminalPage` and finally landing in `TermControl`

## Validation Steps Performed
Tested manually with both paths with and without spaces.
2020-01-30 20:13:57 +00:00
James Holderness 8c46e740e8 Remove unneeded c_str() conversions (#4358)
* Remove unneeded c_str() calls when converting an hstring to a wstring_view.

* Remove unneeded c_str() calls when constructing a FontInfo class with a wstring face name.

* Remove unneeded winrt::to_hstring calls when passing a wstring to a method that expects an hstring.

* Remove unneeded c_str() calls when passing an hstring to a method that already accepts hstrings without conversion.

* Remove unneeded c_str() and data() calls when explicitly constructing an hstring from a wstring.
2020-01-27 10:23:13 -08:00
Mike Griese 830c22b73e Add support for commandline args to wt.exe (#4023)
## Summary of the Pull Request

Adds support for commandline arguments to the Windows Terminal, in accordance with the spec in #3495

## References

* Original issue: #607
* Original spec: #3495

## PR Checklist
* [x] Closes #607
* [x] I work here
* [x] Tests added/passed
* [ ] We should probably add some docs on these commands
* [x] The spec (#3495) needs to be merged first!

## Detailed Description of the Pull Request / Additional comments

🛑 **STOP** 🛑 - have you read #3495 yet? If you haven't, go do that now.

This PR adds support for three initial sub-commands to the `wt.exe` application:
* `new-tab`: Used to create a new tab.
* `split-pane`: Used to create a new split.
* `focus-tab`: Moves focus to another tab.

These commands are largely POC to prove that the commandlines work. They're not totally finished, but they work well enough. Follow up work items will be filed to track adding support for additional parameters and subcommands

Important scenarios added:
* `wt -d .`: Open a new wt instance in the current working directory #878
* `wt -p <profile name>`: Create a wt instance running the given profile, to unblock  #576, #1357, #2339
* `wt ; new-tab ; split-pane -V`: Launch the terminal with multiple tabs, splits, to unblock #756 

## Validation Steps Performed

* Ran tests
* Played with it a bunch
2020-01-27 15:34:12 +00:00
Dustin L. Howett (MSFT) 82f302b714 Shut down all controls under a tab before we remove it from the list (#4337)
This commit introduces a new recursive pane shutdown that will give all
controls under a tab a chance to clean up their state before beign
detached from the UI. It also reorders the call to LastTabClosed() so
that the application does not exit before the final connections are
terminated.

It also teaches TSFInputControl how to shut down to avoid a dramatic
platform bug.

Fixes #4159.
Fixes #4336.

## PR Checklist
* [x] CLA signed
* [x] I've discussed this with core contributors already.

## Validation Steps Performed
Validated through manual terminal teardown within and without the debugger, given a crazy number of panes and tabs.
2020-01-23 22:12:20 +00:00
Michael Kitzan 3ac32af848 Converts Dispatcher().RunAsync to WinRT Coroutines (#4051)
<!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? -->
## Summary of the Pull Request
This PR turns all* instances of `Dispatcher().RunAsync` to WinRT coroutines 👌. 
This was good coding fodder to fill my plane ride ✈️. Enjoy your holidays everyone!

*With the exception of three functions whose signatures cannot be changed due to inheritance and function overriding in `TermControlAutomationPeer` [`L44`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L44), [`L58`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L58),  [`L72`](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalControl/TermControlAutomationPeer.cpp#L72). 

<!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> 
## References

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist
* [x] Closes #3919
* [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [ ] Tests added/passed
* [ ] Requires documentation to be updated
* [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #3919

<!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments
My thought pattern here was to minimally disturb the existing code where possible. So where I could, I converted existing functions into coroutine using functions (like in the [core example](https://github.com/microsoft/terminal/issues/3919#issue-536598706)). For ~the most part~ all instances, I used the format where [`this` is accessed safely within a locked scope](https://github.com/microsoft/terminal/issues/3919#issuecomment-564730620). Some function signatures were changed to take objects by value instead of reference, so the coroutines don't crash when the objects are accessed past their original lifetime. The [copy](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1132) and [paste](https://github.com/microsoft/terminal/blob/master/src/cascadia/TerminalApp/TerminalPage.cpp#L1170) event handler entry points were originally set to a high priority; however, the WinRT coroutines don't appear to support a priority scheme so this priority setting was not preserved in the translation.

<!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
Compiles and runs, and for every event with a clear trigger repro, I triggered it to ensure crashes weren't introduced.
2020-01-10 03:29:49 +00:00
mcpiroman d4c527607a Snap to character grid when resizing window (#3181)
When user resizes window, snap the size to align with the character grid
(like e.g. putty, mintty and most unix terminals). Properly resolves
arbitrary pane configuration (even with different font sizes and
padding) trying to align each pane as close as possible.

It also fixes terminal minimum size enforcement which was not quite well
handled, especially with multiple panes.

This PR does not however try to keep the terminals aligned at other user
actions (e.g. font change or pane split). That is to be tracked by some
other activity.

Snapping is resolved in the pane tree, recursively, so it (hopefully)
works for any possible layout.

Along the way I had to clean up some things as so to make the resulting
code not so cumbersome:
1. Pane.cpp: Replaced _firstPercent and _secondPercent with single
   _desiredSplitPosition to reduce invariants - these had to be kept in
   sync so their sum always gives 1 (and were not really a percent). The
   desired part refers to fact that since panes are aligned, there is
   usually some deviation from that ratio.
2. Pane.cpp: Fixed _GetMinSize() - it was improperly accounting for
   split direction
3. TerminalControl: Made dedicated member for padding instead of
   reading it from a control itself. This is because the winrt property
   functions turned out to be slow and this algorithm needs to access it
   many times. I also cached scrollbar width for the same reason.
4. AppHost: Moved window to client size resolution to virtual method,
   where IslandWindow and NonClientIslandWindow have their own
   implementations (as opposite to pointer casting).

One problem with current implementation is I had to make a long call
chain from the window that requests snapping to the (root) pane that
implements it: IslandWindow -> AppHost's callback -> App ->
TerminalPage -> Tab -> Pane. I don't know if this can be done better.

## Validation Steps Performed
Spam split pane buttons, randomly change font sizes with ctrl+mouse
wheel and drag the window back and forth.

Closes #2834
Closes #2277
2020-01-08 13:19:23 -08:00
Hannes Nel a60ed52064 Terminal uses system default for number of rows scrolled at a t… (#3575)
The terminal will use the system setting to determine the number of lines to scroll at a time.
This can be overridden by adding rowsToScroll to app global settings file.
terminal will use the system setting if the app setting is 0, or not specified. No restart is needed to reflect setting changes in system or the settings file.

The default was hardcoded to 4 in the code with a todo comment. 1 works better on precision touchpads, where 4 scrolls too fast.

Co-authored-by: Hannes Nel <hannesne@microsoft.com>
2020-01-06 09:39:02 -08:00
David Teresi e2a66c4f1c Immediately show the cursor on terminal focus (#4032)
<!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? -->
## Summary of the Pull Request

Before, when a terminal window was focused, the blinking cursor would initially be hidden. This PR will immediately show the cursor when the window is focused, making it easier to keep track of the cursor.

<!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> 
## References

#3761

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

<!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments

I guess I'm the cursor guy now

<!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed

* Switched rapidly between different panes, different tabs and focused and unfocused the main window repeatedly.
2019-12-30 14:28:54 +00:00
Kaiyu Wang a322ff06f8
Fix Search non-blocking follow-ups (#4028)
* search box text localization and search parameters refactoring

* format fix

* remvove unecessary spaces

* Tooltips text localization, CR chanegs

* Move ESC handling to SearchBoxControl

* format check

* mark Esc key input as handled in SearchBoxControl
2019-12-20 17:35:31 -08:00
Kaiyu Wang d7ae8e6db9 Search - add search box control and implement search experience (#3590)
<!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? -->
This is the PR for feature Search: #605 
This PR includes the newly introduced SearchBoxControl in TermControl dir, which is the search bar for the search experience. And the codes that enable Search in Windows Terminal. 

<!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> 
The PR that migrates the Conhost search module: https://github.com/microsoft/terminal/pull/3279
Spec (still actively updating): https://github.com/microsoft/terminal/pull/3299
<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist
* [x] Closes #605 
* [ ] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [ ] Tests added/passed
* [ ] Requires documentation to be updated
* [ ] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #xxx

<!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here -->
These functionalities are included in the search experience. 
1. Search in Terminal text buffer. 
2. Automatic wrap-around. 
3. Search up or down switch by clicking different buttons.
4. Search case sensitively/insensitively by clicking a button.                                                                                                                                                S. Move the search box to the top/bottom by clicking a button. 
6. Close by clicking 'X'. 
7. Open search by ctrl + F.

When the searchbox is open, the user could still interact with the terminal by clicking the terminal input area. 

While I already have the search functionalities, currently there are still some known to-do works and I will keep updating my PR:

1. Optimize the search box UI, this includes:
                                                  1) Theme adaptation. The search box background and font color 
                                                       should change according to the theme, 
                                                  2) Add background. Currently the elements in search box are all
                                                      transparent. However, we need a background. 
                                                  3) Move button should be highlighted once clicked. 
2. Accessibility: search process should be able to performed without mouse. Once the search box is focused, the user should be able to navigate between all interactive elements on the searchbox using keyboard. 

<!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well -->

To test:
1. checkout this branch.
2. Build the project. 
3. Start Windows Terminal and press Ctrl+F
4. The search box should appear on the top right corner.
2019-12-17 15:52:37 +00:00
Michael Kitzan a3f3cc823c Fixed self capture in TermControl (#3908)
<!-- Enter a brief description/summary of your PR here. What does it fix/what does it change/how was it tested (even manually, if necessary)? -->
## Summary of the Pull Request
An asynchronous event handler capturing raw `this` in `TermControl` was causing an exception to be thrown when a scroll update event occurred after closing the active tab. This PR replaces all non-auto_revoke lambda captures in `TermControl` to capture (and validate) a `winrt::weak_ref` instead of using raw `this`.

<!-- Other than the issue solved, is this relevant to any other issues/existing PRs? --> 
## References

<!-- Please review the items on the PR checklist before submitting-->
## PR Checklist
* [x] Closes #2947
* [x] CLA signed. If not, go over [here](https://cla.opensource.microsoft.com/microsoft/Terminal) and sign the CLA
* [ ] Tests added/passed
* [ ] Requires documentation to be updated
* [x] I've discussed this with core contributors already. If not checked, I'm ready to accept this work might be rejected in favor of a different grand plan. Issue number where discussion took place: #2947

<!-- Provide a more detailed description of the PR, other things fixed or any additional comments/features here -->
## Detailed Description of the Pull Request / Additional comments
`TermControl` is already a WinRT type so no changes were required to enable the `winrt::weak_ref` functionality. There was only one strange change I had to make. In the destructor's helper function `Close`, I had to remove two calls to [`Stop`](https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.dispatchertimer.stop#Windows_UI_Xaml_DispatcherTimer_Stop) which were throwing under [some circumstances](https://github.com/microsoft/terminal/issues/2947#issuecomment-562914135). Fortunately, these calls don't appear to be critical, but definitely a spot to look into when reviewing this PR.

Beyond scrolling, any anomalous crash related to the following functionality while closing a tab or WT may be fixed by this PR:
- Settings updating
- Changing background color

<!-- Describe how you validated the behavior. Add automated tests wherever possible, but list manual validation steps taken as well -->
## Validation Steps Performed
Before these changes I was able to consistently repro the issue in #2947. Now, I can no longer repro the issue.
2019-12-13 13:28:35 +00:00
Mike Griese 9d42599939 Add some issue numbers for TODOs from #3468 (#3931)
## Summary of the Pull Request

The original PR had a few TODOs in it without issue numbers. IMO, this wasn't important enough to block the PR over. _Also I'm impatient and wanted that setting_. 

After I merged the PR I created the issues and added the numbers myself.

## References

## PR Checklist
* [x] Closes nothing, this just adds a couple TODOs
* [x] I work here
* [x] this _really_ doesn't need tests
* [x] This _is_ a docs update
2019-12-12 18:55:26 +00:00