Beispiel #1
0
        public static bool TryGetHierarchy(string filePath, out IVsHierarchy vsHierarchy, out uint vsItemId)
        {
            bool result = true;

            vsHierarchy = null;
            vsItemId    = (uint)VSConstants.VSITEMID.Nil;

            IVsUIShellOpenDocument vsUIShellOpenDocument = ServiceProvider.GlobalProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;

            IOleServiceProvider serviceProviderUnused = null;
            int            docInProject = 0;
            IVsUIHierarchy uiHier       = null;


            int hr = vsUIShellOpenDocument.IsDocumentInAProject(filePath, out uiHier, out vsItemId, out serviceProviderUnused, out docInProject);

            if (ErrorHandler.Succeeded(hr) && uiHier != null)
            {
                vsHierarchy = uiHier as IVsHierarchy;
            }
            else
            {
                vsHierarchy = null;
                vsItemId    = (uint)VSConstants.VSITEMID.Nil;
                result      = false;
            }

            return(result);
        }
        public async Task <Uri> GetProjectPathAsync(Uri documentFilePath, CancellationToken cancellationToken)
        {
            if (documentFilePath == null)
            {
                throw new ArgumentNullException(nameof(documentFilePath));
            }

            _foregroundDispatcher.AssertBackgroundThread();

            await _joinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            if (_openDocumentShell == null)
            {
                _openDocumentShell = ServiceProvider.GlobalProvider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
            }

            var hostDocumentFilePath = _session.ConvertSharedUriToLocalPath(documentFilePath);
            var hr = _openDocumentShell.IsDocumentInAProject(hostDocumentFilePath, out var hierarchy, out _, out _, out _);

            if (ErrorHandler.Succeeded(hr) && hierarchy != null)
            {
                ErrorHandler.ThrowOnFailure(((IVsProject)hierarchy).GetMkDocument((uint)VSConstants.VSITEMID.Root, out var path), VSConstants.E_NOTIMPL);

                return(_session.ConvertLocalPathToSharedUri(path));
            }

            return(null);
        }
        /// <include file='doc\ShellDocumentManager.uex' path='docs/doc[@for="ShellDocumentManager.GetHierarchyForFile"]/*' />
        /// <devdoc>
        ///      Retrieves the VS hierarchy and itemid for a file that owns the given file.  This will return
        ///      null if no hierarchy owns the file.
        /// </devdoc>
        public static IVsHierarchy GetHierarchyForFile(IServiceProvider serviceProvider, string file, out int pItemID)
        {
            IVsUIShellOpenDocument openDoc = (IVsUIShellOpenDocument)serviceProvider.GetService(typeof(IVsUIShellOpenDocument));

            if (openDoc == null)
            {
                Debug.Fail("Shell does not support IVsUIShellOpenDocument?");
                throw new SystemException(SR.GetString(SR.ASSEMBLYSERVICEMissingService, typeof(IVsUIShellOpenDocument).Name));
            }

            IVsHierarchy[] hier = new IVsHierarchy[1];

            int[] ppItemId = new int[1];

            if (openDoc.IsDocumentInAProject(file, hier, ppItemId, null) == 0)
            {
                hier[0] = null;
            }

            pItemID = ppItemId[0];


            return(hier[0]);
        }
Beispiel #4
0
        internal void OutputMessage(string message)
        {
            m_buildOutputPane.OutputString(string.Format(CultureInfo.InvariantCulture, "{0}{1}", message, Environment.NewLine));

            // Check whether this message represents an error or a warning and push to task itemlist accordingly
            ErrorTask task     = null;
            string    fileName = null;

            Match match = null;

            foreach (Regex regex in m_messageRegexs)
            {
                match = regex.Match(message);
                if (match.Success)
                {
                    break;
                }
            }

            if (match != null && match.Success)
            {
                fileName = match.Groups["file"].Value;
                var lineNumber = int.Parse(match.Groups["linestart"].Value, CultureInfo.InvariantCulture);
                var colNumber  = int.Parse(match.Groups["columnstart"].Value, CultureInfo.InvariantCulture);

                var errOrWarning = match.Groups["level"].Value;
                var isAnError    = string.Equals(errOrWarning, "error", StringComparison.OrdinalIgnoreCase);
                if (isAnError)
                {
                    m_numErrors++;
                }

                task = new ErrorTask
                {
                    Document      = fileName,
                    Line          = lineNumber - 1,
                    Column        = colNumber - 1,
                    Text          = match.Groups["message"].Value,
                    Priority      = isAnError ? TaskPriority.High : TaskPriority.Normal,
                    ErrorCategory = isAnError ? TaskErrorCategory.Error : TaskErrorCategory.Warning,
                    Category      = TaskCategory.BuildCompile,
                };
            }
            else
            {
                // If the standard pattern is not followed for errors
                if (message.StartsWith("error ", StringComparison.OrdinalIgnoreCase) ||
                    message.StartsWith("error:", StringComparison.OrdinalIgnoreCase))
                {
                    task = new ErrorTask
                    {
                        Text          = message,
                        Priority      = TaskPriority.High,
                        ErrorCategory = TaskErrorCategory.Error,
                        Category      = TaskCategory.BuildCompile,
                    };
                }
            }

            // Add the task (if not null) to error list
            if (task != null)
            {
                if (!string.IsNullOrEmpty(fileName))
                {
                    // populating the project hierarchy to show the project name in the error list window
                    IVsUIHierarchy vsHierarchy;
                    uint           itemId;
                    Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider;
                    var docInProj = 0;

                    var docOpenResult = m_shellOpenDocument.IsDocumentInAProject(
                        fileName,
                        out vsHierarchy,
                        out itemId,
                        out serviceProvider,
                        out docInProj);
                    if (docInProj != 0 && docOpenResult == VSConstants.S_OK)
                    {
                        task.HierarchyItem = vsHierarchy;
                    }
                }

                // Adding navigation handler
                task.Navigate += NavigateTo;
                m_errorListProvider.Tasks.Add(task);
            }
        }
        public void VsTextViewCreated(IVsTextView text_view)
        {
            if (ALanguageUtility.s_service_provider == null)
            {
                ALanguageUtility.s_service_provider = m_service_provider;
            }

            if (m_factory == null)
            {
                return;
            }

            SaveAdapterFactory();
            m_factory.Init(m_service_provider, m_adapters_factory);

            // 获取系统单例,用于打开文件
            if (m_open_document == null)
            {
                m_open_document = m_service_provider.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;
            }

            // 获取视窗
            IWpfTextView view = m_adapters_factory.GetWpfTextView(text_view);

            if (view == null)
            {
                return;
            }

            // 添加关闭监听
            view.Closed += OnViewClosed;

            // 创建ABnf
            if (m_abnf == null)
            {
                m_abnf = ALanguageUtility.CreateABnf(m_factory);
            }
            if (m_abnf == null)
            {
                return;
            }
            if (m_abnf_ui == null)
            {
                m_abnf_ui = ALanguageUtility.CreateABnf(m_factory);
            }
            if (m_abnf_ui == null)
            {
                return;
            }

            // 获取高亮tag
            if (m_highlight_tag == null)
            {
                m_highlight_tag = m_factory.CreateTextMarkerTag();
            }

            if (m_highlight_tag != null)
            {
                view.Properties.AddProperty(nameof(TextMarkerTag), m_highlight_tag);
            }

            // 获取全路径
            string full_path = ALanguageUtility.GetFilePath(view);

            if (full_path == null)
            {
                return;
            }

            var solution = m_factory.GetSolution();

            if (solution == null)
            {
                return;
            }

            var server = solution.GetServer();

            if (server != null)
            {
                view.Properties.AddProperty(nameof(ALanguageServer), server);
                view.TextBuffer.Properties.AddProperty(nameof(ALanguageServer), server);
            }
            view.Properties.AddProperty(nameof(IVsTextView), text_view);

            // 获取所在的工程
            m_open_document.IsDocumentInAProject(full_path, out IVsUIHierarchy project, out uint item_id, out Microsoft.VisualStudio.OLE.Interop.IServiceProvider _ppSP, out int _pDocInProj);
            UIProjectInfo project_info = null;

            if (project != null)
            {
                solution.GetProjects().TryGetValue(project, out project_info);
            }

            // 创建信息,并作为属性给view
            var info = new UIViewItem(m_abnf, m_abnf_ui, view, m_service_provider, m_adapters_factory, project_info, item_id, full_path, m_factory, m_factory.GetLineCommentBegin());

            view.Properties.AddProperty(nameof(UIViewItem), info);
            view.TextBuffer.Properties.AddProperty(nameof(UIViewItem), info);

            // 提前添加各种source
            {
                if (!view.TextBuffer.Properties.TryGetProperty(nameof(ALanguageCompletionSource), out ALanguageCompletionSource source))
                {
                    source = new ALanguageCompletionSource(view.TextBuffer);
                    view.TextBuffer.Properties.AddProperty(nameof(ALanguageCompletionSource), source);
                }
            }
            {
                if (!view.TextBuffer.Properties.TryGetProperty(nameof(ALanguageQuickInfoSource), out ALanguageQuickInfoSource source))
                {
                    source = new ALanguageQuickInfoSource(view.TextBuffer);
                    view.TextBuffer.Properties.AddProperty(nameof(ALanguageQuickInfoSource), source);
                }
            }
            {
                if (!view.TextBuffer.Properties.TryGetProperty(nameof(ALanguageSignatureHelpSource), out ALanguageSignatureHelpSource source))
                {
                    source = new ALanguageSignatureHelpSource(view.TextBuffer);
                    view.TextBuffer.Properties.AddProperty(nameof(ALanguageSignatureHelpSource), source);
                }
            }

            {
                if (!view.Properties.TryGetProperty(nameof(ALanguageErrorTagger), out ALanguageErrorTagger tagger))
                {
                    tagger = new ALanguageErrorTagger(view);
                    view.Properties.AddProperty(nameof(ALanguageErrorTagger), tagger);
                }
            }

            {
                if (!view.Properties.TryGetProperty(nameof(ALanguageReferenceTagger), out ALanguageReferenceTagger tagger))
                {
                    tagger = new ALanguageReferenceTagger(view);
                    view.Properties.AddProperty(nameof(ALanguageReferenceTagger), tagger);
                }
            }

            {
                if (!view.Properties.TryGetProperty(nameof(ALanguageHighlightWordTagger), out ALanguageHighlightWordTagger tagger))
                {
                    tagger = new ALanguageHighlightWordTagger(view);
                    view.Properties.AddProperty(nameof(ALanguageHighlightWordTagger), tagger);
                }
            }

            // 添加命令
            {
                ALanguageGotoDefinitionCommand filter = new ALanguageGotoDefinitionCommand(view);
                text_view.AddCommandFilter(filter, out IOleCommandTarget next);
                filter.Next = next;
                view.Properties.AddProperty(nameof(ALanguageGotoDefinitionCommand) + "Target", next);
            }

            {
                ALanguageCompletionCommand filter = new ALanguageCompletionCommand(view, m_completion_broker);
                text_view.AddCommandFilter(filter, out IOleCommandTarget next);
                filter.Next = next;
                view.Properties.AddProperty(nameof(ALanguageCompletionCommand) + "Target", next);
                view.Properties.AddProperty(nameof(ALanguageCompletionCommand), filter);
            }
        }
Beispiel #6
0
        // --------------------------------------------------------------
        // Editor control
        // --------------------------------------------------------------

        private void ShowSource(string emitter, string path, int line_no)
        {
            IVsUIShellOpenDocument od = (IVsUIShellOpenDocument)MsVsShell.Package.GetGlobalService(typeof(SVsUIShellOpenDocument));

            // not clear why lookup needs a string array; documentation does not mention returning
            // more than one path
            uint search_strategy = (uint)__VSRELPATHSEARCHFLAGS.RPS_UseAllSearchStrategies;

            String[] found_abs_paths = new String[1];
            int      res             = od.SearchProjectsForRelativePath(search_strategy, path, found_abs_paths);

            // if the whole path wasn't found, retry with just the filename
            String chosen_abs_path;

            if (res != VsConstants.S_OK)
            {
                int last_elem_pos = path.LastIndexOf('\\');
                if (last_elem_pos >= 0)
                {
                    string last_elem = path.Substring(last_elem_pos + 1);
                    res = od.SearchProjectsForRelativePath(search_strategy, last_elem, found_abs_paths);
                }
            }

            if (res == VsConstants.S_OK)
            {
                chosen_abs_path = found_abs_paths[0];
            }
            else
            {
                OutputString(System.String.Format("Unable to find source code in any project: path:'{0}' line:{1}", path, line_no));
                return;
            }

            // fetch a hierarchy for the absolute path
            IVsUIHierarchy hierarchy;
            UInt32         item_id;

            Microsoft.VisualStudio.OLE.Interop.IServiceProvider provider;
            Int32 in_proj;

            res = od.IsDocumentInAProject(chosen_abs_path, out hierarchy, out item_id, out provider, out in_proj);

            if (res != VsConstants.S_OK)
            {
                OutputString(System.String.Format("Unable to find project for source code: emitter: '{0}'", emitter));
                return;
            }

            if (in_proj == 0)
            {
                OutputString(System.String.Format("Unable to find source code in project: emitter: '{0}'", emitter));
                return;
            }

            // convert the hierarchy to a project, and open & show the source code document
            IVsProject     project = (IVsProject)hierarchy;
            IntPtr         DOCDATAEXISTING_UNKNOWN = (IntPtr)(int)-1;
            Guid           logical_view            = new Guid(LogicalViewID.Code);
            IVsWindowFrame frame;

            res = project.OpenItem(item_id, logical_view, DOCDATAEXISTING_UNKNOWN, out frame);

            if (res != VsConstants.S_OK)
            {
                OutputString(System.String.Format("Unable to open editor for source code: emitter: '{0}'", emitter));
                return;
            }

            frame.Show();

            // move the cursor to the correct line in the editor
            IVsTextView text_view = Microsoft.VisualStudio.Shell.VsShellUtilities.GetTextView(frame);

            if (text_view == null)
            {
                OutputString(System.String.Format("Unable to access editor for source code: emitter: '{0}'", emitter));
                return;
            }

            line_no = line_no - 1;
            res     = text_view.SetCaretPos(line_no, 0);
            if (res != VsConstants.S_OK)
            {
                OutputString(System.String.Format("Unable to set cursor to source code: emitter: '{0}'", emitter));
                return;
            }

            // and finally, centre the view on the source code line - ignore errors, it doesn't
            // matter that much
            text_view.CenterLines(line_no, 1);
        }