Esempio n. 1
0
        /// <summary>
        /// Override this method to define the async command body te execute on the
        /// background thread
        /// </summary>
        protected override async Task ExecuteAsync()
        {
            IVsStatusbar statusBar = (IVsStatusbar)await SpectNetPackage.Default.GetServiceAsync(typeof(SVsStatusbar));

            statusBar.IsFrozen(out int frozen);
            if (frozen != 0)
            {
                statusBar.FreezeOutput(0);
            }
            statusBar.SetText("Building ZX Spectrum code");
            statusBar.FreezeOutput(1);
            object icon = (short)Constants.SBAI_Build;

            statusBar.Animation(1, ref icon);
            try
            {
                CompileSuccess = await Task.Run(() => CompileCode());
            }
            catch (Exception ex)
            {
                CompileException = ex;
            }
            finally
            {
                statusBar.FreezeOutput(0);
                statusBar.Animation(0, ref icon);
                statusBar.Clear();
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Update status bar.
        /// </summary>
        /// <param name="message"></param>
        private void UpdateStatusBar(string message)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            IVsStatusbar statusBar = (IVsStatusbar)ServiceProvider.GetService(typeof(SVsStatusbar));

            Assumes.Present(statusBar);

            // Make sure the status bar is not frozen

            statusBar.IsFrozen(out int frozen);

            if (frozen != 0)
            {
                statusBar.FreezeOutput(0);
            }

            // Set the status bar text and make its display static.
            statusBar.SetText(message);

            // Freeze the status bar.
            statusBar.FreezeOutput(1);

            // Clear the status bar text.
            statusBar.FreezeOutput(0);
            statusBar.Clear();
        }
        public static void Text(string aText, int aFreezeStatusBar)
        {
            DispatcherHandler.BeginInvoke(() =>
            {
                // Make sure the status bar is not frozen
                if (VSConstants.S_OK != mStatusBar.IsFrozen(out int frozen))
                {
                    return;
                }

                if (0 != frozen)
                {
                    mStatusBar.FreezeOutput(0);
                }

                // Set the status bar text
                mStatusBar.SetText(aText);

                // Freeze the status bar.
                mStatusBar.FreezeOutput(aFreezeStatusBar);

                // Clear the status bar text.
                if (0 == aFreezeStatusBar)
                {
                    mStatusBar.Clear();
                }
            });
        }
        public override void StopProgressMsg(string msg)
        {
            try
            {
                int fFrozen = 1;
                if (m_statusBar != null && m_statusBar.IsFrozen(out fFrozen) == Utility.COM_HResults.S_OK)
                {
                    if (fFrozen == 1)
                    {
                        m_statusBar.FreezeOutput(0);
                    }

                    if (String.IsNullOrEmpty(msg))
                    {
                        m_statusBar.Clear();
                    }
                    else
                    {
                        m_statusBar.SetText(msg);
                    }
                }
            }
            catch (InvalidOperationException)
            {
            }
        }
Esempio n. 5
0
        public static void StopProgressMessage(string message = null)
        {
            ThreadHelper.JoinableTaskFactory.RunAsync(async() =>
            {
                await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                // stock general animation icon
                object icon = (short)Constants.SBAI_General;

                // Make sure the status bar is not frozen
                int frozen;
                _statusBar.IsFrozen(out frozen);

                if (frozen != 0)
                {
                    _statusBar.FreezeOutput(0);
                }


                if (String.IsNullOrEmpty(message))
                {
                    _statusBar.SetText(message);
                }
                else
                {
                    _statusBar.Clear();
                }

                // stop the animation
                _statusBar?.Animation(0, ref icon);
            });
        }
Esempio n. 6
0
        static public void Run(IServiceProvider serviceProvider, IVsStatusbar statusbar)
        {
            var dte      = (DTE2)serviceProvider.GetService(typeof(DTE));
            var projects = dte.Solution.Projects;

            uint   cookie = 0;
            object icon   = (short)Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Build;

            // Initialize the progress bar.
            statusbar.Progress(ref cookie, 1, "", 0, 0);
            statusbar.Animation(1, ref icon);

            for (uint i = 1, n = (uint)projects.Count; i <= n; ++i)
            {
                var project = projects.Item(i);
                statusbar.Progress(ref cookie, 1, "", i + 1, n);
                statusbar.SetText(string.Format("Converting {0}", project.Name));

                ProjectConverter.Run(serviceProvider, project);
            }

            // Clear the progress bar.
            statusbar.Animation(0, ref icon);
            statusbar.Progress(ref cookie, 0, "", 0, 0);
            statusbar.FreezeOutput(0);
            statusbar.Clear();
        }
Esempio n. 7
0
        public override void StopProgressMessage(string message)
        {
            // stock general animation icon
            object icon = (short)Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_General;

            try
            {
                // Make sure the status bar is not frozen
                int frozen;
                _statusBar.IsFrozen(out frozen);

                if (frozen != 0)
                {
                    _statusBar.FreezeOutput(0);
                }


                if (String.IsNullOrEmpty(message))
                {
                    _statusBar.SetText(message);
                }
                else
                {
                    _statusBar.Clear();
                }

                // stop the animation
                _statusBar?.Animation(0, ref icon);
            }
            catch (InvalidOperationException)
            {
            }
        }
Esempio n. 8
0
 public void Clear()
 {
     if (!IsFrozen())
     {
         ErrorHandler.ThrowOnFailure(statusBar.SetText(Properties.Resources.StatusBarDefault));
         ErrorHandler.ThrowOnFailure(statusBar.Clear());
     }
 }
Esempio n. 9
0
 public void Dispose(string?endMessage = null)
 {
     Microsoft.VisualStudio.Shell.ThreadHelper.ThrowIfNotOnUIThread();
     // Clear the status bar text.
     _statusBar.FreezeOutput(0);
     _statusBar.SetText(endMessage ?? "ready");
     _statusBar.Clear();
 }
Esempio n. 10
0
        private void ClearVsStatusbarText()
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            IVsStatusbar statusBar = (IVsStatusbar)ServiceProvider.GetService(typeof(SVsStatusbar));

            Assumes.Present(statusBar);
            statusBar.FreezeOutput(0);
            statusBar.Clear();
        }
Esempio n. 11
0
        public void ClearStatusBar()
        {
            if (null == _statusbar)
            {
                return;
            }

            _statusbar.Clear();
        }
Esempio n. 12
0
            public override void Dispose()
            {
                _taskFactory.Run(async() =>
                {
                    await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

                    StatusBar.Animation(0, ref icon);
                    StatusBar.Progress(ref cookie, 0, "", 0, 0);
                    StatusBar.FreezeOutput(0);
                    StatusBar.Clear();
                });
            }
            public override void Dispose()
            {
                _taskFactory.Run(async() =>
                {
                    await _taskFactory.SwitchToMainThreadAsync();

                    _statusBar.Animation(0, ref Icon);
                    _statusBar.Progress(ref _cookie, 0, "", 0, 0);
                    _statusBar.FreezeOutput(0);
                    _statusBar.Clear();
                });
            }
        private void Print(
            IVsStatusbar statusBar,
            JObject quantifierResult)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            string output = $"PrQuantified = {quantifierResult["Label"]},\t" +
                            $"Diff +{quantifierResult["QuantifiedLinesAdded"]} -{quantifierResult["QuantifiedLinesDeleted"]} (Formula = {quantifierResult["Formula"]})," +
                            $"\tPercentiles: additions = {quantifierResult["PercentileAddition"]}%" +
                            $", deletions = {quantifierResult["PercentileDeletion"]}%, Diff = {quantifierResult["FormulaPercentile"]}%.";

            statusBar.Clear();
            statusBar.SetText(output);
        }
 /// <summary>
 /// Display text on the Visual Studio status bar.
 /// </summary>
 /// <param name="text"></param>
 private void DisplayTextOnStatusBar(string text)
 {
     if (statusBar != null)
     {
         statusBar.IsFrozen(out frozen);
         if (frozen == 0)
         {
             // Set the status bar text and make its display static.
             statusBar.SetText(text);
             statusBar.FreezeOutput(1);
             // Clear the status bar text.
             statusBar.FreezeOutput(0);
             statusBar.Clear();
         }
     }
 }
        /// <summary>Clears all text from the status bar.</summary>
        public async Task ClearAsync()
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                IVsStatusbar statusBar = await VS.Services.GetStatusBarAsync();

                statusBar.FreezeOutput(0);
                statusBar.Clear();
                statusBar.FreezeOutput(1);
            }
            catch (Exception ex)
            {
                await ex.LogAsync();
            }
        }
Esempio n. 17
0
        public static async Task ClearAsync()
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            try
            {
                IVsStatusbar statusBar = await GetServiceAsync();

                statusBar.FreezeOutput(0);
                statusBar.Clear();
                statusBar.FreezeOutput(1);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }
Esempio n. 18
0
        public void WriteStatus(string message)
        {
            // Make sure the status bar is not frozen
            int frozen;

            _statusBar.IsFrozen(out frozen);
            if (frozen != 0)
            {
                _statusBar.FreezeOutput(0);
            }

            // Set the status bar text and make its display static.
            _statusBar.SetText(message);

            // Freeze the status bar.
            _statusBar.FreezeOutput(1);

            // Clear the status bar text.
            _statusBar.FreezeOutput(0);
            _statusBar.Clear();
        }
Esempio n. 19
0
        //<Snippet1>
        void FeedbackRegionExample()
        {
            IVsStatusbar statusBar =
                (IVsStatusbar)GetService(typeof(SVsStatusbar));
            int frozen;

            statusBar.IsFrozen(out frozen);

            if (frozen == 0)
            {
                // Set the status bar text and make its display static.
                statusBar.SetText("Here's some static text.");
                statusBar.FreezeOutput(1);

                // Retrieve the status bar text.
                string text;
                statusBar.GetText(out text);
                System.Windows.Forms.MessageBox.Show(text);

                // Clear the status bar text.
                statusBar.FreezeOutput(0);
                statusBar.Clear();
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Get all library archives accessible to the linker of the specified project.
        /// </summary>
        /// <param name="project">The project to get the LibArchives for</param>
        /// <param name="statusBar">the VS status bar</param>
        /// <returns>Parsed libraries which are accessible by the linker of the given project.</returns>
        public List<LibArchive> GetLibraryArchives(Project project, IVsStatusbar statusBar)
        {
            int frozen;
            uint cookie = 0;
            statusBar.IsFrozen(out frozen);

            if (!_projectArchiveMap.ContainsKey(project))
            {
                var archives = new List<LibArchive>();
                var libraries = GetLibraries(project);

                if (frozen == 0)
                    statusBar.Progress(ref cookie, 1, "", 0, (uint)libraries.Count);

                int i = 0;
                foreach(var lib in libraries)
                {
                    if (frozen == 0)
                    {
                        statusBar.Progress(ref cookie, 1, "", (uint) i++, (uint)libraries.Count);
                        statusBar.SetText("Scanning " + Path.GetFileName(lib));
                    }

                    archives.Add(GetArchive(lib));
                }
                _projectArchiveMap.Add(project, archives);
            }

            if (frozen == 0)
            {
                statusBar.Progress(ref cookie, 0, "", 0, 0);
                statusBar.Clear();
            }

            return _projectArchiveMap[project];
        }
Esempio n. 21
0
 public void Clear()
 {
     _statusBar.Clear();
 }
Esempio n. 22
0
        public string ParseHtml(string text, List <HtmlElement> elementList, TextDocument txtDoc, IVsStatusbar bar, ref uint cookie)
        {
            int  pointer       = 0;
            var  startTagIndex = 0;
            var  endTagIndex   = 0;
            var  endTagBefore  = 0;
            uint completed     = 0;
            uint total         = (uint)text.Count(q => q == '<');

            #region trimming style tags contens
            while (text.Contains("; ") || text.Contains(": ")) //to fix style tag content
            {
                text = text.Replace("; ", ";").Replace(": ", ":");
            }
            #endregion

            text          = text.Replace("STYLE", "style");
            startTagIndex = text.IndexOf('<', pointer);
            endTagIndex   = text.IndexOf('>', pointer);

            try
            {
                txtDoc.Selection.StartOfDocument();
                while (pointer < text.Length && startTagIndex != -1 || endTagIndex != -1)
                {
                    completed++;
                    bar.Progress(ref cookie, 1, string.Empty, completed, total);
                    bar.SetText("Extracting inline styles ...");

                    #region to find current line (txtDoc.Selection.CurrentLine)

                    txtDoc.Selection.CharRight(false, endTagIndex - endTagBefore);
                    endTagBefore = endTagIndex;

                    #endregion

                    var elementText = text.Substring(startTagIndex + 1, (endTagIndex - (startTagIndex + 1)));
                    if (elementText.Contains("style=")) // '=' is really necessary
                    {
                        var parsedElement = elementText.Split(' ');
                        var elementName   = parsedElement[0];
                        var elementId     = string.Empty;
                        var elementStyle  = string.Empty;
                        var elementClass  = string.Empty;
                        var guid          = Guid.NewGuid().ToString();

                        #region checking id attr

                        var idAttr = parsedElement.FirstOrDefault(q => q.Contains("id="));
                        if (idAttr != null)
                        {
                            elementId = idAttr.Replace("id=", string.Empty).Replace("\"", string.Empty);
                        }
                        #endregion

                        #region checking style attr

                        if (parsedElement.Any(q => q.Contains("style=")))
                        {
                            var styleStart = elementText.IndexOf("\"", elementText.IndexOf("style=")) + 1;
                            var styleEnd   = elementText.IndexOf("\"", styleStart);
                            elementStyle = elementText.Substring(styleStart, (styleEnd - styleStart));
                        }

                        elementStyle = elementStyle.EndsWith(";") ? elementStyle : string.Format("{0};", elementStyle);

                        #endregion

                        #region checking class attr

                        var classAttr = parsedElement.Any(q => q.Contains("class="));
                        if (classAttr)
                        {
                            //one class or more?
                            var classStart = elementText.IndexOf("\"", elementText.IndexOf("class"));
                            var classEnd   = elementText.IndexOf("\"", classStart + 1);
                            var classText  = elementText.Substring(classStart, (classEnd - classStart));
                            classText    = classText.Replace(" ", " ."); // "class1 class2" - > "class1 .class2"
                            elementClass = classText.Replace("\"", string.Empty);
                        }

                        #endregion

                        text    = text.Replace(elementText, guid);
                        pointer = text.IndexOf('>', text.IndexOf(guid)) + 1;

                        endTagBefore = endTagBefore + (guid.Length - elementText.Length);

                        //burada entagbefore u revize etmek lazım sanırım. guid.lengt- elementtext.length kadar ekleme yapılabilir

                        elementList.Add(new HtmlElement
                        {
                            Id         = elementId,
                            Name       = elementName,
                            Style      = elementStyle,
                            Class      = elementClass,
                            Guid       = guid,
                            LineNumber = txtDoc.Selection.CurrentLine
                        });
                    }
                    else
                    {
                        pointer = endTagIndex + 1;
                    }

                    startTagIndex = text.IndexOf('<', pointer);
                    endTagIndex   = text.IndexOf('>', pointer);
                }
            }
            catch (Exception)
            {
                // Clear the progress bar.
                bar.Progress(ref cookie, 0, string.Empty, 0, 0);
                bar.FreezeOutput(0);
                bar.Clear();
                //throw;
            }
            return(text);
        }
Esempio n. 23
0
        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private async void ExecuteAsync(object sender, EventArgs e)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            string title = "TrustSource Scanner";

            logger.Debug($"TrustSource scanner Initiated");
            string OptionalBranch = "", OptionalTag = "";

            TrustSourceSettings tsSettings = ((TrustSourceToolsOptions)package).TrustSourceApiSettings;
            bool IsApiConfigured           = !(tsSettings == null || string.IsNullOrEmpty(tsSettings.ApiKey));

            if (!IsApiConfigured)
            {
                string message = "TrustSource Api credentials are not avialable. Please go to Tools preferences and set TrustSource credentails.";
                logger.Debug(message);

                VsShellUtilities.ShowMessageBox(
                    this.package,
                    message,
                    title,
                    OLEMSGICON.OLEMSGICON_INFO,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

                return;
            }

            DTE dte = (DTE)await ServiceProvider.GetServiceAsync(typeof(DTE));

            if (dte != null && !dte.Application.Solution.IsOpen)
            {
                string message = "There is no solution open. Please first open a solution and try again.";
                logger.Debug(message);

                VsShellUtilities.ShowMessageBox(
                    this.package,
                    message,
                    title,
                    OLEMSGICON.OLEMSGICON_INFO,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

                return;
            }

            IVsStatusbar statusBar = (IVsStatusbar)await ServiceProvider.GetServiceAsync(typeof(SVsStatusbar));

            if (statusBar != null)
            {
                // Make sure the status bar is not frozen
                int frozen;

                statusBar.IsFrozen(out frozen);

                if (frozen != 0)
                {
                    statusBar.FreezeOutput(0);
                }

                statusBar.SetText("TrustSource Scanner is in progress..");
                statusBar.FreezeOutput(1);
            }

            if (tsSettings.AskOptional)
            {
                string message = "Dialog for optional parameters";
                logger.Debug(message);

                var  optionalParamsWindow = new OptionalParamsWindow();
                bool?IsProceed            = optionalParamsWindow.ShowDialog();

                if (IsProceed.HasValue && IsProceed.Value)
                {
                    OptionalBranch = optionalParamsWindow.Branch;
                    OptionalTag    = optionalParamsWindow.TagValue;
                }
            }

            try
            {
                SolutionBuild          builder = dte.Application.Solution.SolutionBuild;
                SolutionConfiguration2 config  = (SolutionConfiguration2)builder.ActiveConfiguration;

                /*
                 *              var activeProject = Helper.GetActiveProject(dte);
                 *              if (activeProject == null)
                 *              {
                 *                  throw new Exception("No project is selected. Please, select a project in the solution explorer.");
                 *              }
                 *
                 *              string projectPath = activeProject.FullName;
                 */

                var activeSolution = dte.Solution;
                if (activeSolution == null)
                {
                    throw new Exception("No active solution is found.");
                }

                var projectPath = activeSolution.FullName;

                logger.Debug($"TrustSource Api Key: {tsSettings.ApiKey}");
                logger.Debug($"Project Path: {projectPath}");
                logger.Debug($"Branch (optional): {OptionalBranch}");
                logger.Debug($"Tag (optional): {OptionalTag}");

                logger.Debug($"TrustSource scanner started process");
                Scanner.Initiate(projectPath, tsSettings.ApiKey, "", OptionalBranch, OptionalTag);

                statusBar.FreezeOutput(0);
                statusBar.Clear();
                statusBar.SetText("TrustSource Scan is completed");
                statusBar.FreezeOutput(1);
                statusBar.Clear();

                logger.Debug($"Scan completed successfully.");
                System.Windows.Forms.MessageBox.Show("TrustSource scan is completed", "TrustSource");
            }
            catch (Exception ex)
            {
                logger.Debug($"Exception - Error message: {ex.Message}");
                logger.Debug($"Exception - Stack Trace: {ex.StackTrace}");

                logger.Error($"Scan failed.");

                // Show a message box to prove we were here
                VsShellUtilities.ShowMessageBox(
                    this.package,
                    ex.Message,
                    title,
                    OLEMSGICON.OLEMSGICON_CRITICAL,
                    OLEMSGBUTTON.OLEMSGBUTTON_OK,
                    OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);

                statusBar.SetText("TrustSource Scan: Something went wrong");
                statusBar.FreezeOutput(0);
                statusBar.Clear();

                return;
            }
        }
Esempio n. 24
0
 public int Clear() => m_statusbar.Clear();
Esempio n. 25
0
        private void CompileCommandCallback(object sender, EventArgs args)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            //var mainWindow = System.Windows.Application.Current.MainWindow;
            //var contentControl = mainWindow?.Template?.FindName("PART_SccStatusBarHost", mainWindow) as System.Windows.Controls.ContentControl;

            //var statusbar = contentControl?.Content as System.Windows.Controls.Primitives.StatusBar;

            //statusbar.Items.Add(new System.Windows.Controls.Button() { Content = "U++test" });

            Interlocked.Exchange(ref package.IsCompiling, 1);

            if (package.dte2.Solution.SolutionBuild.BuildState != vsBuildState.vsBuildStateInProgress)
            {
                var projs    = new List <Project>();
                var selitems = package.dte2.ToolWindows.SolutionExplorer.SelectedItems as Array;
                if (selitems != null)
                {
                    foreach (var selitem in selitems)
                    {
                        var uiitem = selitem as UIHierarchyItem;
                        if (uiitem != null)
                        {
                            var proj = uiitem.Object as Project;
                            if (proj != null)
                            {
                                projs.Add(proj);
                            }
                        }
                    }
                }

                UPPCompiler.RaiseReported(null, new CompilerReportedEventArgs(null));

                package.JoinableTaskFactory.RunAsyncAsVsTask(VsTaskRunContext.UIThreadBackgroundPriority,
                                                             async cancellationToken =>
                {
                    await package.JoinableTaskFactory.SwitchToMainThreadAsync();

                    IVsMonitorSelection monitorSelection = await package.GetServiceAsync(typeof(IVsMonitorSelection)) as IVsMonitorSelection;
                    Assumes.Present(monitorSelection);
                    var sol_build_guid    = VSConstants.UICONTEXT_SolutionBuilding;
                    uint sol_build_cookie = 0;
                    monitorSelection.GetCmdUIContextCookie(ref sol_build_guid, out sol_build_cookie);

                    int uiactive = -1;
                    monitorSelection.IsCmdUIContextActive(sol_build_cookie, out uiactive);
                    if (uiactive == 0)
                    {
                        monitorSelection.SetCmdUIContext(sol_build_cookie, 1);
                    }


                    IVsStatusbar statusBar = await package.GetServiceAsync(typeof(SVsStatusbar)) as IVsStatusbar;

                    object icon = (short)Microsoft.VisualStudio.Shell.Interop.Constants.SBAI_Build;

                    statusBar?.SetText("开始编译...");
                    statusBar?.Animation(1, ref icon);

                    var tasks = package.Compile(projs);

                    statusBar?.SetText("编译...");

                    await TaskScheduler.Default;

                    await Task.WhenAll(tasks.Select(vtask => vtask.WaitForFinishedAsync()));

                    await package.JoinableTaskFactory.SwitchToMainThreadAsync();

                    statusBar?.SetText("链接源文件...");
                    tasks.ForEach(task => task.ReLink());

                    statusBar?.Animation(0, ref icon);

                    Interlocked.Exchange(ref package.IsCompiling, 0);

                    uiactive = -1;
                    monitorSelection.IsCmdUIContextActive(sol_build_cookie, out uiactive);
                    if (uiactive == 1)
                    {
                        monitorSelection.SetCmdUIContext(sol_build_cookie, 0);
                    }

                    statusBar?.SetText("已完成");
                    statusBar?.Clear();

                    return(VSConstants.S_OK);
                });
            }
        }
Esempio n. 26
0
        private async Task ReanalyzeWorkspaceHelperAsync(IPythonInterpreterFactory factory, Redirector log)
        {
            _site.MustBeCalledFromUIThread();

            try {
                if (!_recreatingAnalyzer.Wait(0))
                {
                    // Someone else is recreating, so wait for them to finish and return
                    log?.WriteLine("Waiting for existing call");
                    await _recreatingAnalyzer.WaitAsync();

                    try {
                        log?.WriteLine("Existing call complete");
                    } catch {
                        _recreatingAnalyzer.Release();
                        throw;
                    }
                    if (_analyzer?.InterpreterFactory == factory)
                    {
                        _recreatingAnalyzer.Release();
                        return;
                    }
                }
            } catch (ObjectDisposedException) {
                return;
            }

            IVsStatusbar statusBar           = null;
            bool         statusBarConfigured = false;

            try {
                if ((statusBar = _site.GetService(typeof(SVsStatusbar)) as IVsStatusbar) != null)
                {
                    statusBar.SetText(Strings.AnalyzingProject);
                    try {
                        object index = (short)0;
                        statusBar.Animation(1, ref index);
                    } catch (ArgumentNullException) {
                        // Issue in status bar implementation
                        // https://github.com/Microsoft/PTVS/issues/3064
                        // Silently suppress since animation is not critical.
                    }
                    statusBar.FreezeOutput(1);
                    statusBarConfigured = true;
                }

                var oldWatcher = _workspaceFileWatcher;
                _workspaceFileWatcher = new FileWatcher(_pythonWorkspace.Location)
                {
                    EnableRaisingEvents   = true,
                    IncludeSubdirectories = true,
                    NotifyFilter          = NotifyFilters.FileName | NotifyFilters.LastWrite
                };
                _workspaceFileWatcher.Changed += OnWorkspaceFileChanged;
                _workspaceFileWatcher.Deleted += OnWorkspaceFileDeleted;
                oldWatcher?.Dispose();

                log?.WriteLine("Creating new workspace analyzer");
                var analyzer = await CreateAnalyzerAsync(factory, _pythonWorkspace.Location);

                Debug.Assert(analyzer != null);
                log?.WriteLine($"Created workspace analyzer {analyzer}");

                WorkspaceAnalyzerChanging?.Invoke(this, new AnalyzerChangingEventArgs(_analyzer, analyzer));

                var oldAnalyzer = Interlocked.Exchange(ref _analyzer, analyzer);

                if (oldAnalyzer != null)
                {
                    if (analyzer != null)
                    {
                        int beforeCount = analyzer.Files.Count();
                        log?.WriteLine($"Transferring from old analyzer {oldAnalyzer}, which has {oldAnalyzer.Files.Count()} files");
                        await analyzer.TransferFromOldAnalyzer(oldAnalyzer);

                        log?.WriteLine($"Tranferred {analyzer.Files.Count() - beforeCount} files");
                        log?.WriteLine($"Old analyzer now has {oldAnalyzer.Files.Count()} files");
                    }
                    if (oldAnalyzer.RemoveUser())
                    {
                        log?.WriteLine("Disposing old analyzer");
                        oldAnalyzer.Dispose();
                    }
                }

                var files          = new List <string>();
                var pythonServices = _site.GetPythonToolsService();
                foreach (var existing in pythonServices.GetActiveSharedAnalyzers().Select(kv => kv.Value).Where(v => !v.IsDisposed))
                {
                    foreach (var kv in existing.LoadedFiles)
                    {
                        files.Add(kv.Key);
                        log?.WriteLine($"Unloading {kv.Key} from default analyzer");
                        foreach (var b in (kv.Value.TryGetBufferParser()?.AllBuffers).MaybeEnumerate())
                        {
                            PythonTextBufferInfo.MarkForReplacement(b);
                        }
                        try {
                            await existing.UnloadFileAsync(kv.Value);
                        } catch (ObjectDisposedException) {
                            break;
                        }
                    }
                }

                if (analyzer != null)
                {
                    // Set search paths first, as it will save full reanalysis later
                    log?.WriteLine("Setting search paths");
                    await analyzer.SetSearchPathsAsync(_pythonWorkspace.GetAbsoluteSearchPaths());

                    // Add all our files into our analyzer
                    log?.WriteLine($"Adding {files.Count} files");
                    await analyzer.AnalyzeFileAsync(files.ToArray());
                }

                WorkspaceAnalyzerChanged?.Invoke(this, EventArgs.Empty);
            } catch (ObjectDisposedException) {
                // Raced with disposal
            } catch (Exception ex) {
                log?.WriteErrorLine(ex.ToString());
                throw;
            } finally {
                try {
                    if (statusBar != null && statusBarConfigured)
                    {
                        statusBar.FreezeOutput(0);
                        object index = (short)0;
                        statusBar.Animation(0, ref index);
                        statusBar.Clear();
                    }
                } finally {
                    try {
                        _recreatingAnalyzer.Release();
                    } catch (ObjectDisposedException) {
                    }
                }
            }
        }
Esempio n. 27
0
        public void Clear()
        {
            int hr = StatusBarService.Clear();

            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hr);
        }
 public void Dispose()
 {
     _statusbar.Progress(ref _cookie, 0, "", 0, 0);
     _statusbar.FreezeOutput(0);
     _statusbar.Clear();
 }
Esempio n. 29
0
 public static void Done()
 {
     statusBar.Clear();
 }