Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to save input action from command line #16513

Merged
merged 21 commits into from
Jul 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
83e3b8c
Add ability to save input action from command line
e82eric Jan 1, 2024
dd46338
Added command line options for Save Input
e82eric Jan 1, 2024
8bec5ec
Handle key chord parse failure
e82eric Jan 2, 2024
eec4f6b
Saved Input: Use TextBlocks instead of TextBoxes for toast, exclude
e82eric Jan 10, 2024
e54b4a4
Clean up of Save Action ActionArgs
e82eric Jan 20, 2024
03f57ac
Merge branch 'main' into save_input_action
zadjii-msft Mar 18, 2024
e0b0477
format
zadjii-msft Mar 19, 2024
0ad6296
Fix for keychord not being saved
e82eric Mar 21, 2024
d4eaec3
Update so that save input toasts do not show display params for values
e82eric Mar 21, 2024
50baa7b
Update save input subcommand to x-save
e82eric Mar 21, 2024
addf247
Merge remote-tracking branch 'origin/main' into save_input_action
e82eric May 28, 2024
49a74c8
Move save input behind velocity
e82eric May 29, 2024
cf56a9a
cherry-pick into save-input PR (mostly stashing so I make sure I don'…
zadjii-msft May 28, 2024
3f15d6e
Fix for save input toast text boxes not hiding when blank
e82eric May 29, 2024
2bf8391
Updates for SaveTask for PR feedback
e82eric Jun 4, 2024
f5ceac9
Updated save task and save action to save snippet
e82eric Jun 4, 2024
d6873c1
Add validation to avoid saving snippet without a command line
e82eric Jun 4, 2024
cd13fc3
Merge remote-tracking branch 'origin/main' into save_snippet
e82eric Jun 11, 2024
8377749
Address PR feedback
e82eric Jul 1, 2024
452bfce
Merge remote-tracking branch 'origin/main' into save_snippet
e82eric Jul 1, 2024
6c79af0
format
zadjii-msft Jul 2, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 107 additions & 0 deletions src/cascadia/TerminalApp/AppActionHandlers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1264,6 +1264,113 @@ namespace winrt::TerminalApp::implementation
}
}

void TerminalPage::_HandleSaveSnippet(const IInspectable& /*sender*/,
const ActionEventArgs& args)
{
if constexpr (!Feature_SaveSnippet::IsEnabled())
{
return;
}

if (args)
{
if (const auto& realArgs = args.ActionArgs().try_as<SaveSnippetArgs>())
{
auto commandLine = realArgs.Commandline();
if (commandLine.empty())
{
if (const auto termControl{ _GetActiveControl() })
{
if (termControl.HasSelection())
{
const auto selections{ termControl.SelectedText(true) };
const auto selection = std::accumulate(selections.begin(), selections.end(), std::wstring());
commandLine = selection;
}
}
}

if (commandLine.empty())
{
ActionSaveFailed(L"CommandLine is Required");
return;
}

try
{
KeyChord keyChord = nullptr;
if (!realArgs.KeyChord().empty())
{
keyChord = KeyChordSerialization::FromString(winrt::to_hstring(realArgs.KeyChord()));
}
_settings.GlobalSettings().ActionMap().AddSendInputAction(realArgs.Name(), commandLine, keyChord);
_settings.WriteSettingsToDisk();
ActionSaved(commandLine, realArgs.Name(), realArgs.KeyChord());
}
catch (const winrt::hresult_error& ex)
{
auto code = ex.code();
auto message = ex.message();
ActionSaveFailed(message);
args.Handled(true);
return;
}

args.Handled(true);
}
}
}

void TerminalPage::ActionSaved(winrt::hstring input, winrt::hstring name, winrt::hstring keyChord)
{
// If we haven't ever loaded the TeachingTip, then do so now and
// create the toast for it.
if (_actionSavedToast == nullptr)
{
if (auto tip{ FindName(L"ActionSavedToast").try_as<MUX::Controls::TeachingTip>() })
{
_actionSavedToast = std::make_shared<Toast>(tip);
// Make sure to use the weak ref when setting up this
// callback.
tip.Closed({ get_weak(), &TerminalPage::_FocusActiveControl });
}
}
_UpdateTeachingTipTheme(ActionSavedToast().try_as<winrt::Windows::UI::Xaml::FrameworkElement>());

SavedActionName(name);
SavedActionKeyChord(keyChord);
SavedActionCommandLine(input);

if (_actionSavedToast != nullptr)
{
_actionSavedToast->Open();
}
}

void TerminalPage::ActionSaveFailed(winrt::hstring message)
{
// If we haven't ever loaded the TeachingTip, then do so now and
// create the toast for it.
if (_actionSaveFailedToast == nullptr)
{
if (auto tip{ FindName(L"ActionSaveFailedToast").try_as<MUX::Controls::TeachingTip>() })
{
_actionSaveFailedToast = std::make_shared<Toast>(tip);
// Make sure to use the weak ref when setting up this
// callback.
tip.Closed({ get_weak(), &TerminalPage::_FocusActiveControl });
}
}
_UpdateTeachingTipTheme(ActionSaveFailedToast().try_as<winrt::Windows::UI::Xaml::FrameworkElement>());

ActionSaveFailedMessage().Text(message);

if (_actionSaveFailedToast != nullptr)
{
_actionSaveFailedToast->Open();
}
}

void TerminalPage::_HandleSelectCommand(const IInspectable& /*sender*/,
const ActionEventArgs& args)
{
Expand Down
70 changes: 69 additions & 1 deletion src/cascadia/TerminalApp/AppCommandlineArgs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,7 @@ void AppCommandlineArgs::_buildParser()
_buildMovePaneParser();
_buildSwapPaneParser();
_buildFocusPaneParser();
_buildSaveSnippetParser();
}

// Method Description:
Expand Down Expand Up @@ -537,6 +538,72 @@ void AppCommandlineArgs::_buildFocusPaneParser()
setupSubcommand(_focusPaneShort);
}

void AppCommandlineArgs::_buildSaveSnippetParser()
{
_saveCommand = _app.add_subcommand("x-save-snippet", RS_A(L"SaveSnippetDesc"));

auto setupSubcommand = [this](auto* subcommand) {
subcommand->add_option("--name,-n", _saveInputName, RS_A(L"SaveSnippetArgDesc"));
subcommand->add_option("--keychord,-k", _keyChordOption, RS_A(L"KeyChordArgDesc"));
subcommand->add_option("command,", _commandline, RS_A(L"CmdCommandArgDesc"));
subcommand->positionals_at_end(true);

// When ParseCommand is called, if this subcommand was provided, this
// callback function will be triggered on the same thread. We can be sure
// that `this` will still be safe - this function just lets us know this
// command was parsed.
subcommand->callback([&, this]() {
// Build the action from the values we've parsed on the commandline.
ActionAndArgs saveSnippet{};
saveSnippet.Action(ShortcutAction::SaveSnippet);
// First, parse out the commandline in the same way that
// _getNewTerminalArgs does it
SaveSnippetArgs args{};

if (!_commandline.empty())
{
std::ostringstream cmdlineBuffer;

for (const auto& arg : _commandline)
{
if (cmdlineBuffer.tellp() != 0)
{
// If there's already something in here, prepend a space
cmdlineBuffer << ' ';
}

if (arg.find(" ") != std::string::npos)
{
cmdlineBuffer << '"' << arg << '"';
}
else
{
cmdlineBuffer << arg;
}
}

args.Commandline(winrt::to_hstring(cmdlineBuffer.str()));
}

if (!_keyChordOption.empty())
{
args.KeyChord(winrt::to_hstring(_keyChordOption));
}

if (!_saveInputName.empty())
{
winrt::hstring hString = winrt::to_hstring(_saveInputName);
args.Name(hString);
}

saveSnippet.Args(args);
_startupActions.push_back(saveSnippet);
});
};

setupSubcommand(_saveCommand);
}

// Method Description:
// - Add the `NewTerminalArgs` parameters to the given subcommand. This enables
// that subcommand to support all the properties in a NewTerminalArgs.
Expand Down Expand Up @@ -710,7 +777,8 @@ bool AppCommandlineArgs::_noCommandsProvided()
*_focusPaneCommand ||
*_focusPaneShort ||
*_newPaneShort.subcommand ||
*_newPaneCommand.subcommand);
*_newPaneCommand.subcommand ||
*_saveCommand);
}

// Method Description:
Expand Down
4 changes: 4 additions & 0 deletions src/cascadia/TerminalApp/AppCommandlineArgs.h
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ class TerminalApp::AppCommandlineArgs final
CLI::App* _swapPaneCommand;
CLI::App* _focusPaneCommand;
CLI::App* _focusPaneShort;
CLI::App* _saveCommand;

// Are you adding a new sub-command? Make sure to update _noCommandsProvided!

Expand Down Expand Up @@ -123,6 +124,8 @@ class TerminalApp::AppCommandlineArgs final
bool _focusPrevTab{ false };

int _focusPaneTarget{ -1 };
std::string _saveInputName;
std::string _keyChordOption;
// Are you adding more args here? Make sure to reset them in _resetStateToDefault

const Commandline* _currentCommandline{ nullptr };
Expand All @@ -141,6 +144,7 @@ class TerminalApp::AppCommandlineArgs final
winrt::Microsoft::Terminal::Settings::Model::NewTerminalArgs _getNewTerminalArgs(NewTerminalSubcommand& subcommand);
void _addNewTerminalArgs(NewTerminalSubcommand& subcommand);
void _buildParser();
void _buildSaveSnippetParser();
void _buildNewTabParser();
void _buildSplitPaneParser();
void _buildFocusTabParser();
Expand Down
15 changes: 15 additions & 0 deletions src/cascadia/TerminalApp/Resources/en-US/Resources.resw
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,15 @@
<data name="CmdCommandArgDesc" xml:space="preserve">
<value>An optional command, with arguments, to be spawned in the new tab or pane</value>
</data>
<data name="SaveSnippetDesc" xml:space="preserve">
<value>Save command line as input action</value>
</data>
<data name="SaveSnippetArgDesc" xml:space="preserve">
<value>An optional argument</value>
</data>
<data name="KeyChordArgDesc" xml:space="preserve">
<value>An optional argument</value>
</data>
<data name="CmdFocusTabDesc" xml:space="preserve">
<value>Move focus to another tab</value>
</data>
Expand Down Expand Up @@ -898,4 +907,10 @@
<data name="RestartConnectionToolTip" xml:space="preserve">
<value>Restart the active pane connection</value>
</data>
<data name="ActionSavedToast.Title" xml:space="preserve">
<value>Action saved</value>
</data>
<data name="ActionSaveFailedToast.Title" xml:space="preserve">
<value>Action save failed</value>
</data>
</root>
8 changes: 4 additions & 4 deletions src/cascadia/TerminalApp/TerminalAppLib.vcxproj
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,9 @@
</ItemGroup>
<!-- ========================= Misc Files ======================== -->
<ItemGroup>
<PRIResource Include="Resources\en-US\Resources.resw" />
<PRIResource Include="Resources\en-US\Resources.resw">
<SubType>Designer</SubType>
</PRIResource>
<PRIResource Include="Resources\en-US\ContextMenu.resw" />
<OCResourceDirectory Include="Resources" />
</ItemGroup>
Expand Down Expand Up @@ -466,10 +468,8 @@
</ItemDefinitionGroup>
<!-- ========================= Globals ======================== -->
<Import Project="$(OpenConsoleDir)src\cppwinrt.build.post.props" />

<!-- This -must- go after cppwinrt.build.post.props because that includes many VS-provided props including appcontainer.common.props, which stomps on what cppwinrt.targets did. -->
<Import Project="$(OpenConsoleDir)src\common.nugetversions.targets" />

<!--
By default, the PRI file will contain resource paths beginning with the
project name. Since we enabled XBF embedding, this *also* includes App.xbf.
Expand All @@ -490,4 +490,4 @@
</ItemGroup>
</Target>
<Import Project="$(SolutionDir)build\rules\CollectWildcardResources.targets" />
</Project>
</Project>
8 changes: 8 additions & 0 deletions src/cascadia/TerminalApp/TerminalPage.h
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,8 @@ namespace winrt::TerminalApp::implementation
winrt::hstring KeyboardServiceDisabledText();

winrt::fire_and_forget IdentifyWindow();
void ActionSaved(winrt::hstring input, winrt::hstring name, winrt::hstring keyChord);
void ActionSaveFailed(winrt::hstring message);
winrt::fire_and_forget RenameFailed();
winrt::fire_and_forget ShowTerminalWorkingDirectory();

Expand Down Expand Up @@ -199,6 +201,10 @@ namespace winrt::TerminalApp::implementation
WINRT_OBSERVABLE_PROPERTY(winrt::Windows::UI::Xaml::Media::Brush, TitlebarBrush, PropertyChanged.raise, nullptr);
WINRT_OBSERVABLE_PROPERTY(winrt::Windows::UI::Xaml::Media::Brush, FrameBrush, PropertyChanged.raise, nullptr);

WINRT_OBSERVABLE_PROPERTY(winrt::hstring, SavedActionName, PropertyChanged.raise, L"");
WINRT_OBSERVABLE_PROPERTY(winrt::hstring, SavedActionKeyChord, PropertyChanged.raise, L"");
WINRT_OBSERVABLE_PROPERTY(winrt::hstring, SavedActionCommandLine, PropertyChanged.raise, L"");

private:
friend struct TerminalPageT<TerminalPage>; // for Xaml to bind events
std::optional<HWND> _hostingHwnd;
Expand Down Expand Up @@ -258,6 +264,8 @@ namespace winrt::TerminalApp::implementation
bool _isEmbeddingInboundListener{ false };

std::shared_ptr<Toast> _windowIdToast{ nullptr };
std::shared_ptr<Toast> _actionSavedToast{ nullptr };
std::shared_ptr<Toast> _actionSaveFailedToast{ nullptr };
std::shared_ptr<Toast> _windowRenameFailedToast{ nullptr };
std::shared_ptr<Toast> _windowCwdToast{ nullptr };

Expand Down
4 changes: 4 additions & 0 deletions src/cascadia/TerminalApp/TerminalPage.idl
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ namespace TerminalApp
void IdentifyWindow();
void RenameFailed();

String SavedActionName { get; };
String SavedActionKeyChord { get; };
String SavedActionCommandLine { get; };

// We cannot use the default XAML APIs because we want to make sure
// that there's only one application-global dialog visible at a time,
// and because of GH#5224.
Expand Down
39 changes: 39 additions & 0 deletions src/cascadia/TerminalApp/TerminalPage.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:TerminalApp"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:mtu="using:Microsoft.Terminal.UI"
xmlns:mux="using:Microsoft.UI.Xaml.Controls"
Background="Transparent"
mc:Ignorable="d">
Expand Down Expand Up @@ -204,5 +205,43 @@
Title="{x:Bind WindowProperties.VirtualWorkingDirectory, Mode=OneWay}"
x:Load="False"
IsLightDismissEnabled="True" />

<mux:TeachingTip x:Name="ActionSavedToast"
x:Uid="ActionSavedToast"
Title="Action Saved"
HorizontalAlignment="Stretch"
x:Load="False"
IsLightDismissEnabled="True">
<mux:TeachingTip.Content>
<StackPanel HorizontalAlignment="Stretch"
Orientation="Vertical">
<TextBlock x:Name="ActionSavedNameText"
Visibility="{x:Bind mtu:Converters.StringNotEmptyToVisibility(SavedActionName), Mode=OneWay}">
<Run Text="Name: " />
Copy link
Member

Choose a reason for hiding this comment

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

📝: I think I'm fine with these not being localized, since they're literal params to the action args, and we've got precedent for that in the cmdpal already

<Run Text="{x:Bind SavedActionName, Mode=OneWay}" />
</TextBlock>
<TextBlock x:Name="ActionSavedKeyChordText"
Visibility="{x:Bind mtu:Converters.StringNotEmptyToVisibility(SavedActionKeyChord), Mode=OneWay}">
<Run Text="Key Chord: " />
<Run Text="{x:Bind SavedActionKeyChord, Mode=OneWay}" />
</TextBlock>
<TextBlock x:Name="ActionSavedCommandLineText"
Visibility="{x:Bind mtu:Converters.StringNotEmptyToVisibility(SavedActionCommandLine), Mode=OneWay}">
<Run Text="Input: " />
<Run Text="{x:Bind SavedActionCommandLine, Mode=OneWay}" />
</TextBlock>
</StackPanel>
</mux:TeachingTip.Content>
</mux:TeachingTip>
<mux:TeachingTip x:Name="ActionSaveFailedToast"
x:Uid="ActionSaveFailedToast"
Title="Action Save Failed"
x:Load="False"
IsLightDismissEnabled="True">
<mux:TeachingTip.Content>
<TextBlock x:Name="ActionSaveFailedMessage"
Text="" />
</mux:TeachingTip.Content>
</mux:TeachingTip>
</Grid>
</Page>
2 changes: 2 additions & 0 deletions src/cascadia/TerminalSettingsModel/ActionAndArgs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ static constexpr std::string_view SwitchToTabKey{ "switchToTab" };
static constexpr std::string_view TabSearchKey{ "tabSearch" };
static constexpr std::string_view ToggleAlwaysOnTopKey{ "toggleAlwaysOnTop" };
static constexpr std::string_view ToggleCommandPaletteKey{ "commandPalette" };
static constexpr std::string_view SaveSnippetKey{ "experimental.saveSnippet" };
static constexpr std::string_view SuggestionsKey{ "showSuggestions" };
static constexpr std::string_view ToggleFocusModeKey{ "toggleFocusMode" };
static constexpr std::string_view SetFocusModeKey{ "setFocusMode" };
Expand Down Expand Up @@ -389,6 +390,7 @@ namespace winrt::Microsoft::Terminal::Settings::Model::implementation
{ ShortcutAction::TabSearch, RS_(L"TabSearchCommandKey") },
{ ShortcutAction::ToggleAlwaysOnTop, RS_(L"ToggleAlwaysOnTopCommandKey") },
{ ShortcutAction::ToggleCommandPalette, MustGenerate },
{ ShortcutAction::SaveSnippet, MustGenerate },
{ ShortcutAction::Suggestions, MustGenerate },
{ ShortcutAction::ToggleFocusMode, RS_(L"ToggleFocusModeCommandKey") },
{ ShortcutAction::SetFocusMode, MustGenerate },
Expand Down
Loading
Loading