Skip to content

Commit

Permalink
Add selection marker overlays for keyboard selection
Browse files Browse the repository at this point in the history
  • Loading branch information
carlos-zamora committed Aug 3, 2021
1 parent 841cd2a commit 2c52439
Show file tree
Hide file tree
Showing 11 changed files with 162 additions and 8 deletions.
24 changes: 24 additions & 0 deletions src/cascadia/TerminalControl/ControlCore.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
{
_terminal->ClearSelection();
_renderer->TriggerSelection();
_UpdateSelectionMarkersHandlers(*this, winrt::make<implementation::UpdateSelectionMarkersEventArgs>(true));
}

if (vkey == VK_ESCAPE)
Expand Down Expand Up @@ -817,6 +818,24 @@ namespace winrt::Microsoft::Terminal::Control::implementation
_terminal->SetSelectionAnchor(position);
}

Core::Point ControlCore::SelectionAnchor() const
{
auto lock = _terminal->LockForReading();
return til::point{ _terminal->SelectionStartForRendering() };
}

Core::Point ControlCore::SelectionEnd() const
{
auto lock = _terminal->LockForReading();
return til::point{ _terminal->SelectionEndForRendering() };
}

bool ControlCore::MovingStart() const
{
auto lock = _terminal->LockForReading();
return _terminal->MovingStart();
}

// Method Description:
// - Sets selection's end position to match supplied cursor position, e.g. while mouse dragging.
// Arguments:
Expand All @@ -843,6 +862,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
// save location (for rendering) + render
_terminal->SetSelectionEnd(terminalPosition);
_renderer->TriggerSelection();
_UpdateSelectionMarkersHandlers(*this, winrt::make<implementation::UpdateSelectionMarkersEventArgs>(true));
}

bool ControlCore::UpdateSelection(Core::SelectionDirection direction, Core::SelectionExpansion mode)
Expand All @@ -857,6 +877,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
auto lock = _terminal->LockForWriting();
_terminal->UpdateSelection(direction, mode);
_renderer->TriggerSelection();
_UpdateSelectionMarkersHandlers(*this, winrt::make<implementation::UpdateSelectionMarkersEventArgs>(false));
return true;
}

Expand Down Expand Up @@ -918,6 +939,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
{
_terminal->ClearSelection();
_renderer->TriggerSelection();
_UpdateSelectionMarkersHandlers(*this, winrt::make<implementation::UpdateSelectionMarkersEventArgs>(true));
}

// send data up for clipboard
Expand Down Expand Up @@ -1196,6 +1218,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
_terminal->SetBlockSelection(false);
search.Select();
_renderer->TriggerSelection();
_UpdateSelectionMarkersHandlers(*this, winrt::make<implementation::UpdateSelectionMarkersEventArgs>(true));
}
}

Expand Down Expand Up @@ -1386,6 +1409,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
}

_renderer->TriggerSelection();
_UpdateSelectionMarkersHandlers(*this, winrt::make<implementation::UpdateSelectionMarkersEventArgs>(true));
}

void ControlCore::AttachUiaEngine(::Microsoft::Console::Render::IRenderEngine* const pEngine)
Expand Down
4 changes: 4 additions & 0 deletions src/cascadia/TerminalControl/ControlCore.h
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ namespace winrt::Microsoft::Terminal::Control::implementation
bool HasSelection() const;
bool CopyOnSelect() const;
Windows::Foundation::Collections::IVector<winrt::hstring> SelectedText(bool trimTrailingWhitespace) const;
Core::Point SelectionAnchor() const;
Core::Point SelectionEnd() const;
bool MovingStart() const;
void SetSelectionAnchor(til::point const& position);
void SetEndSelectionPoint(til::point const& position);
bool UpdateSelection(Core::SelectionDirection direction, Core::SelectionExpansion mode);
Expand Down Expand Up @@ -165,6 +168,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
TYPED_EVENT(RaiseNotice, IInspectable, Control::NoticeEventArgs);
TYPED_EVENT(TransparencyChanged, IInspectable, Control::TransparencyChangedEventArgs);
TYPED_EVENT(ReceivedOutput, IInspectable, IInspectable);
TYPED_EVENT(UpdateSelectionMarkers, IInspectable, Control::UpdateSelectionMarkersEventArgs);
// clang-format on

private:
Expand Down
4 changes: 4 additions & 0 deletions src/cascadia/TerminalControl/ControlCore.idl
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,9 @@ namespace Microsoft.Terminal.Control
Boolean HasSelection { get; };
IVector<String> SelectedText(Boolean trimTrailingWhitespace);
Boolean UpdateSelection(Microsoft.Terminal.Core.SelectionDirection direction, Microsoft.Terminal.Core.SelectionExpansion mode);
Microsoft.Terminal.Core.Point SelectionAnchor { get; };
Microsoft.Terminal.Core.Point SelectionEnd { get; };
Boolean MovingStart { get; };

String HoveredUriText { get; };
Windows.Foundation.IReference<Microsoft.Terminal.Core.Point> HoveredCell { get; };
Expand Down Expand Up @@ -100,6 +103,7 @@ namespace Microsoft.Terminal.Control
event Windows.Foundation.TypedEventHandler<Object, NoticeEventArgs> RaiseNotice;
event Windows.Foundation.TypedEventHandler<Object, TransparencyChangedEventArgs> TransparencyChanged;
event Windows.Foundation.TypedEventHandler<Object, Object> ReceivedOutput;
event Windows.Foundation.TypedEventHandler<Object, UpdateSelectionMarkersEventArgs> UpdateSelectionMarkers;

};
}
1 change: 1 addition & 0 deletions src/cascadia/TerminalControl/EventArgs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@
#include "ScrollPositionChangedArgs.g.cpp"
#include "RendererWarningArgs.g.cpp"
#include "TransparencyChangedEventArgs.g.cpp"
#include "UpdateSelectionMarkersEventArgs.g.cpp"
12 changes: 12 additions & 0 deletions src/cascadia/TerminalControl/EventArgs.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
#include "ScrollPositionChangedArgs.g.h"
#include "RendererWarningArgs.g.h"
#include "TransparencyChangedEventArgs.g.h"
#include "UpdateSelectionMarkersEventArgs.g.h"
#include "cppwinrt_utils.h"

namespace winrt::Microsoft::Terminal::Control::implementation
Expand Down Expand Up @@ -131,4 +132,15 @@ namespace winrt::Microsoft::Terminal::Control::implementation

WINRT_PROPERTY(double, Opacity);
};

struct UpdateSelectionMarkersEventArgs : public UpdateSelectionMarkersEventArgsT<UpdateSelectionMarkersEventArgs>
{
public:
UpdateSelectionMarkersEventArgs(const bool clearMarkers) :
_ClearMarkers(clearMarkers)
{
}

WINRT_PROPERTY(bool, ClearMarkers, false);
};
}
5 changes: 5 additions & 0 deletions src/cascadia/TerminalControl/EventArgs.idl
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,9 @@ namespace Microsoft.Terminal.Control
{
Double Opacity { get; };
}

runtimeclass UpdateSelectionMarkersEventArgs
{
Boolean ClearMarkers { get; };
}
}
79 changes: 71 additions & 8 deletions src/cascadia/TerminalControl/TermControl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
_core.TransparencyChanged({ this, &TermControl::_coreTransparencyChanged });
_core.RaiseNotice({ this, &TermControl::_coreRaisedNotice });
_core.HoveredHyperlinkChanged({ this, &TermControl::_hoveredHyperlinkChanged });
_core.UpdateSelectionMarkers({ this, &TermControl::_updateSelectionMarkers });
_interactivity.OpenHyperlink({ this, &TermControl::_HyperlinkHandler });
_interactivity.ScrollPositionChanged({ this, &TermControl::_ScrollPositionChanged });

Expand Down Expand Up @@ -358,6 +359,11 @@ namespace winrt::Microsoft::Terminal::Control::implementation
const auto bg = newAppearance.DefaultBackground();
_changeBackgroundColor(bg);

// Update selection markers
Windows::UI::Xaml::Media::SolidColorBrush selectionBackgroundBrush{ til::color{ newAppearance.SelectionBackground() } };
SelectionStartIcon().Foreground(selectionBackgroundBrush);
SelectionEndIcon().Foreground(selectionBackgroundBrush);

// Set TSF Foreground
Media::SolidColorBrush foregroundBrush{};
foregroundBrush.Color(static_cast<til::color>(newAppearance.DefaultForeground()));
Expand Down Expand Up @@ -1651,6 +1657,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation

_updateScrollBar->Run(update);
_updatePatternLocations->Run();
_updateSelectionMarkers(nullptr, winrt::make<UpdateSelectionMarkersEventArgs>(false));
}

// Method Description:
Expand Down Expand Up @@ -2446,8 +2453,8 @@ namespace winrt::Microsoft::Terminal::Control::implementation
_core.ClearHoveredCell();
}

winrt::fire_and_forget TermControl::_hoveredHyperlinkChanged(IInspectable sender,
IInspectable args)
winrt::fire_and_forget TermControl::_hoveredHyperlinkChanged(IInspectable /*sender*/,
IInspectable /*args*/)
{
auto weakThis{ get_weak() };
co_await resume_foreground(Dispatcher());
Expand All @@ -2470,12 +2477,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
HyperlinkTooltipBorder().BorderThickness(newThickness);

// Compute the location of the top left corner of the cell in DIPS
const til::size marginsInDips{ til::math::rounding, GetPadding().Left, GetPadding().Top };
const til::point startPos{ lastHoveredCell.Value() };
const til::size fontSize{ til::math::rounding, _core.FontSize() };
const til::point posInPixels{ startPos * fontSize };
const til::point posInDIPs{ posInPixels / SwapChainPanel().CompositionScaleX() };
const til::point locationInDIPs{ posInDIPs + marginsInDips };
const til::point locationInDIPs{ _toPosInDips(lastHoveredCell.Value()) };

// Move the border to the top left corner of the cell
OverlayCanvas().SetLeft(HyperlinkTooltipBorder(),
Expand All @@ -2487,10 +2489,71 @@ namespace winrt::Microsoft::Terminal::Control::implementation
}
}

winrt::fire_and_forget TermControl::_updateSelectionMarkers(IInspectable /*sender*/, Control::UpdateSelectionMarkersEventArgs args)
{
auto weakThis{ get_weak() };
co_await resume_foreground(Dispatcher());
if (weakThis.get() && args)
{
if (_core.HasSelection() && !args.ClearMarkers())
{
// show/update selection markers
// figure out which endpoint to move, get it and the relevant icon (hide the other icon)
const auto movingStart{ _core.MovingStart() };
const auto selectionAnchor{ movingStart ? _core.SelectionAnchor() : _core.SelectionEnd() };
const auto& icon{ movingStart ? SelectionStartIcon() : SelectionEndIcon() };
const auto& otherIcon{ movingStart ? SelectionEndIcon() : SelectionStartIcon() };
icon.Opacity(1);
otherIcon.Opacity(0);

// Compute the location of the top left corner of the cell in DIPS
const til::point locationInDIPs{ _toPosInDips(selectionAnchor) };

// Move the icon to the top left corner of the cell
SelectionCanvas().SetLeft(icon,
(locationInDIPs.x() - SwapChainPanel().ActualOffset().x));
SelectionCanvas().SetTop(icon,
(locationInDIPs.y() - SwapChainPanel().ActualOffset().y));
}
else
{
// hide selection markers
SelectionStartIcon().Opacity(0);
SelectionEndIcon().Opacity(0);
}
}
}

til::point TermControl::_toPosInDips(const til::point terminalCellPos)
{
const til::size marginsInDips{ til::math::rounding, GetPadding().Left, GetPadding().Top };
const til::size fontSize{ til::math::rounding, _core.FontSize() };
const til::point posInPixels{ terminalCellPos * fontSize };
const til::point posInDIPs{ posInPixels / SwapChainPanel().CompositionScaleX() };
return posInDIPs + marginsInDips;
}

void TermControl::_coreFontSizeChanged(const int fontWidth,
const int fontHeight,
const bool isInitialChange)
{
// scale the selection markers to be the size of a cell
auto scaleIconMarker = [fontWidth, fontHeight](Windows::UI::Xaml::Controls::FontIcon icon) {
const auto size{ icon.DesiredSize() };
const auto scaleX = fontWidth / size.Width;
const auto scaleY = fontHeight / size.Height;

Windows::UI::Xaml::Media::ScaleTransform transform{};
transform.ScaleX(transform.ScaleX() * scaleX);
transform.ScaleY(transform.ScaleY() * scaleY);
icon.RenderTransform(transform);

// now hide the icon
icon.Opacity(0);
};
scaleIconMarker(SelectionStartIcon());
scaleIconMarker(SelectionEndIcon());

// Don't try to inspect the core here. The Core is raising this while
// it's holding its write lock. If the handlers calls back to some
// method on the TermControl on the same thread, and that _method_ calls
Expand Down
3 changes: 3 additions & 0 deletions src/cascadia/TerminalControl/TermControl.h
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,7 @@ namespace winrt::Microsoft::Terminal::Control::implementation
void _FontInfoHandler(const IInspectable& sender, const FontInfoEventArgs& eventArgs);

winrt::fire_and_forget _hoveredHyperlinkChanged(IInspectable sender, IInspectable args);
winrt::fire_and_forget _updateSelectionMarkers(IInspectable sender, Control::UpdateSelectionMarkersEventArgs args);

void _coreFontSizeChanged(const int fontWidth,
const int fontHeight,
Expand All @@ -267,6 +268,8 @@ namespace winrt::Microsoft::Terminal::Control::implementation
void _coreReceivedOutput(const IInspectable& sender, const IInspectable& args);
void _coreRaisedNotice(const IInspectable& s, const Control::NoticeEventArgs& args);
void _coreWarningBell(const IInspectable& sender, const IInspectable& args);

til::point _toPosInDips(const til::point terminalCellPos);
};
}

Expand Down
17 changes: 17 additions & 0 deletions src/cascadia/TerminalControl/TermControl.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,23 @@
</ToolTipService.ToolTip>
</Border>
</Canvas>

<Canvas x:Name="SelectionCanvas"
Visibility="Visible">
<!-- LOAD BEARING Use Opacity instead of Visibility for these two FontIcons.
Visibility::Collapsed prevents us from aquiring the desired size of the icons,
resulting in an inability to scale them upon a FontSize change event -->
<FontIcon x:Name="SelectionStartIcon"
FontFamily="Segoe MDL2 Assets"
Glyph="&#xE893;"
Opacity="0">
</FontIcon>
<FontIcon x:Name="SelectionEndIcon"
FontFamily="Segoe MDL2 Assets"
Glyph="&#xE892;"
Opacity="0">
</FontIcon>
</Canvas>
</SwapChainPanel>

<!--
Expand Down
3 changes: 3 additions & 0 deletions src/cascadia/TerminalCore/Terminal.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,9 @@ class Microsoft::Terminal::Core::Terminal final :
void SetSelectionEnd(const COORD position, std::optional<winrt::Microsoft::Terminal::Core::SelectionExpansion> newExpansionMode = std::nullopt);
void SetBlockSelection(const bool isEnabled) noexcept;
void UpdateSelection(winrt::Microsoft::Terminal::Core::SelectionDirection direction, winrt::Microsoft::Terminal::Core::SelectionExpansion mode);
bool MovingStart() const noexcept;
til::point SelectionStartForRendering() const;
til::point SelectionEndForRendering() const;

const TextBuffer::TextAndColor RetrieveSelectedTextFromBuffer(bool trimTrailingWhitespace);
#pragma endregion
Expand Down
18 changes: 18 additions & 0 deletions src/cascadia/TerminalCore/TerminalSelection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,24 @@ const COORD Terminal::GetSelectionEnd() const noexcept
return _selection->end;
}

til::point Terminal::SelectionStartForRendering() const
{
auto pos{ _selection->start };
const auto bufferSize{ _buffer->GetSize() };
bufferSize.DecrementInBounds(pos);
pos.Y = std::clamp<short>(base::ClampSub(pos.Y, _VisibleStartIndex()), bufferSize.Top(), bufferSize.BottomInclusive());
return pos;
}

til::point Terminal::SelectionEndForRendering() const
{
auto pos{ _selection->end };
const auto bufferSize{ _buffer->GetSize() };
bufferSize.IncrementInBounds(pos);
pos.Y = std::clamp<short>(base::ClampSub(pos.Y, _VisibleStartIndex()), bufferSize.Top(), bufferSize.BottomInclusive());
return pos;
}

// Method Description:
// - Checks if selection is active
// Return Value:
Expand Down

1 comment on commit 2c52439

@github-actions
Copy link

@github-actions github-actions bot commented on 2c52439 Aug 3, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@check-spelling-bot Report

Unrecognized words, please review:

  • aquiring
Previously acknowledged words that are now absent SPACEBAR Unregister
To accept these unrecognized words as correct (and remove the previously acknowledged and now absent words), run the following commands

... in a clone of the [email protected]:microsoft/terminal.git repository
on the dev/cazamor/ks/copy-mode branch:

update_files() {
perl -e '
my @expect_files=qw('".github/actions/spelling/expect/alphabet.txt
.github/actions/spelling/expect/expect.txt
.github/actions/spelling/expect/web.txt"');
@ARGV=@expect_files;
my @stale=qw('"$patch_remove"');
my $re=join "|", @stale;
my $suffix=".".time();
my $previous="";
sub maybe_unlink { unlink($_[0]) if $_[0]; }
while (<>) {
if ($ARGV ne $old_argv) { maybe_unlink($previous); $previous="$ARGV$suffix"; rename($ARGV, $previous); open(ARGV_OUT, ">$ARGV"); select(ARGV_OUT); $old_argv = $ARGV; }
next if /^(?:$re)(?:(?:\r|\n)*$| .*)/; print;
}; maybe_unlink($previous);'
perl -e '
my $new_expect_file=".github/actions/spelling/expect/2c5243990d6f62a36ab167e4534720bba18b9588.txt";
use File::Path qw(make_path);
use File::Basename qw(dirname);
make_path (dirname($new_expect_file));
open FILE, q{<}, $new_expect_file; chomp(my @words = <FILE>); close FILE;
my @add=qw('"$patch_add"');
my %items; @items{@words} = @words x (1); @items{@add} = @add x (1);
@words = sort {lc($a)."-".$a cmp lc($b)."-".$b} keys %items;
open FILE, q{>}, $new_expect_file; for my $word (@words) { print FILE "$word\n" if $word =~ /\w/; };
close FILE;
system("git", "add", $new_expect_file);
'
}

comment_json=$(mktemp)
curl -L -s -S \
  --header "Content-Type: application/json" \
  "https://api.github.com/repos/microsoft/terminal/comments/54378586" > "$comment_json"
comment_body=$(mktemp)
jq -r .body < "$comment_json" > $comment_body
rm $comment_json

patch_remove=$(perl -ne 'next unless s{^</summary>(.*)</details>$}{$1}; print' < "$comment_body")
  

patch_add=$(perl -e '$/=undef;
$_=<>;
s{<details>.*}{}s;
s{^#.*}{};
s{\n##.*}{};
s{(?:^|\n)\s*\*}{}g;
s{\s+}{ }g;
print' < "$comment_body")
  
update_files
rm $comment_body
git add -u
✏️ Contributor please read this

By default the command suggestion will generate a file named based on your commit. That's generally ok as long as you add the file to your commit. Someone can reorganize it later.

⚠️ The command is written for posix shells. You can copy the contents of each perl command excluding the outer ' marks and dropping any '"/"' quotation mark pairs into a file and then run perl file.pl from the root of the repository to run the code. Alternatively, you can manually insert the items...

If the listed items are:

  • ... misspelled, then please correct them instead of using the command.
  • ... names, please add them to .github/actions/spelling/allow/names.txt.
  • ... APIs, you can add them to a file in .github/actions/spelling/allow/.
  • ... just things you're using, please add them to an appropriate file in .github/actions/spelling/expect/.
  • ... tokens you only need in one place and shouldn't generally be used, you can add an item in an appropriate file in .github/actions/spelling/patterns/.

See the README.md in each directory for more information.

🔬 You can test your commits without appending to a PR by creating a new branch with that extra change and pushing it to your fork. The check-spelling action will run in response to your push -- it doesn't require an open pull request. By using such a branch, you can limit the number of typos your peers see you make. 😉

🗜️ If you see a bunch of garbage

If it relates to a ...

well-formed pattern

See if there's a pattern that would match it.

If not, try writing one and adding it to a patterns/{file}.txt.

Patterns are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your lines.

Note that patterns can't match multiline strings.

binary-ish string

Please add a file path to the excludes.txt file instead of just accepting the garbage.

File paths are Perl 5 Regular Expressions - you can test yours before committing to verify it will match your files.

^ refers to the file's path from the root of the repository, so ^README\.md$ would exclude README.md (on whichever branch you're using).

Please sign in to comment.