Skip to content

Use public InternalHost from origin runspace #874

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

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
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
19 changes: 14 additions & 5 deletions src/PowerShellEditorServices.Host/EditorServicesHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
using System.Reflection;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Linq;

namespace Microsoft.PowerShell.EditorServices.Host
{
Expand Down Expand Up @@ -61,6 +64,7 @@ public class EditorServicesHost
{
#region Private Fields

private readonly PSHost internalHost;
private string[] additionalModules;
private string bundledModulesPath;
private DebugAdapter debugAdapter;
Expand Down Expand Up @@ -103,6 +107,11 @@ public EditorServicesHost(
{
Validate.IsNotNull(nameof(hostDetails), hostDetails);

using (var pwsh = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace))
{
this.internalHost = pwsh.AddScript("$Host").Invoke<PSHost>().First();
}

this.hostDetails = hostDetails;
this.enableConsoleRepl = enableConsoleRepl;
this.bundledModulesPath = bundledModulesPath;
Expand All @@ -113,13 +122,13 @@ public EditorServicesHost(
#if DEBUG
if (waitForDebugger)
{
if (Debugger.IsAttached)
if (System.Diagnostics.Debugger.IsAttached)
{
Debugger.Break();
System.Diagnostics.Debugger.Break();
}
else
{
Debugger.Launch();
System.Diagnostics.Debugger.Launch();
}
}
#endif
Expand Down Expand Up @@ -377,7 +386,7 @@ private EditorSession CreateSession(

EditorServicesPSHostUserInterface hostUserInterface =
enableConsoleRepl
? (EditorServicesPSHostUserInterface) new TerminalPSHostUserInterface(powerShellContext, this.logger)
? (EditorServicesPSHostUserInterface) new TerminalPSHostUserInterface(powerShellContext, this.logger, this.internalHost)
: new ProtocolPSHostUserInterface(powerShellContext, messageSender, this.logger);

EditorServicesPSHost psHost =
Expand Down Expand Up @@ -419,7 +428,7 @@ private EditorSession CreateDebugSession(

EditorServicesPSHostUserInterface hostUserInterface =
enableConsoleRepl
? (EditorServicesPSHostUserInterface) new TerminalPSHostUserInterface(powerShellContext, this.logger)
? (EditorServicesPSHostUserInterface) new TerminalPSHostUserInterface(powerShellContext, this.logger, this.internalHost)
: new ProtocolPSHostUserInterface(powerShellContext, messageSender, this.logger);

EditorServicesPSHost psHost =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<Description>Provides common PowerShell editor capabilities as a .NET library.</Description>
<TargetFrameworks>netstandard2.0</TargetFrameworks>
<AssemblyName>Microsoft.PowerShell.EditorServices</AssemblyName>
<LangVersion>Latest</LangVersion>
</PropertyGroup>
<!-- Fail the release build if there are missing public API documentation comments -->
<PropertyGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ public abstract class EditorServicesPSHostUserInterface :
{
#region Private Fields

private readonly HashSet<ProgressKey> currentProgressMessages = new HashSet<ProgressKey>();
Copy link
Member

Choose a reason for hiding this comment

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

thread safety pls 😄 ConcurrentBag

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Changed to using ConcurrentDictionary<,>, but haven't tested it yet so hold off on merge pls

private PromptHandler activePromptHandler;
private PSHostRawUserInterface rawUserInterface;
private CancellationTokenSource commandLoopCancellationToken;
Expand Down Expand Up @@ -83,6 +84,11 @@ public abstract class EditorServicesPSHostUserInterface :
/// </summary>
protected ILogger Logger { get; private set; }

/// <summary>
/// Gets a value indicating whether writing progress is supported.
/// </summary>
internal protected virtual bool SupportsWriteProgress => false;

#endregion

#region Constructors
Expand Down Expand Up @@ -582,17 +588,74 @@ public override void WriteErrorLine(string value)
}

/// <summary>
///
/// Invoked by <see cref="Cmdlet.WriteProgress(ProgressRecord)" /> to display a progress record.
/// </summary>
/// <param name="sourceId"></param>
/// <param name="record"></param>
public override void WriteProgress(
/// <param name="sourceId">
/// Unique identifier of the source of the record. An int64 is used because typically,
/// the 'this' pointer of the command from whence the record is originating is used, and
/// that may be from a remote Runspace on a 64-bit machine.
/// </param>
/// <param name="record">
/// The record being reported to the host.
/// </param>
public sealed override void WriteProgress(
long sourceId,
ProgressRecord record)
{
this.UpdateProgress(
sourceId,
ProgressDetails.Create(record));
// Maintain old behavior if this isn't overridden.
if (!this.SupportsWriteProgress)
{
this.UpdateProgress(sourceId, ProgressDetails.Create(record));
return;
}

// Keep a list of progress records we write so we can automatically
// clean them up after the pipeline ends.
if (record.RecordType == ProgressRecordType.Completed)
{
this.currentProgressMessages.Remove(new ProgressKey(sourceId, record));
}
else
{
this.currentProgressMessages.Add(new ProgressKey(sourceId, record));
}

this.WriteProgressImpl(sourceId, record);
}

/// <summary>
/// Invoked by <see cref="Cmdlet.WriteProgress(ProgressRecord)" /> to display a progress record.
/// </summary>
/// <param name="sourceId">
/// Unique identifier of the source of the record. An int64 is used because typically,
/// the 'this' pointer of the command from whence the record is originating is used, and
/// that may be from a remote Runspace on a 64-bit machine.
/// </param>
/// <param name="record">
/// The record being reported to the host.
/// </param>
protected virtual void WriteProgressImpl(long sourceId, ProgressRecord record)
{
}

internal void ClearProgress()
{
const string nonEmptyString = "noop";
if (!this.SupportsWriteProgress)
{
return;
}

foreach (ProgressKey key in this.currentProgressMessages)
{
// This constructor throws if the activity description is empty even
// with completed records.
var record = new ProgressRecord(key.ActivityId, nonEmptyString, nonEmptyString);
record.RecordType = ProgressRecordType.Completed;
this.WriteProgressImpl(key.SourceId, record);
}

this.currentProgressMessages.Clear();
}

#endregion
Expand Down Expand Up @@ -917,6 +980,8 @@ private void PowerShellContext_ExecutionStatusChanged(object sender, ExecutionSt
// The command loop should only be manipulated if it's already started
if (eventArgs.ExecutionStatus == ExecutionStatus.Aborted)
{
this.ClearProgress();

// When aborted, cancel any lingering prompts
if (this.activePromptHandler != null)
{
Expand All @@ -932,6 +997,8 @@ private void PowerShellContext_ExecutionStatusChanged(object sender, ExecutionSt
// the display of the prompt
if (eventArgs.ExecutionStatus != ExecutionStatus.Running)
{
this.ClearProgress();

// Execution has completed, start the input prompt
this.ShowCommandPrompt();
StartCommandLoop();
Expand All @@ -948,11 +1015,48 @@ private void PowerShellContext_ExecutionStatusChanged(object sender, ExecutionSt
(eventArgs.ExecutionStatus == ExecutionStatus.Failed ||
eventArgs.HadErrors))
{
this.ClearProgress();
this.WriteOutput(string.Empty, true);
var unusedTask = this.WritePromptStringToHostAsync(CancellationToken.None);
}
}

#endregion

private readonly struct ProgressKey : IEquatable<ProgressKey>
{
internal readonly long SourceId;

internal readonly int ActivityId;

internal readonly int ParentActivityId;

internal ProgressKey(long sourceId, ProgressRecord record)
{
SourceId = sourceId;
ActivityId = record.ActivityId;
ParentActivityId = record.ParentActivityId;
}

public bool Equals(ProgressKey other)
{
return SourceId == other.SourceId
&& ActivityId == other.ActivityId
&& ParentActivityId == other.ParentActivityId;
}

public override int GetHashCode()
{
// Algorithm from https://stackoverflow.com/questions/1646807/quick-and-simple-hash-code-combinations
unchecked
{
int hash = 17;
hash = hash * 31 + SourceId.GetHashCode();
hash = hash * 31 + ActivityId.GetHashCode();
hash = hash * 31 + ParentActivityId.GetHashCode();
return hash;
}
}
}
}
}
Loading