private void documentSavedSync(Document document)
        {
            JoinableTaskFactory.Run(async() =>
            {
                await JoinableTaskFactory.SwitchToMainThreadAsync();

                if (document == null || document.Language != "C/C++")
                {
                    return;
                }

                if (Settings.Default.CheckSavedFilesHasValue && Settings.Default.CheckSavedFiles == false)
                {
                    return;
                }

                if (document.ActiveWindow == null)
                {
                    // We get here when new files are being created and added to the project and
                    // then trying to obtain document.ProjectItem yields an exception. Will just skip this.
                    return;
                }
                try
                {
                    var kind = document.ProjectItem.ContainingProject.Kind;
                    if (!isVisualCppProjectKind(document.ProjectItem.ContainingProject.Kind))
                    {
                        return;
                    }

                    Configuration currentConfig = null;
                    try { currentConfig = document.ProjectItem.ConfigurationManager.ActiveConfiguration; }
                    catch (Exception) { currentConfig = null; }
                    if (currentConfig == null)
                    {
                        MessageBox.Show("Cannot perform check - no valid configuration selected", "Cppcheck error");
                        return;
                    }

                    //dynamic project = document.ProjectItem.ContainingProject.Object;
                    Project project = document.ProjectItem.ContainingProject;
                    SourceFile sourceForAnalysis = await createSourceFileAsync(document.ProjectItem);
                    if (sourceForAnalysis == null)
                    {
                        return;
                    }

                    if (!Settings.Default.CheckSavedFilesHasValue)
                    {
                        askCheckSavedFiles();

                        if (!Settings.Default.CheckSavedFiles)
                        {
                            return;
                        }
                    }

                    MainToolWindow.Instance.showIfWindowNotCreated();
                    MainToolWindow.Instance.ContentsType = ICodeAnalyzer.AnalysisType.DocumentSavedAnalysis;
                    runSavedFileAnalysis(sourceForAnalysis, currentConfig);
                }
                catch (Exception ex)
                {
                    if (_outputPane != null)
                    {
                        _outputPane.Clear();
                        _ = AddTextToOutputWindowAsync("Exception occurred in cppcheck add-in: " + ex.Message);
                    }
                    DebugTracer.Trace(ex);
                }
            });
        }
예제 #2
0
#pragma warning restore CA1051 // Do not declare visible instance fields

        public JoinableTaskHelper(JoinableTaskContext context)
        {
            this.Context    = context ?? throw new ArgumentNullException(nameof(context));
            this.Collection = context.CreateCollection();
            this.Factory    = context.CreateFactory(this.Collection);
        }
예제 #3
0
#pragma warning disable VSTHRD100 // Avoid async void methods
        /// <summary>
        ///     When switching between windows
        /// </summary>
        /// <param name="windowActivated"></param>
        /// <param name="lastWindow"></param>
        private async void OnWindowSwitch(Window windowActivated, Window lastWindow)
#pragma warning restore VSTHRD100 // Avoid async void methods
        {
            try {
                await JoinableTaskFactory.SwitchToMainThreadAsync(DisposalToken);

                // Get Extension
                string ext = "";

                if (windowActivated.Document != null)
                {
                    ext = Path.GetExtension(windowActivated.Document.FullName);
                }

                // Update the RichPresence Images based on config.
                DiscordController.Presence = Settings.IsLanguageImageLarge
                    ? new DiscordRPC.RichPresence {
                    largeImageKey  = _languages.ContainsKey(ext) ? _languages[ext] : "visualstudio",
                    largeImageText = _languages.ContainsKey(ext) ? _languages[ext] : "",
                    smallImageKey  = "visualstudio",
                    smallImageText = "Visual Studio 2019"
                }
                    : new DiscordRPC.RichPresence {
                    largeImageKey  = "visualstudio",
                    largeImageText = "Visual Studio 2019",
                    smallImageKey  = _languages.ContainsKey(ext) ? _languages[ext] : "visualstudio",
                    smallImageText = _languages.ContainsKey(ext) ? _languages[ext] : ""
                };

                // Add things to the presence based on config.
                if (Settings.IsFileNameShown && windowActivated.Document != null)
                {
                    DiscordController.Presence.details = Path.GetFileName(GetExactPathName(windowActivated.Document.FullName));
                }

                if (Settings.IsSolutionNameShown && _dte.Solution != null)
                {
                    DiscordController.Presence.state = "Developing " + Path.GetFileNameWithoutExtension(_dte.Solution.FileName);
                }

                // Initialize timestamp
                if (Settings.IsTimestampShown && !InitializedTimestamp)
                {
                    DiscordController.Presence.startTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                    InitialTimestamp     = DiscordController.Presence.startTimestamp;
                    InitializedTimestamp = true;
                }

                // Reset it
                if (Settings.IsTimestampResetEnabled && InitializedTimestamp && Settings.IsTimestampShown)
                {
                    DiscordController.Presence.startTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
                }
                // Set it equal to the initial timestamp (To not reset)
                else if (Settings.IsTimestampShown && !Settings.IsTimestampResetEnabled)
                {
                    DiscordController.Presence.startTimestamp = InitialTimestamp;
                }

                if (Settings.IsPresenceEnabled)
                {
                    DiscordController.Initialize();
                    DiscordRPC.UpdatePresence(ref DiscordController.Presence);
                }
                else
                {
                    DiscordRPC.Shutdown();
                }
            }
            catch (Exception) {
                // ignored
            }
        }
예제 #4
0
        /// <summary>
        ///     Initialization of the package; this method is called right after the package is sited, so this is the place
        ///     where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering InitializeAsync() of: {0}", ToString()));
            await base.InitializeAsync(cancellationToken, progress);

            IDEBuildLogger.UserRegistryRoot = UserRegistryRoot;

            // Switching to main thread to use GetService RPC and cast to service interface (which may involve COM operations)
            // Note: most of our work is not supposed to be heavy, mostly registration of services and callbacks
            await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            solutionEventsListener = new SolutionEventsListener(this);
            solutionEventsListener.BeforeSolutionClosed           += solutionEventsListener_BeforeSolutionClosed;
            solutionEventsListener.AfterSolutionOpened            += solutionEventsListener_AfterSolutionOpened;
            solutionEventsListener.AfterActiveConfigurationChange += SolutionEventsListener_AfterActiveConfigurationChange;
            solutionEventsListener.StartupProjectChanged          += SolutionEventsListener_OnStartupProjectChanged;

            dte2 = GetGlobalService(typeof(SDTE)) as DTE2;

            // Register the C# language service
            // inspiration & credits: https://github.com/IInspectable/Nav.Language.Extensions/commit/08af3d897afac5a54975660fa03f4b629da405e1#diff-b73c0f368f242625f60cfad9cc11f2d5R88
            AddService(typeof(NShaderLanguageService), async(container, ct, type) =>
            {
                await JoinableTaskFactory.SwitchToMainThreadAsync(ct);
                errorListProvider = new ErrorListProvider(this)
                {
                    ProviderGuid = new Guid("ad1083c5-32ad-403d-af3d-32fee7abbdf1"),
                    ProviderName = "Stride Shading Language"
                };
                var langService = new NShaderLanguageService(errorListProvider);
                langService.SetSite(this);
                langService.InitializeColors();    // Make sure to initialize colors before registering!
                return(langService);
            }, true);

            // Add our command handlers for menu (commands must exist in the .vsct file)
            var mcs = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (null != mcs)
            {
                StrideCommands.ServiceProvider = this;
                StrideCommands.RegisterCommands(mcs);
            }

            // Register a timer to call our language service during
            // idle periods.
            var mgr = GetService(typeof(SOleComponentManager))
                      as IOleComponentManager;

            if (m_componentID == 0 && mgr != null)
            {
                OLECRINFO[] crinfo = new OLECRINFO[1];
                crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO));
                crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime |
                                   (uint)_OLECRF.olecrfNeedPeriodicIdleTime;
                crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal |
                                     (uint)_OLECADVF.olecadvfRedrawOff |
                                     (uint)_OLECADVF.olecadvfWarningsOff;
                crinfo[0].uIdleTimeInterval = 1000;
                int hr = mgr.FRegisterComponent(this, crinfo, out m_componentID);
            }

            // If there's already a solution loaded, process it
            var dte = (DTE)GetService(typeof(DTE));

            if (dte.Solution.IsOpen)
            {
                await InitializeCommandProxy();
            }

            // Go back to async thread
            await TaskScheduler.Default;
        }
예제 #5
0
        private async Task InitializeCommandsAsync()
        {
            try {
                using (Log.WithMetrics(nameof(InitializeCommandsAsync))) {
                    var userCommand = new UserCommand(_sessionService, _settingsManager);

                    _commands = new List <VsCommandBase> {
#if DEBUG
                        new WebViewDevToolsCommand(),
#endif
                        new AddCodemarkCommentCommand(_sessionService, PackageGuids.guidWebViewPackageCodeWindowContextMenuCmdSet),
                        new AddCodemarkIssueCommand(_sessionService, PackageGuids.guidWebViewPackageCodeWindowContextMenuCmdSet),
                        new AddCodemarkPermalinkCommand(_sessionService, PackageGuids.guidWebViewPackageCodeWindowContextMenuCmdSet),
                        new AddCodemarkPermalinkInstantCommand(_sessionService, PackageGuids.guidWebViewPackageCodeWindowContextMenuCmdSet),
                        new RequestCodeReviewCommand(_sessionService, PackageGuids.guidWebViewPackageCodeWindowContextMenuCmdSet),

                        new AddCodemarkCommentCommand(_sessionService, PackageGuids.guidWebViewPackageShortcutCmdSet),
                        new AddCodemarkIssueCommand(_sessionService, PackageGuids.guidWebViewPackageShortcutCmdSet),
                        new AddCodemarkPermalinkCommand(_sessionService, PackageGuids.guidWebViewPackageShortcutCmdSet),
                        new AddCodemarkPermalinkInstantCommand(_sessionService, PackageGuids.guidWebViewPackageShortcutCmdSet),
                        new RequestCodeReviewCommand(_sessionService, PackageGuids.guidWebViewPackageShortcutCmdSet),

                        new WebViewReloadCommand(_sessionService),
                        new WebViewToggleCommand(),
                        new AuthenticationCommand(_componentModel, _sessionService),
                        new StartWorkCommand(_sessionService),
                        userCommand
                    };
                    await JoinableTaskFactory.SwitchToMainThreadAsync();

                    await InfoBarProvider.InitializeAsync(this);

                    var menuCommandService = (IMenuCommandService)(await GetServiceAsync(typeof(IMenuCommandService)));
                    foreach (var command in _commands)
                    {
                        menuCommandService.AddCommand(command);
                    }

                    var eventAggregator = _componentModel.GetService <IEventAggregator>();
                    _disposables = new List <IDisposable> {
                        //when a user has logged in/out we alter the text of some of the commands
                        eventAggregator?.GetEvent <SessionReadyEvent>()
                        .ObserveOnApplicationDispatcher()
                        .Subscribe(_ => {
                            userCommand.Update();
                        }),
                        eventAggregator?.GetEvent <SessionLogoutEvent>()
                        .ObserveOnApplicationDispatcher()
                        .Subscribe(_ => {
                            userCommand.Update();
                        }),
                        eventAggregator?.GetEvent <LanguageServerDisconnectedEvent>()
                        .ObserveOnApplicationDispatcher()
                        .Subscribe(_ => {
                            userCommand.Update();
                        }),

                        //eventAggregator?.GetEvent<SessionDidStartSignInEvent>().Subscribe(_ => {
                        //	ThreadHelper.JoinableTaskFactory.Run(async delegate {
                        //		await JoinableTaskFactory.SwitchToMainThreadAsync(CancellationToken.None);
                        //	userCommand.Update();
                        //	});
                        //}),
                        //eventAggregator?.GetEvent<SessionDidFailSignInEvent>().Subscribe(_ => {
                        //	ThreadHelper.JoinableTaskFactory.Run(async delegate {
                        //		await JoinableTaskFactory.SwitchToMainThreadAsync(CancellationToken.None);
                        //	userCommand.Update();
                        //	});
                        //}),
                        //eventAggregator?.GetEvent<SessionDidStartSignOutEvent>().Subscribe(_ => {
                        //	ThreadHelper.JoinableTaskFactory.Run(async delegate {
                        //		await JoinableTaskFactory.SwitchToMainThreadAsync(CancellationToken.None);
                        //		userCommand.Update();
                        //	});
                        //})
                    };
                    if (_sessionService.IsAgentReady)
                    {
                        userCommand.Update();
                    }
                }
            }
            catch (Exception ex) {
                Log.Error(ex, nameof(InitializeCommandsAsync));
            }
        }
        /// <summary>
        ///     Initialization of the package; this method is called right after the package is sited.
        /// </summary>
        protected override async System.Threading.Tasks.Task InitializeAsync(
            CancellationToken cancellationToken,
            IProgress <ServiceProgressData> progress)
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            //Log needs the OptionsPage
            OptionsPage = (OptionsPage)GetDialogPage(typeof(OptionsPage));
            Instance    = this;

            //Log needs the dte object
            dte = GetGlobalService(typeof(DTE)) as DTE;
            if (dte == null)
            {
                //this log will only log with Debug.WriteLine, since we failed to get the DTE for some reason
                Log("Could not get DTE object. Will not initialize.");
                return;
            }

            //This is the earliest we can safely log (that will go the output window)
            //previous logs will be Debug.WriteLine only
            Log($"Entering {nameof(InitializeAsync)}");

            var isSlnLoaded = await IsSolutionLoadedAsync();

            if (isSlnLoaded)
            {
                //already loaded, so we need to handle it asap
                HandleSolutionOpen();
            }

            //it's recommended to keep refs to Events objects to avoid the GC eating them up
            //https://stackoverflow.com/a/32600629/2573470
            solutionEvents = dte.Events.SolutionEvents;
            if (solutionEvents == null)
            {
                Log("Could not get te.Events.SolutionEvents. Will not initialize.");
                return;
            }

            solutionEvents.Opened        += HandleSolutionOpen;
            solutionEvents.BeforeClosing += HandleSolutionClose;

            // Add our command handlers for menu (commands must exist in the .vsct file)
            Log("Adding tool menu handler.");
            var mcs = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (mcs != null)
            {
                // Create the command for the menu item.
                var menuCommandID = new CommandID(GuidList.guidLocalHistoryCmdSet, (int)PkgCmdIDList.cmdidLocalHistoryMenuItem);
                var menuItem      = new MenuCommand(ProjectItemContextMenuHandler, menuCommandID);
                mcs.AddCommand(menuItem);
                Log("Added context menu command.");

                // Create the command for the tool window
                var toolwndCommandID = new CommandID(GuidList.guidLocalHistoryCmdSet, (int)PkgCmdIDList.cmdidLocalHistoryWindow);
                var menuToolWin      = new MenuCommand(ToolWindowMenuItemHandler, toolwndCommandID);
                mcs.AddCommand(menuToolWin);
                Log("Added menu command.");
            }
            else
            {
                Log("Could not get IMenuCommandService. Tool menu will not work.");
            }

            ShowToolWindow(false, cancellationToken);
            dte.Events.DocumentEvents.DocumentOpened += HandleDocumentOpen;
        }
예제 #7
0
        // XSharpLanguageService _langService = null;
        #region Overridden Implementation
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            // Suspend walking until Solution is opened.
            base.SolutionListeners.Add(new ModelScannerEvents(this));
            await base.InitializeAsync(cancellationToken, progress);

            await JoinableTaskFactory.SwitchToMainThreadAsync();

            _uiThread = new UIThread();
            XSharpProjectPackage.instance      = this;
            XSharpModel.XSolution.OutputWindow = this;
            this.RegisterProjectFactory(new XSharpProjectFactory(this));
            this.settings = new XPackageSettings(this);
            validateVulcanEditors();
            this.RegisterDebuggerEvents();
            // Indicate how to open the different source files : SourceCode or Designer ??
            this.RegisterEditorFactory(new XSharpEditorFactory(this));
            this.RegisterProjectFactory(new XSharpWPFProjectFactory(this));

            // editors for the binaries
            base.RegisterEditorFactory(new VOFormEditorFactory(this));
            base.RegisterEditorFactory(new VOMenuEditorFactory(this));
            base.RegisterEditorFactory(new VODBServerEditorFactory(this));
            base.RegisterEditorFactory(new VOFieldSpecEditorFactory(this));
            XSharp.Project.XSharpMenuItems.Initialize(this);

            // Register a timer to call our language service during
            // idle periods.
            IOleComponentManager mgr = await GetServiceAsync(typeof(SOleComponentManager)) as IOleComponentManager;

            if (m_componentID == 0 && mgr != null)
            {
                OLECRINFO[] crinfo = new OLECRINFO[1];
                crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO));
                crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime |
                                   (uint)_OLECRF.olecrfNeedPeriodicIdleTime;
                crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal |
                                     (uint)_OLECADVF.olecadvfRedrawOff |
                                     (uint)_OLECADVF.olecadvfWarningsOff;
                crinfo[0].uIdleTimeInterval = 1000;
                int hr = mgr.FRegisterComponent(this, crinfo, out m_componentID);
            }
            // Initialize Custom Menu Items
            // register property changed event handler


            var shell = await this.GetServiceAsync(typeof(SVsShell)) as IVsShell;

            Assumes.Present(shell);

            shell.AdviseShellPropertyChanges(this, out shellCookie);
            //
            // ObjectBrowser : Add the LibraryManager service as a Service provided by that container
            IServiceContainer      container = this as IServiceContainer;
            ServiceCreatorCallback callback  = new ServiceCreatorCallback(CreateLibraryService);

            //
            container.AddService(typeof(IXSharpLibraryManager), callback, true);
            this._documentWatcher = new XSharpDocumentWatcher(this);

            _txtManager = await GetServiceAsync(typeof(SVsTextManager)) as IVsTextManager4;

            // determine version of VS
            object vers;

            shell.GetProperty((int)__VSSPROPID5.VSSPROPID_ReleaseVersion, out vers);

            VsVersion = vers.ToString();
        }
예제 #8
0
        public ConEmuSession Start([NotNull] ConEmuStartInfo startinfo, [NotNull] JoinableTaskFactory joinableTaskFactory,
                                   [NotNull] string conEmuStyle, string conEmuFontSize)
        {
            if (startinfo == null)
            {
                throw new ArgumentNullException(nameof(startinfo));
            }


            SetConsoleFontSize();

            SetConsoleStyle();

            // Close prev session if there is one
            _running?.CloseConsoleEmulator();
            if (_running != null)
            {
                throw new InvalidOperationException("Cannot start a new console process because another console emulator session has failed to close in due time.");
            }

            _autostartinfo = null;             // As we're starting, no more chance for an autostart
            if (!IsHandleCreated)
            {
                CreateHandle();
            }

            // Spawn session
            var session = new ConEmuSession(startinfo, new ConEmuSession.HostContext((void *)Handle, IsStatusbarVisible), joinableTaskFactory);

            _running = session;
            StateChanged?.Invoke(this, EventArgs.Empty);

            // Wait for its exit
            session.WaitForConsoleEmulatorCloseAsync().ContinueWith(scheduler: TaskScheduler.FromCurrentSynchronizationContext(), continuationAction: task =>
            {
                try
                {
                    _nLastExitCode = _running.GetConsoleProcessExitCode();
                }
                catch (Exception)
                {
                    // NOP
                }
                _running = null;
                Invalidate();
                StateChanged?.Invoke(this, EventArgs.Empty);
            }).Forget();

            return(session);

            void SetConsoleFontSize()
            {
                var startInfoBaseConfiguration = startinfo.BaseConfiguration;

                if (!string.IsNullOrWhiteSpace(conEmuFontSize))
                {
                    if (int.TryParse(conEmuFontSize, out var fontSize))
                    {
                        var nodeFontSize =
                            startInfoBaseConfiguration.SelectSingleNode("/key/key/key/value[@name='FontSize']");

                        if (nodeFontSize?.Attributes != null)
                        {
                            nodeFontSize.Attributes["data"].Value = fontSize.ToString("X8");
                        }
                    }
                }

                startinfo.BaseConfiguration = startInfoBaseConfiguration;
            }

            void SetConsoleStyle()
            {
                if (conEmuStyle != "Default")
                {
                    startinfo.ConsoleProcessExtraArgs = " -new_console:P:\"" + conEmuStyle + "\"";
                }
            }
        }
 public TestThreadingService()
 {
     JoinableTaskContext = new JoinableTaskContextNode(new JoinableTaskContext());
     JoinableTaskFactory = new JoinableTaskFactory(JoinableTaskContext.Context);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DispatcherJoinableTaskFactory"/> class.
 /// </summary>
 /// <param name="innerFactory">The underlying <see cref="JoinableTaskFactory"/> to use when scheduling.</param>
 /// <param name="dispatcher">The <see cref="Dispatcher"/> to use for scheduling work on the UI thread.</param>
 /// <param name="priority">The priority with which to schedule work on the UI thread.</param>
 internal DispatcherJoinableTaskFactory(JoinableTaskFactory innerFactory, Dispatcher dispatcher, DispatcherPriority priority)
     : base(innerFactory)
 {
     this.dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
     this.priority   = priority;
 }
        /// <summary>
        /// Gets a service registered as one type and used as a different type.
        /// </summary>
        /// <typeparam name="I">The type the service is used as (e.g. IVsService).</typeparam>
        /// <typeparam name="S">The type the service is registered as (e.g. SVsService).</typeparam>
        /// <returns>The service.</returns>
        public async Task <I> GetServiceAsync <S, I>()
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync();

            return((I) await GetServiceAsync(typeof(S)));
        }
예제 #12
0
 public PumpingJTF(JoinableTaskFactory joinableTaskFactory)
     : base(joinableTaskFactory)
 {
 }
예제 #13
0
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            // Switches to the UI thread in order to consume some services used in command initialization
            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));

            _dte = await GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE.DTE;

            if (_dte == null)
            {
                return;
            }

            _eventsHandlers = _dte.Events.DocumentEvents;
            _eventsHandlers.DocumentSaved += documentSaved;

            _commandEventsHandlers = _dte.Events.CommandEvents;
            _commandEventsHandlers.BeforeExecute += new _dispCommandEvents_BeforeExecuteEventHandler(CommandEvents_BeforeExecute);

            _outputPane = _dte.AddOutputWindowPane("cppcheck analysis output");

            AnalyzerCppcheck cppcheckAnalayzer = new AnalyzerCppcheck();

            cppcheckAnalayzer.ProgressUpdated += checkProgressUpdated;
            _analyzers.Add(cppcheckAnalayzer);

            if (String.IsNullOrEmpty(Properties.Settings.Default.DefaultArguments))
            {
                Properties.Settings.Default.DefaultArguments = CppcheckSettings.DefaultArguments;
            }

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (null != mcs)
            {
                // Create the command for the menu item.
                {
                    CommandID   menuCommandID = new CommandID(GuidList.guidCPPCheckPluginCmdSet, (int)PkgCmdIDList.cmdidCheckProjectCppcheck);
                    MenuCommand menuItem      = new MenuCommand(onCheckCurrentProjectRequested, menuCommandID);
                    mcs.AddCommand(menuItem);
                }

                {
                    // Create the command for the settings window
                    CommandID   settingsWndCmdId = new CommandID(GuidList.guidCPPCheckPluginCmdSet, (int)PkgCmdIDList.cmdidSettings);
                    MenuCommand menuSettings     = new MenuCommand(onSettingsWindowRequested, settingsWndCmdId);
                    mcs.AddCommand(menuSettings);
                }

                {
                    CommandID   stopCheckMenuCommandID = new CommandID(GuidList.guidCPPCheckPluginCmdSet, (int)PkgCmdIDList.cmdidStopCppcheck);
                    MenuCommand stopCheckMenuItem      = new MenuCommand(onStopCheckRequested, stopCheckMenuCommandID);
                    mcs.AddCommand(stopCheckMenuItem);
                }

                {
                    CommandID   selectionsMenuCommandID = new CommandID(GuidList.guidCPPCheckPluginCmdSet, (int)PkgCmdIDList.cmdidCheckMultiItemCppcheck);
                    MenuCommand selectionsMenuItem      = new MenuCommand(onCheckSelectionsRequested, selectionsMenuCommandID);
                    mcs.AddCommand(selectionsMenuItem);
                }

                {
                    CommandID   projectMenuCommandID = new CommandID(GuidList.guidCPPCheckPluginProjectCmdSet, (int)PkgCmdIDList.cmdidCheckProjectCppcheck1);
                    MenuCommand projectMenuItem      = new MenuCommand(onCheckCurrentProjectRequested, projectMenuCommandID);
                    mcs.AddCommand(projectMenuItem);
                }

                {
                    CommandID   projectsMenuCommandID = new CommandID(GuidList.guidCPPCheckPluginMultiProjectCmdSet, (int)PkgCmdIDList.cmdidCheckProjectsCppcheck);
                    MenuCommand projectsMenuItem      = new MenuCommand(onCheckAllProjectsRequested, projectsMenuCommandID);
                    mcs.AddCommand(projectsMenuItem);
                }

                {
                    CommandID   selectionsMenuCommandID = new CommandID(GuidList.guidCPPCheckPluginMultiItemProjectCmdSet, (int)PkgCmdIDList.cmdidCheckMultiItemCppcheck1);
                    MenuCommand selectionsMenuItem      = new MenuCommand(onCheckSelectionsRequested, selectionsMenuCommandID);
                    mcs.AddCommand(selectionsMenuItem);
                }
            }

            // Creating the tool window
            FindToolWindow(typeof(MainToolWindow), 0, true);
        }
        private async Task checkProjectsAsync(List <Project> projects)
        {
            Debug.Assert(projects.Any());
            setMenuState(true);

            List <SourceFilesWithConfiguration> allConfiguredFiles = new List <SourceFilesWithConfiguration>();

            foreach (var project in projects)
            {
                await JoinableTaskFactory.SwitchToMainThreadAsync();

                Configuration config = await getConfigurationAsync(project);

                if (config == null)
                {
                    MessageBox.Show("No valid configuration in project " + project.Name);
                    continue;
                }

                SourceFilesWithConfiguration sourceFiles = new SourceFilesWithConfiguration();
                sourceFiles.Configuration = config;

                foreach (ProjectItem projectItem in project.ProjectItems)
                {
                    await scanProjectItemForSourceFilesAsync(projectItem, sourceFiles, config, project);
                }

                // Although we're using the same base configuration, it's possible for each file to override that.
                // Group files into separate configs based on actual parameters. We'll be iterating in reverse order so
                // reverse the list first to keep the final order the same.
                List <SourceFile> allSourceFiles = sourceFiles.Files.ToList();
                allSourceFiles.Reverse();

                while (allSourceFiles.Any())
                {
                    SourceFilesWithConfiguration newConfig = new SourceFilesWithConfiguration();
                    newConfig.Configuration = config;

                    SourceFile templateFile = allSourceFiles.Last();
                    newConfig.addOrUpdateFile(templateFile);
                    allSourceFiles.RemoveAt(allSourceFiles.Count - 1);

                    for (int i = allSourceFiles.Count - 1; i >= 0; i--)
                    {
                        SourceFile otherFile = allSourceFiles[i];

                        if (otherFile.Macros.All(templateFile.Macros.Contains) && templateFile.Macros.All(otherFile.Macros.Contains) &&
                            otherFile.MacrosToUndefine.All(templateFile.MacrosToUndefine.Contains) && templateFile.MacrosToUndefine.All(otherFile.MacrosToUndefine.Contains) &&
                            otherFile.IncludePaths.All(templateFile.IncludePaths.Contains) && templateFile.IncludePaths.All(otherFile.IncludePaths.Contains) &&
                            otherFile.ProjectName == templateFile.ProjectName
                            )
                        {
                            newConfig.addOrUpdateFile(otherFile);
                            allSourceFiles.RemoveAt(i);
                        }
                    }

                    if (newConfig.Any())
                    {
                        allConfiguredFiles.Add(newConfig);
                    }
                }
            }

            _ = JoinableTaskFactory.RunAsync(async() => {
                await JoinableTaskFactory.SwitchToMainThreadAsync();

                MainToolWindow.Instance.ContentsType = ICodeAnalyzer.AnalysisType.ProjectAnalysis;
                MainToolWindow.Instance.showIfWindowNotCreated();
            });

            scanProgressUpdated(-1);
            runAnalysis(allConfiguredFiles, false);
        }
예제 #15
0
        /// <summary>
        /// Initializes the package right after it's been "sited" into the fully-initialized Visual Studio IDE.
        /// </summary>
        protected override async System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            Logging.WriteLine("Initializing UnrealVS extension...");

            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            // Grab the MenuCommandService
            MenuCommandService = await GetServiceAsync(typeof(IMenuCommandService)) as OleMenuCommandService;

            // Get access to Visual Studio's DTE object.  This object has various hooks into the Visual Studio
            // shell that are useful for writing extensions.
            DTE = await GetServiceAsync(typeof(DTE)) as DTE;

            Logging.WriteLine("DTE version " + DTE.Version);

            // Get selection manager and register to receive events
            SelectionManager =
                await GetServiceAsync(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;

            SelectionManager.AdviseSelectionEvents(this, out SelectionEventsHandle);

            // Get solution and register to receive events
            SolutionManager = await GetServiceAsync(typeof(SVsSolution)) as IVsSolution2;

            UpdateUnrealLoadedStatus();
            SolutionManager.AdviseSolutionEvents(this, out SolutionEventsHandle);

            // Grab the solution build manager.  We need this in order to change certain things about the Visual
            // Studio environment, like what the active startup project is
            // Get solution build manager
            SolutionBuildManager =
                await GetServiceAsync(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager2;

            SolutionBuildManager.AdviseUpdateSolutionEvents(this, out UpdateSolutionEventsHandle);

            // Create our command-line editor
            CommandLineEditor.Initialize();

            // Create our startup project selector
            StartupProjectSelector = new StartupProjectSelector();

            // Create 'BuildStartupProject' instance
            BuildStartupProject = new BuildStartupProject();

            // Create 'CompileSingleFile' instance
            CompileSingleFile = new CompileSingleFile();

            // Create 'GenerateProjectFiles' tools
            GenerateProjectFiles = new GenerateProjectFiles();

            // Create Batch Builder tools
            BatchBuilder.Initialize();

            // Create the project menu quick builder
            QuickBuilder = new QuickBuild();

            // Call parent implementation
            base.Initialize();

            if (DTE.Solution.IsOpen)
            {
                StartTicker();
            }
        }
        public static async Task ExecuteWithinLockAsync(this SemaphoreSlim semaphore, JoinableTaskCollection collection, JoinableTaskFactory factory, Func <Task> task, CancellationToken cancellationToken = default)
        {
            // Join the caller to our collection, so that if the lock is already held by another task that needs UI
            // thread access we don't deadlock if we're also being waited on by the UI thread. For example, when CPS
            // is draining critical tasks and is waiting us.
            using (collection.Join())
            {
                await semaphore.WaitAsync(cancellationToken);

                using (new SemaphoreDisposer(semaphore))
                {
                    // We do an inner JoinableTaskFactory.RunAsync here to workaround
                    // https://github.com/Microsoft/vs-threading/issues/132
                    JoinableTask joinableTask = factory.RunAsync(task);

                    await joinableTask.Task;
                }
            }
        }
 public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory)
 => _joinableTaskFactory = joinableTaskFactory;
예제 #18
0
 public AsyncTaskService(IPackageService packageService, IMessageService messageService, JoinableTaskFactory taskFactory)
 {
     _packageService = packageService;
     _messageService = messageService;
     _taskFactory    = taskFactory;
 }
예제 #19
0
        void ShowToolWindow <T>() where T : ToolWindowPane
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            JoinableTaskFactory.RunAsync(ShowToolWindowAsync <T>);
        }
예제 #20
0
        private async Task <PickMembersDialog> GetDialogAsync(CancellationToken cancellationToken)
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield : true, cancellationToken);

            return(Application.Current.Windows.OfType <PickMembersDialog>().Single());
        }
예제 #21
0
        /// <summary>
        /// Starts the session.
        /// Opens the emulator view in the control (HWND given in <paramref name="hostcontext" />) by starting the ConEmu child process and giving it that HWND; ConEmu then starts the child Console Process for the commandline given in <paramref name="startinfo" /> and makes it run in the console emulator window.
        /// </summary>
        /// <param name="startinfo">User-defined startup parameters for the console process.</param>
        /// <param name="hostcontext">Control-related parameters.</param>
        /// <param name="joinableTaskFactory">The <see cref="JoinableTaskFactory"/>.</param>
        public ConEmuSession([NotNull] ConEmuStartInfo startinfo, [NotNull] HostContext hostcontext, [NotNull] JoinableTaskFactory joinableTaskFactory)
        {
            if (startinfo == null)
            {
                throw new ArgumentNullException(nameof(startinfo));
            }
            if (hostcontext == null)
            {
                throw new ArgumentNullException(nameof(hostcontext));
            }
            if (joinableTaskFactory == null)
            {
                throw new ArgumentNullException(nameof(joinableTaskFactory));
            }
            if (string.IsNullOrEmpty(startinfo.ConsoleProcessCommandLine))
            {
                throw new InvalidOperationException($"Cannot start a new console process for command line “{startinfo.ConsoleProcessCommandLine}” because it's either NULL, or empty, or whitespace.");
            }

            _joinableTaskFactory = joinableTaskFactory;
            _startinfo           = startinfo;
            startinfo.MarkAsUsedUp();             // No more changes allowed in this copy

            // Directory for working files, +cleanup
            _dirTempWorkingFolder = Init_TempWorkingFolder();

            // Events wiring: make sure sinks pre-installed with start-info also get notified
            Init_WireEvents(startinfo);

            // Should feed ANSI log?
            if (startinfo.IsReadingAnsiStream)
            {
                _ansilog = Init_AnsiLog(startinfo);
            }

            // Cmdline
            CommandLineBuilder cmdl = Init_MakeConEmuCommandLine(startinfo, hostcontext, _ansilog, _dirTempWorkingFolder);

            // Start ConEmu
            // If it fails, lifetime will be terminated; from them on, termination will be bound to ConEmu process exit
            _process = Init_StartConEmu(startinfo, cmdl);

            // GuiMacro executor
            _guiMacroExecutor = new GuiMacroExecutor(startinfo.ConEmuConsoleServerExecutablePath);
            _lifetime.Add(() => ((IDisposable)_guiMacroExecutor).Dispose());

            // Monitor payload process
            Init_ConsoleProcessMonitoring();
        }
예제 #22
0
        private async Task <ChangeSignatureDialog> TryGetDialogAsync(CancellationToken cancellationToken)
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync(alwaysYield : true, cancellationToken);

            return(Application.Current.Windows.OfType <ChangeSignatureDialog>().SingleOrDefault());
        }
        public RazorLanguageService_IVsLanguageDebugInfoTest()
        {
            var joinableTaskContext = new JoinableTaskContextNode(new JoinableTaskContext());

            JoinableTaskFactory = new JoinableTaskFactory(joinableTaskContext.Context);
        }
 public SettingsMonitor(TSetting settings, JoinableTaskFactory joinableTaskFactory)
 {
     _joinableTaskFactory      = joinableTaskFactory;
     _settings                 = settings;
     _settings.SettingsSaving += OnSettingsSaving;
 }
예제 #25
0
 protected override System.Threading.Tasks.Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
 {
     JoinableTaskFactory.RunAsync(Init);
     return(System.Threading.Tasks.Task.CompletedTask);
 }
예제 #26
0
 public void ExecuteSynchronously(Func <Task> asyncAction)
 {
     JoinableTaskFactory.Run(asyncAction);
 }
 public DispatcherJoinableTaskFactory(JoinableTaskFactory innerFactory, Dispatcher dispatcher, DispatcherPriority priority)
     : base(innerFactory)
 {
     _dispatcher = dispatcher;
     _priority   = priority;
 }
예제 #28
0
 public T ExecuteSynchronously <T>(Func <Task <T> > asyncAction)
 {
     return(JoinableTaskFactory.Run(asyncAction));
 }
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress <ServiceProgressData> progress)
        {
            await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            await Command.InitializeAsync(this);
        }
예제 #30
0
 public TestProjectThreadingService(JoinableTaskFactory jtf)
 {
     JoinableTaskFactory = jtf;
 }