private IntPtr CreateCodeView(string documentMoniker, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI) { var codeWindowType = typeof(IVsCodeWindow); var riid = codeWindowType.GUID; var clsid = typeof(VsCodeWindowClass).GUID; var window = (IVsCodeWindow)this._package.CreateInstance(ref clsid, ref riid, codeWindowType); ErrorHandler.ThrowOnFailure(window.SetBuffer(textLines)); ErrorHandler.ThrowOnFailure(window.SetBaseEditorCaption(null)); ErrorHandler.ThrowOnFailure(window.GetEditorCaption(READONLYSTATUS.ROSTATUS_Unknown, out editorCaption)); var userData = textLines as IVsUserData; if (userData != null) { if (this._promptEncodingOnLoad) { var guid = VSConstants.VsTextBufferUserDataGuid.VsBufferEncodingPromptOnLoad_guid; userData.SetData(ref guid, (uint)1); } } InitializeLanguageService(textLines); cmdUI = VSConstants.GUID_TextEditorFactory; return(Marshal.GetIUnknownForObject(window)); }
public Reference AddProject(EnvDTE.Project project) { if (null == project) { return(null); } // Get the soulution. IVsSolution solution = container.ProjectMgr.Site.GetService(typeof(SVsSolution)) as IVsSolution; if (null == solution) { return(null); } // Get the hierarchy for this project. IVsHierarchy projectHierarchy; ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(project.UniqueName, out projectHierarchy)); // Create the selector data. VSCOMPONENTSELECTORDATA selector = new VSCOMPONENTSELECTORDATA(); selector.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project; // Get the project reference string. ErrorHandler.ThrowOnFailure(solution.GetProjrefOfProject(projectHierarchy, out selector.bstrProjRef)); selector.bstrTitle = project.Name; selector.bstrFile = System.IO.Path.GetDirectoryName(project.FullName); return(AddFromSelectorData(selector)); }
private static DTE GetDteFromRot(string monikerName) { Debug.Assert(!string.IsNullOrEmpty(monikerName)); IRunningObjectTable rot; IEnumMoniker monikerEnumerator; object dte = null; try { int result = NativeMethods.GetRunningObjectTable(0, out rot); if (result != NativeMethods.S_OK) { Marshal.ThrowExceptionForHR(result); } rot.EnumRunning(out monikerEnumerator); VsipErrorHandler.ThrowOnFailure(monikerEnumerator.Reset()); uint fetched = 0; IMoniker[] moniker = new IMoniker[1]; while (monikerEnumerator.Next(1, moniker, out fetched) == 0) { IBindCtx bindingContext; result = NativeMethods.CreateBindCtx(0, out bindingContext); if (result != NativeMethods.S_OK) { Marshal.ThrowExceptionForHR(result); } string name; try { moniker[0].GetDisplayName(bindingContext, null, out name); } catch (UnauthorizedAccessException) { // Some processes will throw an exception // when trying to access them. We will just // skip those. continue; } if (name == monikerName) { object returnObject; rot.GetObject(moniker[0], out returnObject); dte = (object)returnObject; break; } } } catch { return(null); } return((DTE)dte); }
public int EnumOriginalCodeBlocks(out IVsEnumCodeBlocks ppEnum) { IVsTextLines buffer; ErrorHandler.ThrowOnFailure(bufferCoordinator.GetSecondaryBuffer(out buffer)); ppEnum = new CodeBlocksEnumerator(buffer); return(VSConstants.S_OK); }
/// <summary> /// Ends the scope of the automation function. This function is also called by the /// Dispose method. /// </summary> public void ExitAutomation() { if (inAutomation) { ErrorHandler.ThrowOnFailure(extensibility.ExitAutomationFunction()); inAutomation = false; } }
/// <summary> /// Returns a RegistryKey object for the root of a given storage type. /// It is up to the caller to dispose the returned object. /// </summary> /// <param name="provider">The service provider to use to access the Visual Studio's services.</param> /// <param name="registryType">The type of registry storage to open.</param> /// <param name="writable">Flag to indicate is the key should be writable.</param> public static RegistryKey RegistryRoot(IServiceProvider provider, __VsLocalRegistryType registryType, bool writable) { if (null == provider) { throw new ArgumentNullException("provider"); } // The current implementation of the shell supports only RegType_UserSettings and // RegType_Configuration, so for any other values we have to return not implemented. if ((__VsLocalRegistryType.RegType_UserSettings != registryType) && (__VsLocalRegistryType.RegType_Configuration != registryType)) { throw new NotSupportedException(); } // Try to get the new ILocalRegistry4 interface that is able to handle the new // registry paths. ILocalRegistry4 localRegistry = provider.GetService(typeof(SLocalRegistry)) as ILocalRegistry4; if (null != localRegistry) { uint rootHandle; string rootPath; if (ErrorHandler.Succeeded(localRegistry.GetLocalRegistryRootEx((uint)registryType, out rootHandle, out rootPath))) { // Check if we have valid data. __VsLocalRegistryRootHandle handle = (__VsLocalRegistryRootHandle)rootHandle; if (!string.IsNullOrEmpty(rootPath) && (__VsLocalRegistryRootHandle.RegHandle_Invalid != handle)) { // Check if the root is inside HKLM or HKCU. Note that this does not depends only from // the registry type, but also from instance-specific data like the RANU flag. RegistryKey root = (__VsLocalRegistryRootHandle.RegHandle_LocalMachine == handle) ? Registry.LocalMachine : Registry.CurrentUser; return(root.OpenSubKey(rootPath, writable)); } } } // We are here if the usage of the new interface failed for same reason, so we have to fall back to // the ond way to access the registry. ILocalRegistry2 oldRegistry = provider.GetService(typeof(SLocalRegistry)) as ILocalRegistry2; if (null == oldRegistry) { // There is something wrong with this installation or this service provider. return(null); } string registryPath; NativeMethods.ThrowOnFailure(oldRegistry.GetLocalRegistryRoot(out registryPath)); if (string.IsNullOrEmpty(registryPath)) { return(null); } RegistryKey regRoot = (__VsLocalRegistryType.RegType_Configuration == registryType) ? Registry.LocalMachine : Registry.CurrentUser; return(regRoot.OpenSubKey(registryPath, writable)); }
/// <summary> /// Defines the beginning of the scope of an automation function. This constuctor /// calls EnterAutomationFunction to signal the Shell that the current function is /// changing the status of the automation objects. /// </summary> public AutomationScope(IServiceProvider provider) { Utilities.ArgumentNotNull("provider", provider); extensibility = provider.GetService(typeof(IVsExtensibility)) as IVsExtensibility3; Assumes.Present(extensibility); ErrorHandler.ThrowOnFailure(extensibility.EnterAutomationFunction()); inAutomation = true; }
/// <include file='doc\FlavoredProject.uex' path='docs/doc[@for="FlavoredProject.OnAggregationComplete"]/*' /> /// <devdoc> /// This is called when all object in aggregation have received InitializeForOuter calls. /// At this point the aggregation is complete and fully functional. /// </devdoc> protected virtual void OnAggregationComplete() { // This will subscribe to the IVsTrackProjectDocumentsEvents. // This is not required to flavor a project but makes it easier for derived class // to subscribe to these events. IVsTrackProjectDocuments2 trackDocuments = GetTrackProjectDocuments(); ErrorHandler.ThrowOnFailure(trackDocuments.AdviseTrackProjectDocumentsEvents(_documentsEventsSink, out cookie)); }
public int SetCaretPos(int iLine, int iColumn) { TextSpan original = new TextSpan(); original.iStartLine = original.iEndLine = iLine; original.iStartIndex = original.iEndIndex = iColumn; TextSpan[] converted = new TextSpan[1]; ErrorHandler.ThrowOnFailure(bufferCoordinator.MapSecondaryToPrimarySpan(original, converted)); return(intellisenseHost.SetContextCaretPos(converted[0].iStartLine, converted[0].iStartIndex)); }
private void Navigate(string url) { IVsWebBrowsingService webBrowsingService = this.GetService(typeof(SVsWebBrowsingService)) as IVsWebBrowsingService; if (webBrowsingService != null) { IVsWindowFrame frame; ErrorHandler.ThrowOnFailure(webBrowsingService.Navigate(url, 0, out frame)); } }
public NemerleContainedLanguage(IVsTextBufferCoordinator bufferCoordinator, NemerleIntellisenseProvider intellisenseProject, uint itemId, IVsHierarchy pHierarchy) { if (null == bufferCoordinator) { throw new ArgumentNullException("bufferCoordinator"); } if (null == intellisenseProject) { throw new ArgumentNullException("intellisenseProject"); } _hierarchy = pHierarchy; object projectItem = null; pHierarchy.GetProperty(itemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out projectItem); _projectItem = projectItem as EnvDTE.ProjectItem; EnvDTE.Property prop = _projectItem.Properties.Item("FullPath"); if (prop != null) { _filePath = prop.Value as string; } var project = _projectItem.ContainingProject as NemerleOAProject; if (project != null) { _projectInfo = ((NemerleProjectNode)project.Project).ProjectInfo; } _typeResolutionService = null; DynamicTypeService typeService = LanguageService.GetService(typeof(DynamicTypeService)) as DynamicTypeService; if (typeService != null) { _typeResolutionService = typeService.GetTypeResolutionService(this._hierarchy); } this.bufferCoordinator = bufferCoordinator; this.intellisenseProject = intellisenseProject; this.itemId = itemId; // Make sure that the secondary buffer uses the IronPython language service. IVsTextLines buffer; ErrorHandler.ThrowOnFailure(bufferCoordinator.GetSecondaryBuffer(out buffer)); Guid languageGuid; this.GetLanguageServiceID(out languageGuid); ErrorHandler.ThrowOnFailure(buffer.SetLanguageServiceID(ref languageGuid)); _documentClosingEventHandler = new _dispDocumentEvents_DocumentClosingEventHandler(OnDocumentClosing); }
// »щет в исходном файле все блоки, обрамленные прагмой #line N / #line default private void SearchForCodeBlocks(IVsTextLines buffer) { ErrorHandler.ThrowOnFailure(buffer.LockBufferEx((uint)BufferLockFlags.BLF_READ)); try { int totalLines; ErrorHandler.ThrowOnFailure(buffer.GetLineCount(out totalLines)); var state = ParseState.WaitForBlockStart; var blockSpan = new TextSpanAndCookie(); for (int line = 0; line < totalLines; ++line) { int lineLen; ErrorHandler.ThrowOnFailure(buffer.GetLengthOfLine(line, out lineLen)); string lineText; ErrorHandler.ThrowOnFailure(buffer.GetLineText(line, 0, line, lineLen, out lineText)); if (state == ParseState.WaitForBlockStart) { var match = _linePragmaRegex.Match(lineText); if (match.Success) { blockSpan.ulHTMLCookie = uint.Parse(match.Groups[1].Value, NumberStyles.Integer, CultureInfo.InvariantCulture); blockSpan.CodeSpan = new TextSpan(); blockSpan.CodeSpan.iStartLine = line + 1; blockSpan.CodeSpan.iStartIndex = 0; state = ParseState.WaitForBlockEnd; } } else { if (lineText.Trim().StartsWith("#line default", StringComparison.InvariantCultureIgnoreCase)) { blockSpan.CodeSpan.iEndLine = line - 1; buffer.GetLengthOfLine(blockSpan.CodeSpan.iEndLine, out blockSpan.CodeSpan.iEndIndex); blocks.Add(blockSpan); blockSpan = new TextSpanAndCookie(); state = ParseState.WaitForBlockStart; } } } } finally { // Make sure that the buffer is always unlocked when we exit this function. buffer.UnlockBufferEx((uint)BufferLockFlags.BLF_READ); } }
public static T LoadPackage <T>([NotNull] this IVsShell shell) where T : Package { Requires.NotNull(shell, nameof(shell)); Guid guid = typeof(T).GUID; IVsPackage package; ErrorHandler.ThrowOnFailure(shell.LoadPackage(ref guid, out package)); return((T)package); }
public static T LoadPackage <T>(this IVsShell shell) where T : Package { Contract.Requires <ArgumentNullException>(shell != null, "shell"); Guid guid = typeof(T).GUID; IVsPackage package; ErrorHandler.ThrowOnFailure(shell.LoadPackage(ref guid, out package)); return((T)package); }
/// <summary> /// Called by the shell when a node has been renamed from the GUI /// </summary> /// <param name="label">The name of the new label.</param> /// <returns>A success or failure value.</returns> public override int SetEditLabel(string label) { int result = this.DelegateSetPropertyToNested((int)__VSHPROPID.VSHPROPID_EditLabel, label); if (ErrorHandler.Succeeded(result)) { this.RenameNestedProjectInParentProject(label); } return(result); }
internal void SafeOperation(Action op) { try { op(); } catch (Exception ex) when(!ErrorHandler.IsCriticalException(ex)) { logger.WriteLine($"Daemon error: {ex.ToString()}"); } }
public int GetSelectedText(out string pbstrText) { TextSpan[] span = new TextSpan[1]; ErrorHandler.ThrowOnFailure(intellisenseHost.GetContextSelection(span)); TextSpan[] convertedSpan = new TextSpan[1]; ErrorHandler.ThrowOnFailure(bufferCoordinator.MapPrimaryToSecondarySpan(span[0], convertedSpan)); IVsTextLines buffer; ErrorHandler.ThrowOnFailure(bufferCoordinator.GetSecondaryBuffer(out buffer)); return(buffer.GetLineText(convertedSpan[0].iStartLine, convertedSpan[0].iStartIndex, convertedSpan[0].iEndLine, convertedSpan[0].iEndIndex, out pbstrText)); }
public void InsertRange(int start, IList <string> lines) { // If the set of lines is empty we can exit now if ((null == lines) || (lines.Count == 0)) { hasMerged = true; return; } if (start < 0) { throw new ArgumentOutOfRangeException("start"); } int insertLine = start; int insertIndex = 0; // Verify that the insertion point is inside the buffer. int totalLines = LineCount; if (insertLine > totalLines) { insertLine = totalLines; } // Create the text to add to the buffer. StringBuilder builder = new StringBuilder(); if ((insertLine == totalLines) && (totalLines > 0)) { insertLine = totalLines - 1; ErrorHandler.ThrowOnFailure(textBuffer.GetLengthOfLine(insertLine, out insertIndex)); builder.AppendLine(); } foreach (string line in lines) { builder.AppendLine(line); } // Lock the buffer before changing its content. ErrorHandler.ThrowOnFailure(textBuffer.LockBuffer()); try { // Get the text to insert and pin it so that we can pass it as pointer // to the buffer's functions. string text = builder.ToString(); GCHandle handle = GCHandle.Alloc(text, GCHandleType.Pinned); try { TextSpan[] span = new TextSpan[1]; ErrorHandler.ThrowOnFailure(textBuffer.ReplaceLines(insertLine, insertIndex, insertLine, insertIndex, handle.AddrOfPinnedObject(), text.Length, span)); hasMerged = true; } finally { // Free the memory. handle.Free(); } } finally { // Make sure that the buffer is unlocked also in case of exception. textBuffer.UnlockBuffer(); } }
/// <summary> /// Ends the scope of the automation function. This function is also called by the /// Dispose method. /// </summary> public void ExitAutomation() { if (inAutomation) { ThreadHelper.JoinableTaskFactory.Run(async delegate { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); ErrorHandler.ThrowOnFailure(extensibility.ExitAutomationFunction()); inAutomation = false; }); } }
/// <summary> /// Defines the beginning of the scope of an automation function. This constuctor /// calls EnterAutomationFunction to signal the Shell that the current function is /// changing the status of the automation objects. /// </summary> public AutomationScope(IServiceProvider provider) { Utilities.ArgumentNotNull("provider", provider); extensibility = provider.GetService(typeof(EnvDTE.IVsExtensibility)) as IVsExtensibility3; if (null == extensibility) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(extensibility.EnterAutomationFunction()); inAutomation = true; }
public MarkdownLanguageInfo(SVsServiceProvider serviceProvider) { _serviceProvider = serviceProvider; IVsTextManager2 textManager = (IVsTextManager2)serviceProvider.GetService(typeof(SVsTextManager)); LANGPREFERENCES2[] preferences = new LANGPREFERENCES2[1]; preferences[0].guidLang = typeof(MarkdownLanguageInfo).GUID; ErrorHandler.ThrowOnFailure(textManager.GetUserPreferences2(null, null, preferences, null)); _languagePreferences = CreateLanguagePreferences(preferences[0]); _languagePreferencesCookie = ((IConnectionPointContainer)textManager).Advise <LanguagePreferences, IVsTextManagerEvents2>(_languagePreferences); }
public int SetSelection(int iAnchorLine, int iAnchorCol, int iEndLine, int iEndCol) { TextSpan original = new TextSpan(); original.iStartLine = iAnchorLine; original.iStartIndex = iAnchorCol; original.iEndLine = iEndLine; original.iEndIndex = iEndCol; TextSpan[] converted = new TextSpan[1]; ErrorHandler.ThrowOnFailure(bufferCoordinator.MapSecondaryToPrimarySpan(original, converted)); return(intellisenseHost.SetContextSelection(converted[0].iStartLine, converted[0].iStartIndex, converted[0].iEndLine, converted[0].iEndIndex)); }
public int GetSelection(out int piAnchorLine, out int piAnchorCol, out int piEndLine, out int piEndCol) { TextSpan[] span = new TextSpan[1]; ErrorHandler.ThrowOnFailure(intellisenseHost.GetContextSelection(span)); TextSpan[] convertedSpan = new TextSpan[1]; ErrorHandler.ThrowOnFailure(bufferCoordinator.MapPrimaryToSecondarySpan(span[0], convertedSpan)); piAnchorLine = convertedSpan[0].iStartLine; piAnchorCol = convertedSpan[0].iStartIndex; piEndLine = convertedSpan[0].iEndLine; piEndCol = convertedSpan[0].iEndIndex; return(VSConstants.S_OK); }
private IntPtr FindDocDataFromRDT() { // Get a reference to the RDT. IVsRunningDocumentTable rdt = Package.GetGlobalService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (null == rdt) { return(IntPtr.Zero); } // Get the enumeration of the running documents. IEnumRunningDocuments documents; ErrorHandler.ThrowOnFailure(rdt.GetRunningDocumentsEnum(out documents)); IntPtr documentData = IntPtr.Zero; uint[] docCookie = new uint[1]; uint fetched; while ((VSConstants.S_OK == documents.Next(1, docCookie, out fetched)) && (1 == fetched)) { uint flags; uint editLocks; uint readLocks; string moniker; IVsHierarchy docHierarchy; uint docId; IntPtr docData = IntPtr.Zero; try { ErrorHandler.ThrowOnFailure( rdt.GetDocumentInfo(docCookie[0], out flags, out readLocks, out editLocks, out moniker, out docHierarchy, out docId, out docData)); // Check if this document is the one we are looking for. if ((docId == fileId) && (ownerHierarchy.Equals(docHierarchy))) { documentData = docData; docData = IntPtr.Zero; break; } } finally { if (IntPtr.Zero != docData) { Marshal.Release(docData); } } } return(documentData); }
private void Unadvise() { Debug.Assert(this.cookie.HasValue, "Already unadvised"); if (ErrorHandler.Succeeded(this.InfoBarUIElement.Unadvise(this.cookie.Value))) { this.cookie = null; } else { Debug.Fail("Failed in IVsInfoBarUIElement.Unadvise"); } }
private static bool TryGetInfoBarHost(IVsWindowFrame frame, out IVsInfoBarHost infoBarHost) { object infoBarHostObj; if (ErrorHandler.Failed(frame.GetProperty((int)__VSFPROPID7.VSFPROPID_InfoBarHost, out infoBarHostObj))) { infoBarHost = null; return(false); } infoBarHost = infoBarHostObj as IVsInfoBarHost; return(infoBarHost != null); }
public int GetColorizer(out IVsColorizer ppColorizer) { ppColorizer = null; if (null == LanguageService) { // We should always be able to get the language service. return(VSConstants.E_UNEXPECTED); } IVsTextLines buffer; ErrorHandler.ThrowOnFailure(bufferCoordinator.GetSecondaryBuffer(out buffer)); return(LanguageService.GetColorizer(buffer, out ppColorizer)); }
private void HandleDaemonReady(object sender, EventArgs e) { // Could be on the UI thread -> unhandled exceptions will crash VS try { MakeRequest(); } catch (Exception ex) when(!ErrorHandler.IsCriticalException(ex)) { // Squash non-critical exceptions Debug.WriteLine($"Error handling daemon ready notification: {ex.ToString()}"); } }
private IntPtr CreateCodeView(IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI) { Type codeWindowType = typeof(IVsCodeWindow); Guid riid = codeWindowType.GUID; Guid clsid = typeof(VsCodeWindowClass).GUID; IVsCodeWindow window = (IVsCodeWindow)_package.CreateInstance(ref clsid, ref riid, codeWindowType); ErrorHandler.ThrowOnFailure(window.SetBuffer(textLines)); ErrorHandler.ThrowOnFailure(window.SetBaseEditorCaption(null)); ErrorHandler.ThrowOnFailure(window.GetEditorCaption(READONLYSTATUS.ROSTATUS_Unknown, out editorCaption)); cmdUI = VSConstants.GUID_TextEditorFactory; return(Marshal.GetIUnknownForObject(window)); }
private static IVsWindowFrame GetToolWindowFrame(IVsUIShell shell, Guid toolwindowGuid) { Debug.Assert(shell != null); IVsWindowFrame frame; int hr = shell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fForceCreate, ref toolwindowGuid, out frame); if (ErrorHandler.Failed(hr) || frame == null) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.CannotFindToolWindow, toolwindowGuid), nameof(toolwindowGuid)); } return(frame); }