Files
hrynco-kswitcher/src/files_command_completion.h
T

322 lines
16 KiB
C++

#pragma once
#include "platform.h"
#include "files_powershell.h"
#include "files_windows_command_catalog.h"
#include "../vendor/json.hpp"
#include <optional>
#include <vector>
namespace ks::files
{
class CommandCompletion
{
public:
using Json = nlohmann::json;
CommandCompletion() = default;
CommandCompletion(const CommandCompletion &) = delete;
CommandCompletion &operator=(const CommandCompletion &) = delete;
~CommandCompletion() { close(); }
bool request(const std::wstring &line, DWORD caret, const std::wstring &directory)
{
auto message=Json{{"line",utf8(line)},{"caret",caret},{"directory",utf8(directory)}}.dump(
-1,' ',true,Json::error_handler_t::replace)+"\n";
if(message.size()>32768 || (!process && !start())) return false;
if(!write(message))
{
close();
return false;
}
deadline=GetTickCount64()+5000;
return true;
}
// An empty optional means the request is still running.
std::optional<Json> poll()
{
DWORD available{},count{};
char chunk[8192];
if(!PeekNamedPipe(output,nullptr,0,nullptr,&available,nullptr) ||
GetTickCount64()>=deadline || pending.size()>1024*1024)
{
close();
return Json{};
}
if(available && ReadFile(output,chunk,std::min<DWORD>(available,sizeof(chunk)),&count,nullptr))
pending.append(chunk,count);
const auto end=pending.find('\n');
if(end==pending.npos) return {};
auto result=Json::parse(pending.begin(),pending.begin()+end,nullptr,false);
pending.erase(0,end+1);
return result;
}
private:
HANDLE process{},input{},output{},job{};
ULONGLONG deadline{};
std::string pending;
bool write(std::string_view message)
{
DWORD written{};
return WriteFile(input,message.data(),static_cast<DWORD>(message.size()),&written,nullptr) &&
written==message.size();
}
bool start()
{
SECURITY_ATTRIBUTES inheritable{sizeof(inheritable),nullptr,TRUE};
HANDLE childInput{},childOutput{};
std::string catalog;
for(const auto row:windowsCommandCatalog) catalog.append(row).push_back('\n');
const auto initial=Json{{"catalog",std::move(catalog)}}.dump()+"\n";
const auto inputCapacity=static_cast<DWORD>(initial.size()+32768);
const bool pipes=CreatePipe(&childInput,&input,&inheritable,inputCapacity) &&
CreatePipe(&output,&childOutput,&inheritable,65536) &&
SetHandleInformation(input,HANDLE_FLAG_INHERIT,0) &&
SetHandleInformation(output,HANDLE_FLAG_INHERIT,0);
const bool started=pipes && launch(childInput,childOutput) && write(initial);
if(childInput) CloseHandle(childInput);
if(childOutput) CloseHandle(childOutput);
if(!started) close();
return started;
}
bool launch(HANDLE childInput,HANDLE childOutput)
{
const auto shell=windowsPowerShell();
if(shell.empty()) return false;
// The request is data on stdin. PowerShell parses it for completion in this separate session.
wchar_t command[]=LR"PS(powershell.exe -NoLogo -NoProfile -NonInteractive -Command "
$ProgressPreference = 'SilentlyContinue';
[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);
function Get-CompletedArguments($command, $position, $includeCurrent) {
foreach ($element in ($command.CommandElements | Select-Object -Skip 1)) {
if ($element.Extent.EndOffset -gt $position -or
(!$includeCurrent -and $element.Extent.EndOffset -eq $position)) { break }
if ($element -is [System.Management.Automation.Language.StringConstantExpressionAst]) {
$element.Value;
} else { $element.Extent.Text }
}
}
function New-ArgumentCompletion([string]$value) {
$text = $value;
if ($value.StartsWith('@') -or $value -notmatch '^[\p{L}\p{M}\p{N}._/@:+,=\-]+$') {
$quote = [string][char]39;
$text = $quote + [System.Management.Automation.Language.CodeGeneration]::EscapeSingleQuotedStringContent($value) + $quote;
}
[System.Management.Automation.CompletionResult]::new($text, $value, 'ParameterValue', $value)
}
function Get-DhcpAdapterNames {
foreach ($adapter in [Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
if (!$adapter.Supports([Net.NetworkInformation.NetworkInterfaceComponent]::IPv4)) { continue }
try {
if ($adapter.GetIPProperties().GetIPv4Properties().IsDhcpEnabled) { $adapter.Name }
} catch {}
}
}
$initial = ConvertFrom-Json -InputObject ([Console]::ReadLine());
$windowsCommands = @{};
$windowsHelp = @{};
foreach ($row in ($initial.catalog -split '\r?\n')) {
if (!$row) { continue }
$name, $values, $article = $row.Split([char]9, 3);
$windowsCommands[$name] = if ($values) { $values.Split(' ') } else { @() };
if ($article) { $windowsHelp[$name] = $article }
}
$windowsRoots = @($windowsCommands.Keys | Where-Object { !($_.Contains(' ')) } | Sort-Object);
$windowsPrograms = @(foreach ($name in $windowsRoots) { $name; $name + '.exe'; $name + '.com' });
function Get-WindowsCommandContext($command, $position, $includeCurrent) {
if (!$command) { return }
$invoked = $command.GetCommandName();
if (!$invoked -or !$windowsCommands.ContainsKey([IO.Path]::GetFileNameWithoutExtension($invoked))) { return }
$resolved = Get-Command -Name ([WildcardPattern]::Escape($invoked)) -ErrorAction SilentlyContinue |
Select-Object -First 1;
if ($resolved -is [System.Management.Automation.AliasInfo]) { $resolved = $resolved.ResolvedCommand }
if ($resolved -isnot [System.Management.Automation.ApplicationInfo]) { return }
$name = [IO.Path]::GetFileNameWithoutExtension($resolved.Name);
$arguments = @(Get-CompletedArguments $command $position $includeCurrent);
$values = $null;
if ($name -eq 'cmd') {
for ($i = 0; $i -lt $arguments.Count; ++$i) {
if ($arguments[$i] -notin '/c', '/k') { continue }
if ($i + 1 -lt $arguments.Count) {
$name = [IO.Path]::GetFileNameWithoutExtension($arguments[$i + 1]);
$arguments = @($arguments | Select-Object -Skip ($i + 2));
} else { $values = $windowsRoots }
break
}
}
$root = $name;
$article = $windowsHelp[$name];
if (!$values) {
foreach ($argument in $arguments) {
$child = $name + ' ' + $argument;
if (!$windowsCommands.ContainsKey($child)) { break }
$name = $child;
if ($windowsHelp[$name]) { $article = $windowsHelp[$name] }
}
$values = $windowsCommands[$name];
}
@{ root = $root; values = $values; arguments = $arguments; article = $article }
}
Register-ArgumentCompleter -Native -CommandName $windowsPrograms -ScriptBlock {
param($word, $command, $position)
$context = Get-WindowsCommandContext $command $position $false;
if (!$context) { return }
if ($context.root -eq 'ipconfig' -and $context.arguments.Count -and
$context.arguments[0] -in '/renew','/release') {
$script:adapterArguments = $true;
if ($context.arguments.Count -ne 1) { return }
$prefix = ([string]$word).Trim([char[]]@([char]39, [char]34));
foreach ($adapterName in (Get-DhcpAdapterNames | Sort-Object -Unique)) {
if ($adapterName.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) {
New-ArgumentCompletion $adapterName
}
}
return
}
if ($word -eq '?') { $word = '/?' }
foreach ($value in $context.values) {
if ($value.StartsWith([string]$word, [StringComparison]::OrdinalIgnoreCase)) {
[System.Management.Automation.CompletionResult]::new($value)
}
}
};
Register-ArgumentCompleter -Native -CommandName dotnet,dotnet.exe -ScriptBlock {
param($word, $command, $position)
$offset = $position - $command.Extent.StartOffset;
dotnet.exe complete --position $offset $command.ToString() 2>$null | ForEach-Object {
[System.Management.Automation.CompletionResult]::new($_)
}
};
function Find-GitCompletionTools {
$git = Get-Command git.exe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1;
if (!$git) { return }
$location = [IO.DirectoryInfo]::new([IO.Path]::GetDirectoryName($git.Source));
for ($level = 0; $location -and $level -lt 3; ++$level) {
$root = $location.FullName;
$location = $location.Parent;
$bash = Join-Path $root 'usr/bin/bash.exe';
if (![IO.File]::Exists($bash)) { continue }
foreach ($architecture in 'mingw64', 'mingw32', 'clangarm64') {
$script = Join-Path $root ($architecture + '/share/git/completion/git-completion.bash');
if ([IO.File]::Exists($script)) { return @{ bash = $bash; script = $script } }
}
}
}
# Send words as data to Git for Windows. Backslash-quote escapes are for Windows PowerShell's native argv.
$gitCompletionRunner = @'
export GIT_ALLOW_PROTOCOL= GIT_TERMINAL_PROMPT=0
mapfile -t input
for i in ~${!input[@]}~; do input[i]=~${input[i]%$'\r'}~; done
source ~${input[0]}~ || exit
words=(~${input[@]:1}~)
cword=$(( ${#words[@]} - 1 ))
cur=${words[cword]}
prev=${words[cword-1]}
__git_main
if (( ${#COMPREPLY[@]} )); then printf '%s\n' ~${COMPREPLY[@]}~; fi
'@.Replace('~', ('\' + [char]34));
$OutputEncoding = [Console]::OutputEncoding;
Register-ArgumentCompleter -Native -CommandName git,git.exe -ScriptBlock {
param($word, $command, $position)
if (!$script:gitCompletionTools) { $script:gitCompletionTools = Find-GitCompletionTools }
if (!$script:gitCompletionTools) { return }
$arguments = @('git') + @(Get-CompletedArguments $command $position) + @([string]$word);
@($script:gitCompletionTools.script) + $arguments |
& $script:gitCompletionTools.bash --noprofile --norc -p -c $gitCompletionRunner 2>$null |
ForEach-Object {
$value = $_.TrimEnd();
if ($value) { New-ArgumentCompletion $value }
}
};
function Get-CompletionCommand($request) {
$prefix = $request.line.Substring(0, $request.caret).TrimEnd();
$ast = [System.Management.Automation.Language.Parser]::ParseInput($prefix, [ref]$null, [ref]$null);
$ast.FindAll({
param($node)
$node -is [System.Management.Automation.Language.CommandAst] -and
$node.Extent.EndOffset -eq $prefix.Length
}, $true) | Select-Object -Last 1;
}
function Test-NoCommandArguments($command) {
if (!$command) { return $false }
$name = $command.GetCommandName();
if (!$name) { return $false }
$info = Get-Command -Name ([WildcardPattern]::Escape($name)) -ErrorAction SilentlyContinue;
if ($info -is [System.Management.Automation.AliasInfo]) { $info = $info.ResolvedCommand }
return ($info -is [System.Management.Automation.FunctionInfo] -or
$info -is [System.Management.Automation.CmdletInfo]) -and $info.Parameters.Count -eq 0;
}
while ($null -ne ($line = [Console]::ReadLine())) {
try {
$request = ConvertFrom-Json -InputObject $line -ErrorAction Stop;
Set-Location -LiteralPath $request.directory -ErrorAction Stop;
$script:adapterArguments = $false;
$command = Get-CompletionCommand $request;
$context = Get-WindowsCommandContext $command $request.caret $true;
$result = TabExpansion2 -inputScript $request.line -cursorColumn $request.caret;
$candidates = $result.CompletionMatches;
if ($candidates.Count -and $candidates[0].ResultType -in 'ProviderItem','ProviderContainer' -and
($script:adapterArguments -or (Test-NoCommandArguments $command))) {
$candidates = $candidates | Where-Object { $_.ResultType -notin 'ProviderItem','ProviderContainer' };
}
$items = @($candidates | Select-Object -First 100 | ForEach-Object {
@{ label = $_.ListItemText; text = $_.CompletionText; directory = ($_.ResultType -eq 'ProviderContainer') }
});
$reply = @{ index = $result.ReplacementIndex; length = $result.ReplacementLength;
matches = $items; article = [string]$context.article };
[Console]::WriteLine((ConvertTo-Json -InputObject $reply -Compress -Depth 4));
} catch { [Console]::WriteLine('{}') }
}")PS";
job=CreateJobObjectW(nullptr,nullptr);
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits{};
limits.BasicLimitInformation.LimitFlags=JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if(!job || !SetInformationJobObject(job,JobObjectExtendedLimitInformation,&limits,sizeof(limits))) return false;
SIZE_T bytes{};
InitializeProcThreadAttributeList(nullptr,1,0,&bytes);
std::vector<unsigned char> storage(bytes);
auto attributes=reinterpret_cast<LPPROC_THREAD_ATTRIBUTE_LIST>(storage.data());
if(!InitializeProcThreadAttributeList(attributes,1,0,&bytes)) return false;
HANDLE inherited[]{childInput,childOutput};
STARTUPINFOEXW startup{};
startup.StartupInfo.cb=sizeof(startup);
startup.StartupInfo.dwFlags=STARTF_USESTDHANDLES;
startup.StartupInfo.hStdInput=childInput;
startup.StartupInfo.hStdOutput=startup.StartupInfo.hStdError=childOutput;
startup.lpAttributeList=attributes;
PROCESS_INFORMATION child{};
const bool started=UpdateProcThreadAttribute(attributes,0,PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
inherited,sizeof(inherited),nullptr,nullptr) &&
CreateProcessW(shell.c_str(),command,nullptr,nullptr,TRUE,
CREATE_SUSPENDED|CREATE_NO_WINDOW|EXTENDED_STARTUPINFO_PRESENT,
nullptr,nullptr,&startup.StartupInfo,&child);
DeleteProcThreadAttributeList(attributes);
if(!started) return false;
process=child.hProcess;
const bool running=AssignProcessToJobObject(job,process) && ResumeThread(child.hThread)!=DWORD(-1);
if(!running) TerminateProcess(process,1);
CloseHandle(child.hThread);
return running;
}
void close()
{
for(const auto handle:{job,input,output,process})
if(handle) CloseHandle(handle);
job=input=output=process=nullptr;
pending.clear();
}
};
}