public DebugAdapter(ChannelBase serverChannel) : base(serverChannel)
 {
     this.editorSession = new EditorSession();
     this.editorSession.StartSession();
     this.editorSession.DebugService.DebuggerStopped += this.DebugService_DebuggerStopped;
     this.editorSession.PowerShellContext.OutputWritten += this.powerShellContext_OutputWritten;
 }
        public DebugAdapter(ChannelBase serverChannel) : base(serverChannel)
        {
            this.editorSession = new EditorSession();
            this.editorSession.StartSession();
            this.editorSession.DebugService.DebuggerStopped += this.DebugService_DebuggerStopped;
            this.editorSession.ConsoleService.OutputWritten += this.powerShellContext_OutputWritten;

            // Set up the output debouncer to throttle output event writes
            this.outputDebouncer = new OutputDebouncer(this);
        }
        protected override void Shutdown()
        {
            Logger.Write(LogLevel.Normal, "Debug adapter is shutting down...");

            if (this.editorSession != null)
            {
                this.editorSession.Dispose();
                this.editorSession = null;
            }
        }
        protected override void Shutdown()
        {
            Logger.Write(LogLevel.Normal, "Language service is shutting down...");

            if (this.editorSession != null)
            {
                this.editorSession.Dispose();
                this.editorSession = null;
            }
        }
Example #5
0
        public DebugAdapter(HostDetails hostDetails, ChannelBase serverChannel)
            : base(serverChannel)
        {
            this.editorSession = new EditorSession();
            this.editorSession.StartSession(hostDetails);
            this.editorSession.DebugService.DebuggerStopped += this.DebugService_DebuggerStopped;
            this.editorSession.ConsoleService.OutputWritten += this.powerShellContext_OutputWritten;

            // Set up the output debouncer to throttle output event writes
            this.outputDebouncer = new OutputDebouncer(this);
        }
Example #6
0
        private async void OnLanguageServiceClientConnectAsync(
            object sender,
            ChannelBase serverChannel)
        {
            MessageDispatcher messageDispatcher = new MessageDispatcher(this.logger);

            ProtocolEndpoint protocolEndpoint =
                new ProtocolEndpoint(
                    serverChannel,
                    messageDispatcher,
                    this.logger);

            protocolEndpoint.UnhandledException += ProtocolEndpoint_UnhandledException;

            this.editorSession =
                CreateSession(
                    this.hostDetails,
                    this.profilePaths,
                    protocolEndpoint,
                    messageDispatcher,
                    this.enableConsoleRepl);

            this.languageServer =
                new LanguageServer(
                    this.editorSession,
                    messageDispatcher,
                    protocolEndpoint,
                    this.serverCompletedTask,
                    this.logger);

            await this.editorSession.PowerShellContext.ImportCommandsModuleAsync(
                Path.Combine(
                    Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location),
                    @"..\Commands"));

            this.languageServer.Start();

            // TODO: This can be moved to the point after the $psEditor object
            // gets initialized when that is done earlier than LanguageServer.Initialize
            foreach (string module in this.additionalModules)
            {
                var command =
                    new System.Management.Automation.PSCommand()
                    .AddCommand("Microsoft.PowerShell.Core\\Import-Module")
                    .AddParameter("Name", module);

                await this.editorSession.PowerShellContext.ExecuteCommandAsync <System.Management.Automation.PSObject>(
                    command,
                    sendOutputToHost : false,
                    sendErrorToHost : true);
            }

            protocolEndpoint.Start();
        }
        public LanguageServer(ChannelBase serverChannel) : base(serverChannel)
        {
            this.editorSession = new EditorSession();
            this.editorSession.StartSession();
            this.editorSession.ConsoleService.OutputWritten += this.powerShellContext_OutputWritten;

            // Always send console prompts through the UI in the language service
            // TODO: This will change later once we have a general REPL available
            // in VS Code.
            this.editorSession.ConsoleService.PushPromptHandlerContext(
                new ProtocolPromptHandlerContext(this));
        }
        public DocumentSymbolFeature(
            EditorSession editorSession,
            IMessageHandlers messageHandlers,
            ILogger logger)
            : base(logger)
        {
            this.editorSession = editorSession;

            messageHandlers.SetRequestHandler(
                DocumentSymbolRequest.Type,
                this.HandleDocumentSymbolRequest);
        }
Example #9
0
        private void OnDebugServiceClientConnect(object sender, TcpSocketServerChannel serverChannel)
        {
            MessageDispatcher messageDispatcher = new MessageDispatcher(this.logger);

            ProtocolEndpoint protocolEndpoint =
                new ProtocolEndpoint(
                    serverChannel,
                    messageDispatcher,
                    this.logger);

            if (this.enableConsoleRepl)
            {
                this.debugAdapter =
                    new DebugAdapter(
                        this.editorSession,
                        false,
                        messageDispatcher,
                        protocolEndpoint,
                        this.logger);
            }
            else
            {
                EditorSession debugSession =
                    this.CreateDebugSession(
                        this.hostDetails,
                        profilePaths,
                        protocolEndpoint,
                        messageDispatcher,
                        this.languageServer?.EditorOperations,
                        false);

                this.debugAdapter =
                    new DebugAdapter(
                        debugSession,
                        true,
                        messageDispatcher,
                        protocolEndpoint,
                        this.logger);
            }

            this.debugAdapter.SessionEnded +=
                (obj, args) =>
            {
                this.logger.Write(
                    LogLevel.Normal,
                    "Previous debug session ended, restarting debug service listener...");

                this.debugServiceListener.Start();
            };

            this.debugAdapter.Start();
            protocolEndpoint.Start();
        }
Example #10
0
        public void Work()
        {
            var types = TypeManifest.Construct(
                new Type[]
            {
                typeof(int),
                typeof(bool),
                typeof(string),
            },
                new Type[]
            {
                typeof(RootModel),
                typeof(ChildModel)
            }
                );

            var manifest = new BehaviourManifest()
            {
                Nodes = null,
                Types = types
            };

            var sourceObject = new RootModel()
            {
                FirstValue = "Lol",
                AChild     = new ChildModel()
                {
                },
                BChild   = null,
                Children = new ChildModel[]
                {
                    new ChildModel(),
                    null
                },
                MoreChildren = new Dictionary <string, ChildModel>()
                {
                    ["alpha"] = new ChildModel()
                    {
                    },
                    ["beta"] = null
                }
            };

            var editorSession = new EditorSession(manifest, sourceObject, new JsonSerializer());

            DrawTree(editorSession.Root);

            editorSession.Root["BChild"].SetValue(new ChildModel());
            editorSession.Root["BChild"].ApplyModifiedProperties();

            DrawTree(editorSession.Root);
        }
        protected async Task HandleInitializeRequest(
            InitializeRequestArguments initializeParams,
            EditorSession editorSession,
            RequestContext <object, object> requestContext)
        {
            // Send the Initialized event first so that we get breakpoints
            await requestContext.SendEvent(
                InitializedEvent.Type,
                null);

            // Now send the Initialize response to continue setup
            await requestContext.SendResult(new object());
        }
Example #12
0
        protected override void Shutdown()
        {
            // Make sure remaining output is flushed before exiting
            this.outputDebouncer.Flush().Wait();

            Logger.Write(LogLevel.Normal, "Debug adapter is shutting down...");

            if (this.editorSession != null)
            {
                this.editorSession.Dispose();
                this.editorSession = null;
            }
        }
Example #13
0
        protected override async Task Shutdown()
        {
            // Make sure remaining output is flushed before exiting
            await this.outputDebouncer.Flush();

            Logger.Write(LogLevel.Normal, "Language service is shutting down...");

            if (this.editorSession != null)
            {
                this.editorSession.Dispose();
                this.editorSession = null;
            }
        }
 public DebugAdapter(
     EditorSession editorSession,
     bool ownsEditorSession,
     IMessageHandlers messageHandlers,
     IMessageSender messageSender,
     ILogger logger)
 {
     this.Logger            = logger;
     this.editorSession     = editorSession;
     this.messageSender     = messageSender;
     this.messageHandlers   = messageHandlers;
     this.ownsEditorSession = ownsEditorSession;
 }
 public DebugAdapter(
     EditorSession editorSession,
     bool ownsEditorSession,
     IMessageHandlers messageHandlers,
     IMessageSender messageSender,
     ILogger logger)
 {
     Logger             = logger;
     _editorSession     = editorSession;
     _messageSender     = messageSender;
     _messageHandlers   = messageHandlers;
     _ownsEditorSession = ownsEditorSession;
 }
Example #16
0
        public static void Open(EditorSession session, EditorField graphField)
        {
            var window = GetWindow <BehaviourEditor>();

            window.Show();

            window.GraphFrame      = new BehaviourGraphFrame();
            window.GraphFrame.View = new BehaviourEditorView();
            window.GraphFrame.View.BeginSession(session, graphField);

            window.GraphFrame.Window = window;
            window.GraphFrame.OnEnable();
        }
Example #17
0
        public EditorSessionFrame(EditorSession editorSession)
        {
            EditorSession = editorSession;

            EditorSession.OnChanged += () =>
            {
                HasUnsavedChanges = true;
            };

            var feature = EditorSession.GetOrCreateFeature <FramedEditorSessionFeature>();

            feature.Frame = this;
        }
        protected override void Shutdown()
        {
            // Make sure remaining output is flushed before exiting
            this.outputDebouncer.Flush().Wait();

            Logger.Write(LogLevel.Normal, "Debug adapter is shutting down...");

            if (this.editorSession != null)
            {
                this.editorSession.Dispose();
                this.editorSession = null;
            }
        }
Example #19
0
 public static void DrawEditor(EditorSession editor)
 {
     if (editor == null)
     {
         return;
     }
     EditorGUI.indentLevel++;
     foreach (var field in editor.Root)
     {
         DrawField(field);
     }
     EditorGUI.indentLevel--;
 }
Example #20
0
        protected async Task HandleSignatureHelpRequest(
            TextDocumentPosition textDocumentPosition,
            EditorSession editorSession,
            RequestContext <SignatureHelp, object> requestContext)
        {
            ScriptFile scriptFile =
                editorSession.Workspace.GetFile(
                    textDocumentPosition.Uri);

            ParameterSetSignatures parameterSets =
                await editorSession.LanguageService.FindParameterSetsInFile(
                    scriptFile,
                    textDocumentPosition.Position.Line + 1,
                    textDocumentPosition.Position.Character + 1);

            SignatureInformation[] signatures = null;
            int?activeParameter = null;
            int?activeSignature = 0;

            if (parameterSets != null)
            {
                signatures =
                    parameterSets
                    .Signatures
                    .Select(s =>
                {
                    return(new SignatureInformation
                    {
                        Label = parameterSets.CommandName + " " + s.SignatureText,
                        Documentation = null,
                        Parameters =
                            s.Parameters
                            .Select(CreateParameterInfo)
                            .ToArray()
                    });
                })
                    .ToArray();
            }
            else
            {
                signatures = new SignatureInformation[0];
            }

            await requestContext.SendResult(
                new SignatureHelp
            {
                Signatures      = signatures,
                ActiveParameter = activeParameter,
                ActiveSignature = activeSignature
            });
        }
Example #21
0
        public void WorkWithGenerics()
        {
            var manifest = BehaviourManifest.CreateFromAppDomain(AppDomain.CurrentDomain);

            var generic = new GenericModel()
            {
                Data = JObject.FromObject(new ChildModel()),
                Type = "ChildModel"
            };

            var editorSession = new EditorSession(manifest, generic, new JsonSerializer());

            DrawTree(editorSession.Root);
        }
Example #22
0
        public async Task <IActionResult> Create(EditorSession editorSession)
        {
            if (ModelState.IsValid)
            {
                //editorSession.Id = Guid.NewGuid();
                editorSession.Teacher = await _userManager.GetUserAsync(User);

                _context.Add(editorSession);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(editorSession));
        }
Example #23
0
        protected async Task HandleHoverRequest(
            TextDocumentPosition textDocumentPosition,
            EditorSession editorSession,
            RequestContext <Hover, object> requestContext)
        {
            ScriptFile scriptFile =
                editorSession.Workspace.GetFile(
                    textDocumentPosition.Uri);

            SymbolDetails symbolDetails =
                await editorSession
                .LanguageService
                .FindSymbolDetailsAtLocation(
                    scriptFile,
                    textDocumentPosition.Position.Line + 1,
                    textDocumentPosition.Position.Character + 1);

            List <MarkedString> symbolInfo = new List <MarkedString>();
            Range?symbolRange = null;

            if (symbolDetails != null)
            {
                symbolInfo.Add(
                    new MarkedString
                {
                    Language = "PowerShell",
                    Value    = symbolDetails.DisplayString
                });

                if (!string.IsNullOrEmpty(symbolDetails.Documentation))
                {
                    symbolInfo.Add(
                        new MarkedString
                    {
                        Language = "markdown",
                        Value    = symbolDetails.Documentation
                    });
                }

                symbolRange = GetRangeFromScriptRegion(symbolDetails.SymbolReference.ScriptRegion);
            }

            await requestContext.SendResult(
                new Hover
            {
                Contents = symbolInfo.ToArray(),
                Range    = symbolRange
            });
        }
Example #24
0
        public EditorSessionFrame(IResource resource)
        {
            Resource = resource;

            JObject editorTarget;

            using (var editorTargetData = Resource.LoadStream())
                using (var sr = new StreamReader(editorTargetData))
                    using (var reader = new JsonTextReader(sr))
                    {
                        editorTarget = JObject.Load(reader);
                    }

            var manifest = BehaviourManifest.CreateFromAppDomain(AppDomain.CurrentDomain);

            string typeName = null;

            if (Resource.Tags.Contains("type-building"))
            {
                typeName = "BuildingTemplate";
            }
            else if (Resource.Tags.Contains("type-resource"))
            {
                typeName = "ResourceTemplate";
            }
            else if (Resource.Tags.Contains("type-buildingpack"))
            {
                typeName = "BuildingPackTemplate";
            }
            else if (Resource.Tags.Contains("gamerules"))
            {
                typeName = "GameRulesTemplate";
            }
            else
            {
                typeName = "ProceduralItemTemplate";
            }

            EditorSession = new EditorSession(manifest, editorTarget, typeName, serializer);

            EditorSession.OnChanged += () =>
            {
                HasUnsavedChanges = true;
            };

            var feature = EditorSession.Root.GetOrCreateFeature <FramedEditorSessionFeature>();

            feature.Frame = this;
        }
Example #25
0
        public static void Open(EditorSession session, EditorObject editorObject)
        {
            var window = GetWindow <BehaviourEditor>();

            window.Show();

            window.GraphFrame = new BehaviourGraphFrame
            {
                View = new BehaviourEditorView()
            };
            window.GraphFrame.View.BeginSession(session, editorObject);

            window.GraphFrame.Window = window;
            window.GraphFrame.OnEnable();
        }
Example #26
0
        public override async Task OnConnectedAsync()
        {
            string        sessionId     = Context.GetHttpContext().Request.Query["sessionid"];
            EditorSession editorSession = await _dbContext.Sessions.Include(x => x.Teacher).SingleOrDefaultAsync(x => x.Id == Guid.Parse(sessionId)); // SingleOrDefault(x => x.Id == Guid.Parse(sessionId));

            if (Context.User.Identity.Name != editorSession.Teacher.UserName)
            {
                await Groups.AddToGroupAsync(Context.ConnectionId, editorSession.SignalRStudentGroupName());
            }
            else
            {
                await Groups.AddToGroupAsync(Context.ConnectionId, editorSession.SignalRTeacherGroupName());
            }
            await base.OnConnectedAsync();
        }
        private async void OnLanguageServiceClientConnect(
            object sender,
            TcpSocketServerChannel serverChannel)
        {
            MessageDispatcher messageDispatcher = new MessageDispatcher(this.logger);

            ProtocolEndpoint protocolEndpoint =
                new ProtocolEndpoint(
                    serverChannel,
                    messageDispatcher,
                    this.logger);

            protocolEndpoint.UnhandledException += ProtocolEndpoint_UnhandledException;

            this.editorSession =
                CreateSession(
                    this.hostDetails,
                    this.profilePaths,
                    protocolEndpoint,
                    messageDispatcher,
                    this.enableConsoleRepl);

            this.languageServer =
                new LanguageServer(
                    this.editorSession,
                    messageDispatcher,
                    protocolEndpoint,
                    this.logger);

            await this.editorSession.PowerShellContext.ImportCommandsModule(
                Path.Combine(
                    Path.GetDirectoryName(this.GetType().GetTypeInfo().Assembly.Location),
                    @"..\..\Commands"));

            this.languageServer.Start();

            // TODO: This can be moved to the point after the $psEditor object
            // gets initialized when that is done earlier than LanguageServer.Initialize
            foreach (string module in this.additionalModules)
            {
                await this.editorSession.PowerShellContext.ExecuteCommand <System.Management.Automation.PSObject>(
                    new System.Management.Automation.PSCommand().AddCommand("Import-Module").AddArgument(module),
                    false,
                    true);
            }

            protocolEndpoint.Start();
        }
Example #28
0
        public CodeLensFeature(
            EditorSession editorSession,
            IMessageHandlers messageHandlers,
            ILogger logger)
            : base(logger)
        {
            this.editorSession = editorSession;

            messageHandlers.SetRequestHandler(
                CodeLensRequest.Type,
                this.HandleCodeLensRequest);

            messageHandlers.SetRequestHandler(
                CodeLensResolveRequest.Type,
                this.HandleCodeLensResolveRequest);
        }
Example #29
0
        public DebugAdapter(
            HostDetails hostDetails,
            ProfilePaths profilePaths,
            ChannelBase serverChannel,
            IEditorOperations editorOperations)
            : base(serverChannel)
        {
            this.editorSession = new EditorSession();
            this.editorSession.StartDebugSession(hostDetails, profilePaths, editorOperations);
            this.editorSession.PowerShellContext.RunspaceChanged += this.powerShellContext_RunspaceChanged;
            this.editorSession.DebugService.DebuggerStopped      += this.DebugService_DebuggerStopped;
            this.editorSession.ConsoleService.OutputWritten      += this.powerShellContext_OutputWritten;

            // Set up the output debouncer to throttle output event writes
            this.outputDebouncer = new OutputDebouncer(this);
        }
Example #30
0
        protected Task HandleDidCloseTextDocumentNotification(
            TextDocumentIdentifier closeParams,
            EditorSession editorSession,
            EventContext eventContext)
        {
            // Find and close the file in the current session
            var fileToClose = editorSession.Workspace.GetFile(closeParams.Uri);

            if (fileToClose != null)
            {
                editorSession.Workspace.CloseFile(fileToClose);
            }

            Logger.Write(LogLevel.Verbose, "Finished closing document.");

            return(Task.FromResult(true));
        }
        public LanguageServer(ChannelBase serverChannel) : base(serverChannel)
        {
            this.editorSession = new EditorSession();
            this.editorSession.StartSession();
            this.editorSession.ConsoleService.OutputWritten += this.powerShellContext_OutputWritten;

            // Always send console prompts through the UI in the language service
            // TODO: This will change later once we have a general REPL available
            // in VS Code.
            this.editorSession.ConsoleService.PushPromptHandlerContext(
                new ProtocolPromptHandlerContext(
                    this,
                    this.editorSession.ConsoleService));

            // Set up the output debouncer to throttle output event writes
            this.outputDebouncer = new OutputDebouncer(this);
        }
Example #32
0
        protected async Task HandleDocumentSymbolRequest(
            TextDocumentIdentifier textDocumentIdentifier,
            EditorSession editorSession,
            RequestContext <SymbolInformation[], object> requestContext)
        {
            ScriptFile scriptFile =
                editorSession.Workspace.GetFile(
                    textDocumentIdentifier.Uri);

            FindOccurrencesResult foundSymbols =
                editorSession.LanguageService.FindSymbolsInFile(
                    scriptFile);

            SymbolInformation[] symbols = null;

            string containerName = Path.GetFileNameWithoutExtension(scriptFile.FilePath);

            if (foundSymbols != null)
            {
                symbols =
                    foundSymbols
                    .FoundOccurrences
                    .Select(r =>
                {
                    return(new SymbolInformation
                    {
                        ContainerName = containerName,
                        Kind = GetSymbolKind(r.SymbolType),
                        Location = new Location
                        {
                            Uri = new Uri(r.FilePath).AbsolutePath,
                            Range = GetRangeFromScriptRegion(r.ScriptRegion)
                        },
                        Name = GetDecoratedSymbolName(r)
                    });
                })
                    .ToArray();
            }
            else
            {
                symbols = new SymbolInformation[0];
            }

            await requestContext.SendResult(symbols);
        }
        private static async Task DelayThenInvokeDiagnostics(
            int delayMilliseconds,
            ScriptFile[] filesToAnalyze,
            EditorSession editorSession,
            EventContext eventContext,
            CancellationToken cancellationToken)
        {
            // First of all, wait for the desired delay period before
            // analyzing the provided list of files
            try
            {
                await Task.Delay(delayMilliseconds, cancellationToken);
            }
            catch (TaskCanceledException)
            {
                // If the task is cancelled, exit directly
                return;
            }

            // If we've made it past the delay period then we don't care
            // about the cancellation token anymore.  This could happen
            // when the user stops typing for long enough that the delay
            // period ends but then starts typing while analysis is going
            // on.  It makes sense to send back the results from the first
            // delay period while the second one is ticking away.

            // Get the requested files
            foreach (ScriptFile scriptFile in filesToAnalyze)
            {
                Logger.Write(LogLevel.Verbose, "Analyzing script file: " + scriptFile.FilePath);

                var semanticMarkers =
                    editorSession.AnalysisService.GetSemanticMarkers(
                        scriptFile);

                var allMarkers = scriptFile.SyntaxMarkers.Concat(semanticMarkers);

                await PublishScriptDiagnostics(
                    scriptFile,
                    semanticMarkers,
                    eventContext);
            }

            Logger.Write(LogLevel.Verbose, "Analysis complete.");
        }
Example #34
0
        public async Task PostComment(string questionId, JObject range, string comment)
        {
            string          sessionId = Context.GetHttpContext().Request.Query["sessionid"];
            SessionQuestion sessionQuestion;

            if (string.IsNullOrWhiteSpace(questionId))
            {
                sessionQuestion = new SessionQuestion
                {
                    StartLineNumber = range.Value <int>("startLineNumber"),
                    StartColumn     = range.Value <int>("startColumn"),
                    EndLineNumber   = range.Value <int>("endLineNumber"),
                    EndColumn       = range.Value <int>("endColumn"),
                    AskedBy         = await _userManager.GetUserAsync(Context.User)
                };
                EditorSession editorSession = await _dbContext.Sessions.FindAsync(Guid.Parse(sessionId));

                editorSession.Questions.Add(sessionQuestion);
            }
            else
            {
                sessionQuestion = await _dbContext.SessionQuestions.FindAsync(Guid.Parse(questionId));
            }

            SessionQuestionComment sessionQuestionComment = new SessionQuestionComment
            {
                Text = comment,
                User = await _userManager.GetUserAsync(Context.User)
            };

            sessionQuestion.Comments.Add(sessionQuestionComment);

            _dbContext.SaveChanges();

            if (string.IsNullOrWhiteSpace(questionId))
            {
                await Clients.Group($"{sessionId}_Teachers").SendCoreAsync("QuestionPosted", new object[] { sessionQuestion });

                await Clients.Client(Context.ConnectionId).SendCoreAsync("QuestionPosted", new object[] { sessionQuestion });
            }
            else
            {
                await Clients.All.SendCoreAsync("CommentPosted", new object[] { sessionQuestion.Id, sessionQuestionComment });
            }
        }
        protected async Task HandleScopesRequest(
            ScopesRequestArguments scopesParams,
            EditorSession editorSession,
            RequestContext <ScopesResponseBody, object> requestContext)
        {
            VariableScope[] variableScopes =
                editorSession.DebugService.GetVariableScopes(
                    scopesParams.FrameId);

            await requestContext.SendResult(
                new ScopesResponseBody
            {
                Scopes =
                    variableScopes
                    .Select(Scope.Create)
                    .ToArray()
            });
        }
Example #36
0
        public DebuggerService2(RunbookViewModel runbookViewModel)
        {
            Logger.Initialize(Path.Combine(AppHelper.CachePath, "PowerShellEditorServices.log"), LogLevel.Verbose);

            /*_powerShell = new PowerShellContext();
             * _workspace = new Workspace(_powerShell.PowerShellVersion);
             *
             * _debugService = new DebugService(_powerShell);
             * _debugService.DebuggerStopped += OnDebugStopped;*/
            _editorSession = new EditorSession();
            _editorSession.StartSession();
            _editorSession.DebugService.DebuggerStopped += OnDebugStopped;
            _editorSession.ConsoleService.OutputWritten += OnConsoleOutputWritten;

            _runbookViewModel = runbookViewModel;

            _breakpoints = new List <LineBreakpoint>();
        }
        private static async Task DelayThenInvokeDiagnostics(
            int delayMilliseconds,
            ScriptFile[] filesToAnalyze,
            EditorSession editorSession,
            EventContext eventContext,
            CancellationToken cancellationToken)
        {
            // First of all, wait for the desired delay period before
            // analyzing the provided list of files
            try
            {
                await Task.Delay(delayMilliseconds, cancellationToken);
            }
            catch (TaskCanceledException)
            {
                // If the task is cancelled, exit directly
                return;
            }

            // If we've made it past the delay period then we don't care
            // about the cancellation token anymore.  This could happen
            // when the user stops typing for long enough that the delay
            // period ends but then starts typing while analysis is going
            // on.  It makes sense to send back the results from the first
            // delay period while the second one is ticking away.

            // Get the requested files
            foreach (ScriptFile scriptFile in filesToAnalyze)
            {
                Logger.Write(LogLevel.Verbose, "Analyzing script file: " + scriptFile.FilePath);

                var semanticMarkers =
                    editorSession.AnalysisService.GetSemanticMarkers(
                        scriptFile);

                var allMarkers = scriptFile.SyntaxMarkers.Concat(semanticMarkers);

                await PublishScriptDiagnostics(
                    scriptFile,
                    semanticMarkers,
                    eventContext);
            }

            Logger.Write(LogLevel.Verbose, "Analysis complete.");
        }
        private Task RunScriptDiagnostics(
            ScriptFile[] filesToAnalyze,
            EditorSession editorSession,
            EventContext eventContext)
        {
            if (!this.currentSettings.ScriptAnalysis.Enable.Value)
            {
                // If the user has disabled script analysis, skip it entirely
                return Task.FromResult(true);
            }

            // If there's an existing task, attempt to cancel it
            try
            {
                if (existingRequestCancellation != null)
                {
                    // Try to cancel the request
                    existingRequestCancellation.Cancel();

                    // If cancellation didn't throw an exception,
                    // clean up the existing token
                    existingRequestCancellation.Dispose();
                    existingRequestCancellation = null;
                }
            }
            catch (Exception e)
            {
                // TODO: Catch a more specific exception!
                Logger.Write(
                    LogLevel.Error,
                    string.Format(
                        "Exception while cancelling analysis task:\n\n{0}",
                        e.ToString()));

                TaskCompletionSource<bool> cancelTask = new TaskCompletionSource<bool>();
                cancelTask.SetCanceled();
                return cancelTask.Task;
            }

            // Create a fresh cancellation token and then start the task.
            // We create this on a different TaskScheduler so that we
            // don't block the main message loop thread.
            // TODO: Is there a better way to do this?
            existingRequestCancellation = new CancellationTokenSource();
            Task.Factory.StartNew(
                () =>
                    DelayThenInvokeDiagnostics(
                        750,
                        filesToAnalyze,
                        editorSession,
                        eventContext,
                        existingRequestCancellation.Token),
                CancellationToken.None,
                TaskCreationOptions.None,
                TaskScheduler.Default);

            return Task.FromResult(true);
        }
 public Task ProcessMessage(
     EditorSession editorSession, 
     MessageWriter messageWriter)
 {
     return Task.FromResult(false);
 }
 public LanguageServer(ChannelBase serverChannel) : base(serverChannel)
 {
     this.editorSession = new EditorSession();
     this.editorSession.StartSession();
     this.editorSession.PowerShellContext.OutputWritten += this.powerShellContext_OutputWritten;
 }
        async Task ListenForMessages()
        {
            this.messageLoopSyncContext = SynchronizationContext.Current;

            // Ensure that the console is using UTF-8 encoding
            System.Console.InputEncoding = Encoding.UTF8;
            System.Console.OutputEncoding = Encoding.UTF8;

            // Open the standard input/output streams
            this.inputStream = System.Console.OpenStandardInput();
            this.outputStream = System.Console.OpenStandardOutput();

            IMessageSerializer messageSerializer = null;
            IMessageProcessor messageProcessor = null;

            // Use a different serializer and message processor based
            // on whether this instance should host a language server
            // debug adapter.
            if (this.runDebugAdapter)
            {
                DebugAdapter debugAdapter = new DebugAdapter();
                debugAdapter.Initialize();

                messageProcessor = debugAdapter;
                messageSerializer = new V8MessageSerializer();
            }
            else
            {
                // Set up the LanguageServer
                LanguageServer languageServer = new LanguageServer();
                languageServer.Initialize();

                messageProcessor = languageServer;
                messageSerializer = new JsonRpcMessageSerializer();
            }

            // Set up the reader and writer
            this.messageReader = 
                new MessageReader(
                    this.inputStream,
                    messageSerializer);

            this.messageWriter = 
                new MessageWriter(
                    this.outputStream,
                    messageSerializer);

            // Set up the console host which will send events
            // through the MessageWriter
            this.consoleHost = new StdioConsoleHost(messageWriter);

            // Set up the PowerShell session
            this.editorSession = new EditorSession();
            this.editorSession.StartSession(this.consoleHost);
            this.editorSession.PowerShellContext.OutputWritten += powerShellContext_OutputWritten;

            if (this.runDebugAdapter)
            {
                // Attach to debugger events from the PowerShell session
                this.editorSession.DebugService.DebuggerStopped += DebugService_DebuggerStopped;
            }

            // Run the message loop
            bool isRunning = true;
            while (isRunning)
            {
                Message newMessage = null;

                try
                {
                    // Read a message from stdin
                    newMessage = await this.messageReader.ReadMessage();
                }
                catch (MessageParseException e)
                {
                    // TODO: Write an error response

                    Logger.Write(
                        LogLevel.Error,
                        "Could not parse a message that was received:\r\n\r\n" +
                        e.ToString());

                    // Continue the loop
                    continue;
                }

                // Process the message
                await messageProcessor.ProcessMessage(
                    newMessage,
                    this.editorSession,
                    this.messageWriter);
            }
        }