private async Task OutputMessageAsync(string message, bool clear = false) { await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); IVsOutputWindowPane outputPane = null; IVsWindowFrame windowFrame = null; var outputWindow = ServiceProvider.GlobalProvider.GetService(typeof(SVsOutputWindow)) as IVsOutputWindow; if (outputWindow != null && ErrorHandler.Failed(outputWindow.GetPane(windowGuid, out outputPane))) { outputWindow.CreatePane(windowGuid, "Meadow Device Explorer", 1, 1); outputWindow.GetPane(windowGuid, out outputPane); } var vsUiShell = ServiceProvider.GlobalProvider.GetService(typeof(SVsUIShell)) as IVsUIShell; uint flags = (uint)__VSFINDTOOLWIN.FTW_fForceCreate; vsUiShell?.FindToolWindow(flags, VSConstants.StandardToolWindows.Output, out windowFrame); if (clear) { outputPane?.Clear(); } windowFrame?.Show(); outputPane?.Activate(); outputPane?.OutputString($"[{DateTime.Now.ToLocalTime()}] {message}" + Environment.NewLine); }
public override int OpenWithSpecific(uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) { frame = null; Debug.Assert(editorType == VSConstants.GUID_ProjectDesignerEditor, "Cannot open project designer with guid " + editorType.ToString()); if (this.Node == null || this.Node.ProjectMgr == null || this.Node.ProjectMgr.IsClosed) { return VSConstants.E_FAIL; } IVsUIShellOpenDocument uiShellOpenDocument = this.Node.ProjectMgr.Site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IOleServiceProvider serviceProvider = this.Node.ProjectMgr.Site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider; if (serviceProvider != null && uiShellOpenDocument != null) { string fullPath = this.GetFullPathForDocument(); string caption = this.GetOwnerCaption(); IVsUIHierarchy parentHierarchy = this.Node.ProjectMgr.GetProperty((int)__VSHPROPID.VSHPROPID_ParentHierarchy) as IVsUIHierarchy; IntPtr parentHierarchyItemId = (IntPtr)this.Node.ProjectMgr.GetProperty((int)__VSHPROPID.VSHPROPID_ParentHierarchyItemid); ErrorHandler.ThrowOnFailure(uiShellOpenDocument.OpenSpecificEditor(editorFlags, fullPath, ref editorType, physicalView, ref logicalView, caption, parentHierarchy, (uint)(parentHierarchyItemId.ToInt32()), docDataExisting, serviceProvider, out frame)); if (frame != null) { if (windowFrameAction == WindowFrameShowAction.Show) { ErrorHandler.ThrowOnFailure(frame.Show()); } } } return VSConstants.S_OK; }
private void ActivateOutputWindow() { var uiShell = ServiceLocator.GetGlobalService <SVsUIShell, IVsUIShell>(); if (uiShell != null) { IVsWindowFrame toolWindow = null; uiShell.FindToolWindow(0, ref GuidList.guidVsWindowKindOutput, out toolWindow); toolWindow?.Show(); } }
public static bool NavigateToFrame(IVsWindowFrame frame, int start, int length) { int hr = frame.Show(); if (ErrorHandler.Succeeded(hr)) { IVsTextView vsTextView = VsShellUtilities.GetTextView(frame); if (vsTextView != null) { return NavigateToTextView(vsTextView, start, length); } } return false; }
public void Activate() { IVsWindowFrame toolWindow = null; _vsUiShell.FindToolWindow(0, ref GuidList.guidVsWindowKindOutput, out toolWindow); toolWindow?.Show(); VsOutputWindowPane.Activate(); }
public void Execute(object parameter) { IVsWindowFrame toolWindow = null; _vsUiShell.FindToolWindow(0, ref GuidList.guidVsWindowKindOutput, out toolWindow); toolWindow?.Show(); IVsOutputWindowPane pane; if (_vsOutputWindow.GetPane(ref NuGetConsole.Implementation.GuidList.guidNuGetOutputWindowPaneGuid, out pane) == VSConstants.S_OK) { pane.Activate(); } }
public bool GetAlreadyOpenedDocument(string path, out IVsWindowFrame windowFrame) { Validate.IsNotNull(path, nameof(path)); IVsUIHierarchy hierarchy; uint itemId; // DevDiv 248655: Calling OpenFile on a previewed document will promote it. // Do not promote unnecessarily. Simply activate the window if it exists. if (!VsShellUtilities.IsDocumentOpen(this.singletons.ServiceProvider, path, VSConstants.LOGVIEWID.Code_guid, out hierarchy, out itemId, out windowFrame) || windowFrame == null) { return false; } return ErrorHandler.Succeeded(windowFrame.Show()); }
public void Execute(object parameter) { NuGetUIThreadHelper.JoinableTaskFactory.Run(async() => { await NuGetUIThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync(); IVsWindowFrame toolWindow = null; _vsUiShell.Value.FindToolWindow(0, ref GuidList.guidVsWindowKindOutput, out toolWindow); toolWindow?.Show(); IVsOutputWindowPane pane; if (_vsOutputWindow.Value.GetPane(ref NuGetConsole.GuidList.guidNuGetOutputWindowPaneGuid, out pane) == VSConstants.S_OK) { pane.Activate(); } }); }
// Initialization Logic /// <summary> /// Called by anything attempting to open a project file editor window, usually by a command. This will show the window frame, creating it if /// has not already been created. /// </summary> public async Task OpenEditorAsync() { // We access _windowFrame inside the lock, so we must be on the UI thread in that case await _threadingService.SwitchToUIThread(); lock (_lock) { // If the editor is already open, just show it and return if (_currentState != EditorState.NoEditor) { // If we're initializing, _windowFrame might be null. In that case, when the initialization code // is done, it'll take care of showing the frame. _windowFrame?.Show(); return; } _currentState = EditorState.Initializing; } // Set up the buffer manager, which will create the temp file. Nothing else in OpenEditor requires the UI thread (tasks aquire it as needed) // so we don't need to resume on the same thread. _textBufferManager = _textBufferManagerFactory.CreateExport().Value; await _textBufferManager.InitializeBufferAsync().ConfigureAwait(false); // Open and show the editor frame. _windowFrame = await _shellHelper.OpenDocumentWithSpecificEditorAsync(_serviceProvider, _textBufferManager.FilePath, XmlFactoryGuid, Guid.Empty).ConfigureAwait(false); // Set up the save listener _textBufferStateListener = _textBufferListenerFactory.CreateExport().Value; await _textBufferStateListener.InitializeListenerAsync(_textBufferManager.FilePath).ConfigureAwait(false); // Set up the listener that will check for when the frame is closed. _frameEventsListener = _frameEventsListenerFactory.CreateExport().Value; await _frameEventsListener.InitializeEventsAsync(_windowFrame).ConfigureAwait(false); // Set up the project file watcher, so changes to the project file are detected and the buffer is updated. _projectFileModelWatcher = _projectFileWatcherFactory.CreateExport().Value; _projectFileModelWatcher.InitializeModelWatcher(); // Finally, move to the editor open state lock (_lock) { _currentState = EditorState.EditorOpen; } }
/// <include file='doc\Utilities.uex' path='docs/doc[@for="VsShell.OpenDocumentWithSpecificEditor1"]/*' /> public static void OpenDocumentWithSpecificEditor(IServiceProvider provider, string fullPath, Guid editorType, Guid logicalView, out IVsUIHierarchy hierarchy, out uint itemID, out IVsWindowFrame windowFrame) { windowFrame = null; itemID = NativeMethods.VSITEMID_NIL; hierarchy = null; //open document IVsUIShellOpenDocument shellOpenDoc = provider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; RunningDocumentTable pRDT = new RunningDocumentTable(provider); string physicalView = null; if (shellOpenDoc != null) { NativeMethods.ThrowOnFailure(shellOpenDoc.MapLogicalView(ref editorType, ref logicalView, out physicalView)); // See if the requested editor is already open with the requested view. uint docCookie; IVsHierarchy ppIVsHierarchy; object docData = pRDT.FindDocument(fullPath, out ppIVsHierarchy, out itemID, out docCookie); if (docData != null) { int pfOpen; uint flags = (uint)__VSIDOFLAGS.IDO_ActivateIfOpen; int hr = shellOpenDoc.IsSpecificDocumentViewOpen((IVsUIHierarchy)ppIVsHierarchy, itemID, fullPath, ref editorType, physicalView, flags, out hierarchy, out itemID, out windowFrame, out pfOpen); if (NativeMethods.Succeeded(hr) && pfOpen == 1) { return; } } IOleServiceProvider psp; uint editorFlags = (uint)__VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_UseEditor | (uint)__VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_DoOpen; NativeMethods.ThrowOnFailure(shellOpenDoc.OpenDocumentViaProjectWithSpecific(fullPath, editorFlags, ref editorType, physicalView, ref logicalView, out psp, out hierarchy, out itemID, out windowFrame)); if (windowFrame != null) NativeMethods.ThrowOnFailure(windowFrame.Show()); psp = null; } }
/// <include file='doc\Utilities.uex' path='docs/doc[@for="VsShell.OpenDocument1"]/*' /> public static void OpenDocument(IServiceProvider provider, string fullPath, Guid logicalView, out IVsUIHierarchy hierarchy, out uint itemID, out IVsWindowFrame windowFrame) { windowFrame = null; itemID = NativeMethods.VSITEMID_NIL; hierarchy = null; //open document if (!IsDocumentOpen(provider, fullPath, Guid.Empty, out hierarchy, out itemID, out windowFrame)) { IVsUIShellOpenDocument shellOpenDoc = provider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (shellOpenDoc != null) { IOleServiceProvider psp; uint itemid; NativeMethods.ThrowOnFailure(shellOpenDoc.OpenDocumentViaProject(fullPath, ref logicalView, out psp, out hierarchy, out itemid, out windowFrame)); if (windowFrame != null) NativeMethods.ThrowOnFailure(windowFrame.Show()); psp = null; } } else if (windowFrame != null) { NativeMethods.ThrowOnFailure(windowFrame.Show()); } }
public static void OpenDocument(IServiceProvider provider, string fullPath, Guid logicalView, out IVsUIHierarchy hierarchy, uint[] itemID, out IVsWindowFrame windowFrame) { windowFrame = null; hierarchy = null; //open document IVsUIShellOpenDocument shellOpenDoc = provider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IVsRunningDocumentTable pRDT = provider.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable; if (pRDT != null) { IntPtr punkDocData; uint docCookie; uint pitemid; IVsHierarchy ppIVsHierarchy; pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, fullPath, out ppIVsHierarchy, out pitemid, out punkDocData, out docCookie); if (punkDocData == IntPtr.Zero) { IOleServiceProvider psp; uint itemid; shellOpenDoc.OpenDocumentViaProject(fullPath, ref logicalView, out psp, out hierarchy, out itemid, out windowFrame); if (windowFrame != null) windowFrame.Show(); psp = null; } else { Marshal.Release(punkDocData); int pfOpen; shellOpenDoc.IsDocumentOpen((IVsUIHierarchy)ppIVsHierarchy, pitemid, fullPath, ref logicalView, (uint)__VSIDOFLAGS.IDO_IgnoreLogicalView, out hierarchy, itemID, out windowFrame, out pfOpen); if (windowFrame != null) windowFrame.Show(); } } }
public static void OpenDocument( ServiceProvider provider, string fullPath, out IVsUIHierarchy hierarchy, out uint itemID, out IVsWindowFrame windowFrame, out IVsTextView view) { view = null; windowFrame = null; itemID = VsConstants.VSITEMID_NIL; hierarchy = null; //open document IVsUIShellOpenDocument shellOpenDoc = (IVsUIShellOpenDocument)provider.QueryService(VsConstants.SID_SVsUIShellOpenDocument, typeof(IVsUIShellOpenDocument)); IVsRunningDocumentTable pRDT = (IVsRunningDocumentTable)provider.QueryService(VsConstants.SID_SVsRunningDocumentTable, typeof(IVsRunningDocumentTable)); if (pRDT != null) { IntPtr punkDocData; uint docCookie; uint pitemid; IVsHierarchy ppIVsHierarchy; pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, fullPath, out ppIVsHierarchy, out pitemid, out punkDocData, out docCookie); if (punkDocData == IntPtr.Zero) { Microsoft.VisualStudio.OLE.Interop.IServiceProvider psp; uint itemid; Guid logicalView = Guid.Empty; shellOpenDoc.OpenDocumentViaProject(fullPath, ref logicalView, out psp, out hierarchy, out itemid, out windowFrame); if (windowFrame != null) windowFrame.Show(); psp = null; } else { Marshal.Release(punkDocData); Guid logicalView = Guid.Empty; int pfOpen; shellOpenDoc.IsDocumentOpen((IVsUIHierarchy)ppIVsHierarchy, pitemid, fullPath, ref logicalView, (uint)__VSIDOFLAGS.IDO_IgnoreLogicalView, out hierarchy, out itemID, out windowFrame, out pfOpen); if (windowFrame != null) windowFrame.Show(); } } //return objects WindowFrameGetTextView( windowFrame, out view ); }
internal static IVsTextView GetTextView(IVsWindowFrame windowFrame) { if (windowFrame != null) { object docView; windowFrame.Show(); windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out docView); if (docView != null) { IVsTextView textView = docView as IVsTextView; if (textView == null) { IVsCodeWindow codeWindow = docView as IVsCodeWindow; if (codeWindow != null) { codeWindow.GetPrimaryView(out textView); } } return textView; } } return null; }
public void Show() { IVsWindowFrame frame = window?.Frame as IVsWindowFrame; frame?.Show(); }
/// <summary> /// Menu callback event handler that activates the merge pane after selecting work items in Work Item Query view. /// See <see cref="MergeWIControl"/> /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> public static void MyWIExpMergeIDCallback(object sender, EventArgs e) { var origCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; IVsThreadedWaitDialog2 dlg = null; int icanceled; try { if (Utilities.paneMerge == null) { Cursor.Current = origCursor; MessageBox.Show("Failed to initialize " + Utilities.AppTitle + ": Pane was null.", Utilities.AppTitle); return; } var mfrm = Utilities.paneMerge.control; mfrm.SuppressEvents = true; mfrm.defServerName = "$/" + Utilities.vsTeamCtxMan.CurrentContext.TeamProjectName; mfrm.Initialize(); mfrm.ClearGrids(); IVsWindowFrame frame = Utilities.paneMerge.Frame as IVsWindowFrame; if (frame == null) { Cursor.Current = origCursor; MessageBox.Show("Failed to initialize " + Utilities.AppTitle + ": Frame was null.", Utilities.AppTitle); return; } // Bring the tool window to the front and give it focus ErrorHandler.ThrowOnFailure(frame.Show()); int idx = 0; int iddx = 0; bool nolinks = true; bool bcanceled = false; object _lockToken1 = new object(); object _lockToken2 = new object(); string sourcePath; dlg = Utilities.CreateThreadedWaitDialog("Collecting information about changesets", "Starting to process changesets...", "status", 100); dlg.UpdateProgress("Collecting information about changesets", "Starting to process changesets...", "status", 0, 100, true, out bcanceled); IWorkItemTrackingDocument doc2 = Utilities.docsrv2.FindDocument(Utilities.dte.ActiveDocument.FullName, _lockToken2); if (doc2 == null) { Cursor.Current = origCursor; return; } foreach (int i in (doc2 as IResultsDocument).SelectedItemIds) { IWorkItemDocument widoc = Utilities.docsrv2.GetWorkItem(Utilities.tfscoll, i, _lockToken1); if (widoc == null) { continue; } if (!widoc.IsLoaded) { widoc.Load(); } iddx = 0; while (!widoc.IsLoaded && ++iddx < 10) { Thread.Sleep(1000); if (widoc.ItemState == WorkItemState.Error) { Utilities.OutputCommandString(widoc.Exception != null ? widoc.Exception.ToString() : "WorkItem cannot be loaded " + i); iddx = i; break; } } if (iddx == 10) { Utilities.OutputCommandString("WorkItem cannot be loaded " + i + ". Please open it manually and then try to load again."); iddx = i; break; } iddx = 0; foreach (Link lnk in widoc.Item.Links.Cast <Link>().Where(x => x.ArtifactLinkType.Name == "Fixed in Changeset")) { Changeset ch = Utilities.vcsrv.ArtifactProvider.GetChangeset(new Uri((lnk as ExternalLink).LinkedArtifactUri)); if (ch.Changes == null || ch.Changes.Length == 0) { continue; } string change = ch.Changes.Take(5).Select(x => x.ChangeType.ToString()).Aggregate((x, y) => x + "," + y); if (ch.Changes.Length > 5) { change += "..."; } string[] relbranches = MergeFactory.QueryBranchObjectOwnership(ch.ChangesetId); if (relbranches.Length == 0) { sourcePath = "$/" + Utilities.vsTeamCtxMan.CurrentContext.TeamProjectName; } else { sourcePath = relbranches[0]; } //} ListViewItem itm = mfrm.AddNewGridItem(widoc.Item.Id.ToString(), ch.ChangesetId.ToString(), ch.CreationDate.ToShortDateString(), ch.Owner, sourcePath, change, ch.Comment, new ListViewItemTag(ch.ChangesetId, widoc.Item.Id, sourcePath, ch.CreationDate)); Utilities.OutputCommandString("Adding Changeset: " + itm.Name + " => " + sourcePath); nolinks = false; dlg.UpdateProgress("Collecting information about changesets", "Processing changeset: " + ch.ChangesetId, "status", idx++, 100, false, out bcanceled); if (bcanceled) { widoc.Release(_lockToken1); doc2.Release(_lockToken2); mfrm.SortItems(); mfrm.SuppressEvents = false; Cursor.Current = origCursor; return; } if (idx == 100) { idx = 0; } } widoc.Release(_lockToken1); } doc2.Release(_lockToken2); mfrm.SortItems(); mfrm.UpdateRelatedBranchesCombo(); mfrm.SuppressEvents = false; Cursor.Current = origCursor; dlg.EndWaitDialog(out icanceled); if (iddx > 0) { MessageBox.Show("WorkItem cannot be loaded " + iddx + ". Please open it manually and then try to load again.", Utilities.AppTitle); } else if (nolinks) { MessageBox.Show("No linked Changesets where found in selected Work Items.", Utilities.AppTitle); } } catch (Exception ex) { Cursor.Current = origCursor; if (dlg != null) { dlg.EndWaitDialog(out icanceled); } Utilities.OutputCommandString(ex.ToString()); MessageBox.Show(ex.InnerException != null ? ex.InnerException.Message : ex.Message, Utilities.AppTitle, MessageBoxButtons.OK); } return; }
public int OpenItem(uint itemid, ref Guid rguidLogicalView, IntPtr punkDocDataExisting, out IVsWindowFrame ppWindowFrame) { _logger.LogHierarchy("OpenItem({0})", (int)itemid); ppWindowFrame = null; NodeViewModel node; uint flags = 536936448U; int hresult = 0; if (!_nodes.FindNode(itemid, out node)) return VSConstants.E_FAIL; if (string.IsNullOrEmpty(node.FullPath)) return VSConstants.E_NOTIMPL; IVsUIHierarchy hierarchy; uint itemid1; if (!VsShellUtilities.IsDocumentOpen(_serviceProvider, node.FullPath, rguidLogicalView, out hierarchy, out itemid1, out ppWindowFrame)) { IVsHierarchy hierOpen; int isDocInProj; IsDocumentInAnotherProject(node.FullPath, out hierOpen, out itemid1, out isDocInProj); if (hierOpen == null) { hresult = OpenItemViaMiscellaneousProject(flags, node.FullPath, ref rguidLogicalView, out ppWindowFrame); } else { var vsProject3 = hierOpen as IVsProject3; hresult = vsProject3 == null ? OpenItemViaMiscellaneousProject(flags, node.FullPath, ref rguidLogicalView, out ppWindowFrame) : vsProject3.OpenItem(itemid1, ref rguidLogicalView, punkDocDataExisting, out ppWindowFrame); } } if (ppWindowFrame != null) hresult = ppWindowFrame.Show(); return hresult; }
void ShowXamlEditor() { ErrorHandler.ThrowOnFailure(_subFrame.Show()); }
/// <summary> /// Registers given document and editor objects in the RDT under given /// hierarchy item. /// </summary> /// <param name="item">Hierarchy item identifier for this object.</param> /// <param name="document">Refernce to the document object.</param> /// <param name="view">Reference to the view object (editor).</param> public void RegisterEditor(int item, IDocument document, IEditor view) { // Validate inputs if (item < 0) { throw new ArgumentException(Resources.Error_InvalidHierarchyItemID, "item"); } if (document == null) { throw new ArgumentNullException("document"); } if (view == null) { throw new ArgumentNullException("view"); } Debug.Assert(hierarchyAccessor != null, "Hierarchy accessor is not initialized!"); Debug.Assert(shell != null, "Hierarchy accessor is not initialized!"); // Prepare data for shell call string moniker = BuildMoniker(document.TypeName, document.ObjectID); Guid editorID = Guid.Empty; Guid commandGroupID = view.CommandGroupID; IntPtr dataPunk = Marshal.GetIUnknownForObject(document); IntPtr viewPunk = Marshal.GetIUnknownForObject(view); // Validate prepared data Debug.Assert(!String.IsNullOrEmpty(moniker), "Failed to build moniker string!"); Debug.Assert(dataPunk != null, "Failed to marshal document object!"); Debug.Assert(viewPunk != null, "Failed to marshal view object!"); // Variable to store result IVsWindowFrame winFrame = null; // Initialize IDE editor infrastracture int result = shell.InitializeEditorInstance( (uint)0, // Initialization flags. We need default behavior here viewPunk, // View object reference (should implement IVsWindowPane) dataPunk, // Docuemnt object reference (should implement IVsPersistDocData) moniker, // Document moniker ref editorID, // GUID of the editor type null, // Name of the physical view. We use default ref editorID, // GUID identifying the logical view. String.Empty, // Initial caption defined by the document owner. Will be initialized by the editor later String.Empty, // Initial caption defined by the document editor. Will be initialized by the editor later Hierarchy, // Pointer to the IVsUIHierarchy interface of the project that contains the document (uint)item, // UI hierarchy item identifier of the document in the project system IntPtr.Zero, // Pointer to the IUnknown interface of the document data object if the document data object already exists in the running document table // Project-specific service provider. hierarchyAccessor.ServiceProvider as Microsoft.VisualStudio.OLE.Interop.IServiceProvider, ref commandGroupID, // Command UI GUID of the commands to display for this editor. out winFrame // The window frame that contains the editor ); // Validate result code and frame object Debug.Assert(winFrame != null && ErrorHandler.Succeeded(result), "Failed to initialize editor!"); ErrorHandler.ThrowOnFailure(result); // Pass frame reference to the editor for caption control view.OwnerFrame = winFrame; // Display editor if initialized winFrame.Show(); }
public void Execute() { _replFactory.CreateRepl(_frameworkProvider(), Path.GetDirectoryName(_selectedProjectProvider.Get().FullName)); _toolWindowFrame.Show(); }
// -------------------------------------------------------------------------------------------- /// <summary> /// Renders this window visible, brings the window to the top, and activates the window. /// </summary> /// <returns> /// If the method succeeds, it returns S_OK. If it fails, it returns an error code. /// </returns> // -------------------------------------------------------------------------------------------- int IVsWindowFrame.Show() { return(_Frame.Show()); }
public static void OpenItem(ServiceProvider site, bool newFile, bool openWith, ref Guid logicalView, IntPtr punkDocDataExisting, IVsHierarchy pHierarchy, uint hierarchyId, out IVsWindowFrame windowFrame) { windowFrame = null; IntPtr docData = punkDocDataExisting; try { uint itemid = hierarchyId; object pvar; pHierarchy.GetProperty(hierarchyId, (int)__VSHPROPID.VSHPROPID_Caption, out pvar); string caption = (string)pvar; string fullPath = null; if (punkDocDataExisting != IntPtr.Zero) { try { // if interface is not supported, return null IPersistFileFormat pff = (IPersistFileFormat)Marshal.GetTypedObjectForIUnknown(punkDocDataExisting, typeof(IPersistFileFormat)); uint format; pff.GetCurFile(out fullPath, out format); } catch { }; } if (fullPath == null) { string dir; pHierarchy.GetProperty((uint)VsConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectDir, out pvar); dir = (string)pvar; pHierarchy.GetProperty(hierarchyId, (int)__VSHPROPID.VSHPROPID_SaveName, out pvar); fullPath = dir != null?Path.Combine(dir, (string)pvar) : (string)pvar; } IVsUIHierarchy pRootHierarchy = null; pHierarchy.GetProperty((uint)VsConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Root, out pvar); IntPtr ptr; if (pvar == null) { pRootHierarchy = (IVsUIHierarchy)pHierarchy; } else { ptr = (IntPtr)pvar; pRootHierarchy = (IVsUIHierarchy)Marshal.GetTypedObjectForIUnknown(ptr, typeof(IVsUIHierarchy)); Marshal.Release(ptr); } IVsUIHierarchy pVsUIHierarchy = pRootHierarchy; IVsUIShellOpenDocument doc = (IVsUIShellOpenDocument)site.QueryService(VsConstants.SID_VsUIShellOpenDocument, typeof(IVsUIShellOpenDocument)); const uint OSE_ChooseBestStdEditor = 0x20000000; const uint OSE_UseOpenWithDialog = 0x10000000; const uint OSE_OpenAsNewFile = 0x40000000; if (openWith) { doc.OpenStandardEditor(OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, pVsUIHierarchy, itemid, docData, site.Unwrap(), out windowFrame); } else { // First we see if someone else has opened the requested view of the file and if so, // simply activate that view. IVsRunningDocumentTable pRDT = (IVsRunningDocumentTable)site.QueryService(VsConstants.SID_SVsRunningDocumentTable, typeof(IVsRunningDocumentTable)); if (pRDT != null) { uint docCookie; IVsHierarchy ppIVsHierarchy; pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, fullPath, out ppIVsHierarchy, out itemid, out docData, out docCookie); if (ppIVsHierarchy != null && docCookie != VsConstants.VSDOCCOOKIE_NIL && pHierarchy != ppIVsHierarchy && pVsUIHierarchy != ppIVsHierarchy) { // not opened by us, so call IsDocumentOpen with the right IVsUIHierarchy so we avoid the // annoying "This document is opened by another project" message prompt. pVsUIHierarchy = (IVsUIHierarchy)ppIVsHierarchy; itemid = (uint)VsConstants.VSITEMID_SELECTION; } ppIVsHierarchy = null; } IVsUIHierarchy ppHierOpen; uint pitemidOpen; int pfOpen; doc.IsDocumentOpen(pVsUIHierarchy, itemid, fullPath, ref logicalView, (uint)__VSIDOFLAGS.IDO_ActivateIfOpen, out ppHierOpen, out pitemidOpen, out windowFrame, out pfOpen); if (pfOpen != 1) { uint openFlags = OSE_ChooseBestStdEditor; if (newFile) { openFlags |= OSE_OpenAsNewFile; } //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid // of the node being opened, otherwise the debugger doesn't work. doc.OpenStandardEditor(openFlags, fullPath, ref logicalView, caption, pRootHierarchy, hierarchyId, docData, site.Unwrap(), out windowFrame); if (windowFrame != null) { if (newFile) { object var; windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var); IVsPersistDocData ppd = (IVsPersistDocData)var; ppd.SetUntitledDocPath(fullPath); } } } } if (windowFrame != null) { windowFrame.Show(); } } catch (COMException e) { if ((uint)e.ErrorCode != (uint)OleErrors.OLE_E_PROMPTSAVECANCELLED) { #if DEBUG MessageBox.Show(e.Message); #endif } } catch (Exception e) { #if DEBUG MessageBox.Show(e.Message); #endif } if (docData != punkDocDataExisting) { Marshal.Release(docData); } }
/// <summary> /// Menu callback event handler that activates the merge pane after selecting paths in Source Control Explorer. /// See <see cref="MergeWIControl"/> /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> public static void MySCQuBuildIDCallback(object sender, EventArgs e) { var origCursor = Cursor.Current; Cursor.Current = Cursors.WaitCursor; IVsThreadedWaitDialog2 dlg = null; bool nolinks = true; bool bcanceled = false; int icanceled; try { if (Utilities.vcext.Explorer.Workspace.Folders.Length == 0) { Cursor.Current = origCursor; MessageBox.Show("The workspace is not mapped to any local folder.", Utilities.AppTitle); return; } string folderPath = Utilities.vcext.Explorer.CurrentFolderItem.SourceServerPath; if (!MergeFactory.ServerItemExists(folderPath)) { Cursor.Current = origCursor; MessageBox.Show("Target server path is cloacked or doesn't exist.", Utilities.AppTitle); return; } if (Utilities.paneMerge == null) { Cursor.Current = origCursor; MessageBox.Show("Failed to initialize " + Utilities.AppTitle + ": Pane was null.", Utilities.AppTitle); return; } var mfrm = Utilities.paneMerge.control; mfrm.SuppressEvents = true; mfrm.defServerName = folderPath; mfrm.Initialize(); mfrm.ClearGrids(); IVsWindowFrame frame = Utilities.paneMerge.Frame as IVsWindowFrame; if (frame == null) { Cursor.Current = origCursor; MessageBox.Show("Failed to initialize " + Utilities.AppTitle + ": Frame was null.", Utilities.AppTitle); return; } // Bring the tool window to the front and give it focus ErrorHandler.ThrowOnFailure(frame.Show()); dlg = Utilities.CreateThreadedWaitDialog("Collecting information about changesets", "Starting to process changests...", "status", 100); dlg.UpdateProgress("Collecting information about changesets", "Starting to process changesets...", "status", 0, 100, true, out bcanceled); foreach (string sourcePath in Utilities.vcext.Explorer.SelectedItems.Select(x => x.SourceServerPath)) { int idx = 0; foreach (Changeset ch in Utilities.vcsrv.QueryHistory(sourcePath, VersionSpec.Latest, 0, RecursionType.Full, null, null, null, Int32.MaxValue, true, true, false, false)) { if (ch.Changes == null || ch.Changes.Length == 0) { continue; } string change = ch.Changes.Take(5).Select(x => x.ChangeType.ToString()).Aggregate((x, y) => x + "," + y); if (ch.Changes.Length > 5) { change += "..."; } string wrkitemstr = ""; int wrkitemid = 0; if (ch.WorkItems != null && ch.WorkItems.Length > 0) { wrkitemstr = ch.WorkItems.Select(x => x.Id.ToString()).Aggregate((x, y) => x + "," + y); wrkitemid = ch.WorkItems[0].Id; } ListViewItem itm = mfrm.AddNewGridItem(wrkitemstr, ch.ChangesetId.ToString(), ch.CreationDate.ToShortDateString(), ch.Owner, sourcePath, change, ch.Comment, new ListViewItemTag(ch.ChangesetId, wrkitemid, sourcePath, ch.CreationDate)); Utilities.OutputCommandString("Adding Changeset: " + itm.Name + " => " + sourcePath); nolinks = false; dlg.UpdateProgress("Collecting information about changesets", "Processing changeset: " + ch.ChangesetId, "status", idx++, 100, false, out bcanceled); if (bcanceled) { mfrm.SortItems(); mfrm.SuppressEvents = false; Cursor.Current = origCursor; return; } if (idx == 100) { idx = 0; } } } mfrm.SortItems(); mfrm.UpdateRelatedBranchesCombo(); mfrm.SuppressEvents = false; Cursor.Current = origCursor; dlg.EndWaitDialog(out icanceled); if (nolinks) { MessageBox.Show("No Changesets where found in selected path.", Utilities.AppTitle); } } catch (Exception ex) { Cursor.Current = origCursor; if (dlg != null) { dlg.EndWaitDialog(out icanceled); } Utilities.OutputCommandString(ex.ToString()); MessageBox.Show(ex.InnerException != null ? ex.InnerException.Message : ex.Message, Utilities.AppTitle, MessageBoxButtons.OK); } return; }
public static void OpenDocumentWithSpecificEditor(IServiceProvider provider, string fullPath, Guid editorType, string physicalView, Guid logicalView, out IVsUIHierarchy hierarchy, uint[] itemID, out IVsWindowFrame windowFrame) { windowFrame = null; hierarchy = null; //open document IVsUIShellOpenDocument shellOpenDoc = provider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IVsRunningDocumentTable pRDT = provider.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable; if (pRDT != null) { IntPtr punkDocData; uint docCookie; uint pitemid; IVsHierarchy ppIVsHierarchy; pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, fullPath, out ppIVsHierarchy, out pitemid, out punkDocData, out docCookie); if (punkDocData != IntPtr.Zero) { Marshal.Release(punkDocData); int pfOpen; shellOpenDoc.IsDocumentOpen((IVsUIHierarchy)ppIVsHierarchy, pitemid, fullPath, ref logicalView, (uint)__VSIDOFLAGS.IDO_IgnoreLogicalView, out hierarchy, itemID, out windowFrame, out pfOpen); hierarchy = null; if (windowFrame != null) { Guid currentEditor; windowFrame.GetGuidProperty((int)__VSFPROPID.VSFPROPID_guidEditorType, out currentEditor); object currentView; windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_pszPhysicalView, out currentView); if (currentEditor == editorType && currentView != null && physicalView == currentView.ToString()) { windowFrame.Show(); return; } } //windowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_PromptSave); windowFrame = null; } IOleServiceProvider psp; uint itemid; uint editorFlags = (uint)__VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_UseEditor; shellOpenDoc.OpenDocumentViaProjectWithSpecific(fullPath, editorFlags, ref editorType, physicalView, ref logicalView, out psp, out hierarchy, out itemid, out windowFrame); if (windowFrame != null) windowFrame.Show(); psp = null; } }
public static void OpenItem(ServiceProvider site, bool newFile, bool openWith, ref Guid logicalView, IntPtr punkDocDataExisting, IVsHierarchy pHierarchy, uint hierarchyId, out IVsWindowFrame windowFrame) { windowFrame = null; IntPtr docData = punkDocDataExisting; try { uint itemid = hierarchyId; object pvar; pHierarchy.GetProperty(hierarchyId, (int)__VSHPROPID.VSHPROPID_Caption, out pvar); string caption = (string)pvar; string fullPath = null; if (punkDocDataExisting != IntPtr.Zero) { try { // if interface is not supported, return null IPersistFileFormat pff = (IPersistFileFormat)Marshal.GetTypedObjectForIUnknown(punkDocDataExisting, typeof(IPersistFileFormat)); uint format; pff.GetCurFile(out fullPath, out format); } catch { }; } if (fullPath == null) { string dir; pHierarchy.GetProperty((uint)VsConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectDir, out pvar); dir = (string)pvar; pHierarchy.GetProperty(hierarchyId, (int)__VSHPROPID.VSHPROPID_SaveName, out pvar); fullPath = dir != null ? Path.Combine(dir,(string)pvar) : (string)pvar; } IVsUIHierarchy pRootHierarchy = null; pHierarchy.GetProperty((uint)VsConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Root, out pvar); IntPtr ptr; if (pvar == null) { pRootHierarchy = (IVsUIHierarchy)pHierarchy; } else { ptr = (IntPtr)pvar; pRootHierarchy = (IVsUIHierarchy)Marshal.GetTypedObjectForIUnknown(ptr, typeof(IVsUIHierarchy)); Marshal.Release(ptr); } IVsUIHierarchy pVsUIHierarchy = pRootHierarchy; IVsUIShellOpenDocument doc = (IVsUIShellOpenDocument)site.QueryService(VsConstants.SID_VsUIShellOpenDocument, typeof(IVsUIShellOpenDocument)); const uint OSE_ChooseBestStdEditor = 0x20000000; const uint OSE_UseOpenWithDialog = 0x10000000; const uint OSE_OpenAsNewFile = 0x40000000; if (openWith) { doc.OpenStandardEditor(OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, pVsUIHierarchy, itemid, docData, site.Unwrap(), out windowFrame); } else { // First we see if someone else has opened the requested view of the file and if so, // simply activate that view. IVsRunningDocumentTable pRDT = (IVsRunningDocumentTable)site.QueryService(VsConstants.SID_SVsRunningDocumentTable, typeof(IVsRunningDocumentTable)); if (pRDT != null) { uint docCookie; IVsHierarchy ppIVsHierarchy; pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, fullPath, out ppIVsHierarchy, out itemid, out docData, out docCookie); if (ppIVsHierarchy != null && docCookie != VsConstants.VSDOCCOOKIE_NIL && pHierarchy != ppIVsHierarchy && pVsUIHierarchy != ppIVsHierarchy) { // not opened by us, so call IsDocumentOpen with the right IVsUIHierarchy so we avoid the // annoying "This document is opened by another project" message prompt. pVsUIHierarchy = (IVsUIHierarchy)ppIVsHierarchy; itemid = (uint)VsConstants.VSITEMID_SELECTION; } ppIVsHierarchy = null; } IVsUIHierarchy ppHierOpen; uint pitemidOpen; int pfOpen; doc.IsDocumentOpen(pVsUIHierarchy, itemid, fullPath, ref logicalView, (uint)__VSIDOFLAGS.IDO_ActivateIfOpen, out ppHierOpen, out pitemidOpen, out windowFrame, out pfOpen); if (pfOpen != 1) { uint openFlags = OSE_ChooseBestStdEditor; if (newFile) openFlags |= OSE_OpenAsNewFile; //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid // of the node being opened, otherwise the debugger doesn't work. doc.OpenStandardEditor(openFlags, fullPath, ref logicalView, caption, pRootHierarchy, hierarchyId, docData, site.Unwrap(), out windowFrame); if (windowFrame != null) { if (newFile) { object var; windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var); IVsPersistDocData ppd = (IVsPersistDocData)var; ppd.SetUntitledDocPath(fullPath); } } } } if (windowFrame != null) windowFrame.Show(); } catch (COMException e) { if ((uint)e.ErrorCode != (uint)OleErrors.OLE_E_PROMPTSAVECANCELLED) { #if DEBUG MessageBox.Show(e.Message); #endif } } catch (Exception e) { #if DEBUG MessageBox.Show(e.Message); #endif } if (docData != punkDocDataExisting) { Marshal.Release(docData); } }
/// <include file='doc\Hierarchy.uex' path='docs/doc[@for="HierarchyNode.OpenItem3"]/*' /> public static void OpenItem(IServiceProvider site, bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr punkDocDataExisting, IVsHierarchy pHierarchy, uint hierarchyId, out IVsWindowFrame windowFrame) { windowFrame = null; IntPtr docData = punkDocDataExisting; Exception error = null; try { uint itemid = hierarchyId; object pvar; NativeMethods.ThrowOnFailure(pHierarchy.GetProperty(hierarchyId, (int)__VSHPROPID.VSHPROPID_Caption, out pvar)); string caption = (string)pvar; string fullPath = null; if (punkDocDataExisting != IntPtr.Zero) { fullPath = VsShell.GetFilePath(punkDocDataExisting); } if (fullPath == null) { string dir; NativeMethods.ThrowOnFailure(pHierarchy.GetProperty(NativeMethods.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectDir, out pvar)); dir = (string)pvar; NativeMethods.ThrowOnFailure(pHierarchy.GetProperty(hierarchyId, (int)__VSHPROPID.VSHPROPID_SaveName, out pvar)); // todo: what if the path is a URL? fullPath = dir != null ? Path.Combine(dir, (string)pvar) : (string)pvar; } IVsUIHierarchy pRootHierarchy = null; NativeMethods.ThrowOnFailure(pHierarchy.GetProperty(NativeMethods.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Root, out pvar)); IntPtr ptr; if (pvar == null) { pRootHierarchy = (IVsUIHierarchy)pHierarchy; } else { ptr = (IntPtr)pvar; pRootHierarchy = (IVsUIHierarchy)Marshal.GetTypedObjectForIUnknown(ptr, typeof(IVsUIHierarchy)); Marshal.Release(ptr); } IVsUIHierarchy pVsUIHierarchy = pRootHierarchy; IVsUIShellOpenDocument doc = site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; const uint OSE_ChooseBestStdEditor = 0x20000000; const uint OSE_UseOpenWithDialog = 0x10000000; const uint OSE_OpenAsNewFile = 0x40000000; if (openWith) { IOleServiceProvider psp = site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider; NativeMethods.ThrowOnFailure(doc.OpenStandardEditor(OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, pVsUIHierarchy, itemid, docData, psp, out windowFrame)); } else { // First we see if someone else has opened the requested view of the file. IVsRunningDocumentTable pRDT = site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (pRDT != null) { uint docCookie; IVsHierarchy ppIVsHierarchy; NativeMethods.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, fullPath, out ppIVsHierarchy, out itemid, out docData, out docCookie)); if (ppIVsHierarchy != null && docCookie != (uint)ShellConstants.VSDOCCOOKIE_NIL && pHierarchy != ppIVsHierarchy && pVsUIHierarchy != ppIVsHierarchy) { // not opened by us, so call IsDocumentOpen with the right IVsUIHierarchy so we avoid the // annoying "This document is opened by another project" message prompt. pVsUIHierarchy = (IVsUIHierarchy)ppIVsHierarchy; itemid = (uint)NativeMethods.VSITEMID_SELECTION; } ppIVsHierarchy = null; } uint openFlags = 0; if (newFile) openFlags |= OSE_OpenAsNewFile; //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid // of the node being opened, otherwise the debugger doesn't work. IOleServiceProvider psp = site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider; int retryCount = 1; while (retryCount > 0) { try { if (editorType != Guid.Empty) { NativeMethods.ThrowOnFailure(doc.OpenSpecificEditor(editorFlags, fullPath, ref editorType, physicalView, ref logicalView, caption, pRootHierarchy, hierarchyId, docData, psp, out windowFrame)); } else { openFlags |= OSE_ChooseBestStdEditor; NativeMethods.ThrowOnFailure(doc.OpenStandardEditor(openFlags, fullPath, ref logicalView, caption, pRootHierarchy, hierarchyId, docData, psp, out windowFrame)); } break; } catch (Exception e) { if (e is COMException) { COMException ce = (COMException)e; if (ce.ErrorCode == NativeMethods.OLE_E_PROMPTSAVECANCELLED) { break; } } // perhaps the editor is not compatible with an existing one. // try OpenStandardEditor. if (editorType != Guid.Empty) { editorType = Guid.Empty; } else { throw e; } } } } if (windowFrame != null) { if (newFile) { object var; NativeMethods.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var)); IVsPersistDocData ppd = (IVsPersistDocData)var; NativeMethods.ThrowOnFailure(ppd.SetUntitledDocPath(fullPath)); } } if (windowFrame != null) NativeMethods.ThrowOnFailure(windowFrame.Show()); } catch (Exception e) { error = e; } if (error != null) { string msg = error.Message; if (logicalView != Guid.Empty) { if (editorType != Guid.Empty) { msg = String.Format(SR.GetString(SR.EditorViewError), logicalView.ToString(), editorType.ToString()) + "\r\n" + msg; } else { msg = String.Format(SR.GetString(SR.StandardEditorViewError), logicalView.ToString()) + "\r\n" + msg; } } else if (editorType != Guid.Empty) { msg = String.Format(SR.GetString(SR.StandardEditorViewError), logicalView.ToString()) + "\r\n" + msg; } MessageBox.Show(msg, SR.GetString(SR.Error), MessageBoxButtons.OK, MessageBoxIcon.Error); if (windowFrame != null) { try { NativeMethods.ThrowOnFailure(windowFrame.CloseFrame(0)); } catch { } windowFrame = null; } } if (docData != punkDocDataExisting && docData != IntPtr.Zero) { Marshal.Release(docData); } }
/// <include file='doc\VsShellUtilities.uex' path='docs/doc[@for="VsShellUtilities.OpenDocument"]/*' /> /// <devdoc> /// Open document using the appropriate project. /// </devdoc> /// <param name="provider">The service provider.</param> /// <param name="fullPath">Full path to the document.</param> /// <param name="logicalView">GUID identifying the logical view.</param> /// <param name="hierarchy">Reference to the IVsUIHierarchy interface of the project that contains the Open document.</param> /// <param name="itemID"> Reference to the hierarchy item identifier of the document in the project.</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the document.</param> public static void OpenDocument(IServiceProvider provider, string fullPath, Guid logicalView, out IVsUIHierarchy hierarchy, out uint itemID, out IVsWindowFrame windowFrame) { windowFrame = null; itemID = VSConstants.VSITEMID_NIL; hierarchy = null; if (provider == null) { throw new ArgumentException("provider"); } if (String.IsNullOrEmpty(fullPath)) { throw new ArgumentException("fullPath"); } //open document if (!IsDocumentOpen(provider, fullPath, logicalView, out hierarchy, out itemID, out windowFrame)) { IVsUIShellOpenDocument shellOpenDoc = provider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (shellOpenDoc != null) { IOleServiceProvider psp; uint itemid; ErrorHandler.ThrowOnFailure(shellOpenDoc.OpenDocumentViaProject(fullPath, ref logicalView, out psp, out hierarchy, out itemid, out windowFrame)); } } if (windowFrame != null) { ErrorHandler.ThrowOnFailure(windowFrame.Show()); } }
protected int Open(bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction, bool reopen = false) { windowFrame = null; if (this.Node == null || this.Node.ProjectMgr == null || this.Node.ProjectMgr.IsClosed) { return(VSConstants.E_FAIL); } Debug.Assert(this.Node != null, "No node has been initialized for the document manager"); Debug.Assert(this.Node.ProjectMgr != null, "No project manager has been initialized for the document manager"); Debug.Assert(this.Node is FileNode, "Node is not FileNode object"); int returnValue = VSConstants.S_OK; string caption = this.GetOwnerCaption(); string fullPath = this.GetFullPathForDocument(); IVsUIShellOpenDocument uiShellOpenDocument = this.Node.ProjectMgr.Site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IOleServiceProvider serviceProvider = this.Node.ProjectMgr.Site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider; var openState = uiShellOpenDocument as IVsUIShellOpenDocument3; bool showDialog = !reopen && (openState == null || !((__VSNEWDOCUMENTSTATE)openState.NewDocumentState).HasFlag(__VSNEWDOCUMENTSTATE.NDS_Provisional)); // Make sure that the file is on disk before we open the editor and display message if not found if (!((FileNode)this.Node).IsFileOnDisk(showDialog)) { // Bail since we are not able to open the item // Do not return an error code otherwise an internal error message is shown. The scenario for this operation // normally is already a reaction to a dialog box telling that the item has been removed. return(VSConstants.S_FALSE); } try { this.Node.ProjectMgr.OnOpenItem(fullPath); int result = VSConstants.E_FAIL; if (openWith) { result = uiShellOpenDocument.OpenStandardEditor((uint)__VSOSEFLAGS.OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } else { __VSOSEFLAGS openFlags = 0; if (newFile) { openFlags |= __VSOSEFLAGS.OSE_OpenAsNewFile; } //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid // of the node being opened, otherwise the debugger doesn't work. if (editorType != Guid.Empty) { result = uiShellOpenDocument.OpenSpecificEditor(editorFlags, fullPath, ref editorType, physicalView, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } else { openFlags |= __VSOSEFLAGS.OSE_ChooseBestStdEditor; result = uiShellOpenDocument.OpenStandardEditor((uint)openFlags, fullPath, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } } if (result != VSConstants.S_OK && result != VSConstants.S_FALSE && result != VSConstants.OLE_E_PROMPTSAVECANCELLED) { ErrorHandler.ThrowOnFailure(result); } if (windowFrame != null) { object var; if (newFile) { ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var)); IVsPersistDocData persistDocData = (IVsPersistDocData)var; ErrorHandler.ThrowOnFailure(persistDocData.SetUntitledDocPath(fullPath)); } var = null; ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var)); this.Node.DocCookie = (uint)(int)var; if (windowFrameAction == WindowFrameShowAction.Show) { ErrorHandler.ThrowOnFailure(windowFrame.Show()); } else if (windowFrameAction == WindowFrameShowAction.ShowNoActivate) { ErrorHandler.ThrowOnFailure(windowFrame.ShowNoActivate()); } else if (windowFrameAction == WindowFrameShowAction.Hide) { ErrorHandler.ThrowOnFailure(windowFrame.Hide()); } } } catch (COMException e) { XSharpProjectPackage.Instance.DisplayException(e); returnValue = e.ErrorCode; CloseWindowFrame(ref windowFrame); } return(returnValue); }
/// <summary> /// Attempts to navigate a VS editor to the text marker. /// </summary> /// <param name="usePreviewPane">Indicates whether to use VS's preview pane.</param> /// <param name="moveFocusToCaretLocation">Indicates whether to move focus to the caret location.</param> /// <returns>Returns true if a VS editor was opened.</returns> /// <remarks> /// The <paramref name="usePreviewPane"/> indicates whether Visual Studio opens the document as a preview (tab to the right) /// rather than as an "open code editor" (tab attached to other open documents on the left). /// </remarks> public bool NavigateTo(bool usePreviewPane, bool moveFocusToCaretLocation) { ThreadHelper.ThrowIfNotOnUIThread(); bool documentWasOpened = false; // Make sure to fully populate region. if (!this.TryToFullyPopulateRegionAndFilePath()) { return(false); } // If the tag doesn't have a persistent span, or its associated document isn't open, // then this indicates that we need to attempt to open the document and cause it to // be tagged. if (!this.PersistentSpanValid()) { // Now, we need to make sure the document gets tagged before the next section of code // in this method attempts to navigate to it. // So the flow looks like this. Get Visual Studio to open the document for us. // That will cause Visual Studio to create a text view for it. // Now, just because a text view is created does not mean that // a request for "tags" has occurred. Tagging (and the display of those tags) // is highly asynchronous. Taggers are created on demand and disposed when they are no longer // needed. It is quite common to have multiple taggers active for the same text view and text buffers // at the same time. (An easy example is a split-window scenario). // This class relies on a persistent span (this.persistentSpan) being non-null and valid. // This class "creates" the persistent span when it is asked for its tags in the GetTags // method. // To facilitate that, we will: // 1) Open the document // 2) Get the text view from the document. // 2a) That alone may be enough to make the persistent span valid if it was already created. // 3) If the persistent span still isn't valid (likely because we have crated the persistent span yet), ask ourselves for the tags which will // cause the span to be created. IVsWindowFrame vsWindowFrame = SdkUIUtilities.OpenDocument(ServiceProvider.GlobalProvider, this.resolvedFullFilePath, usePreviewPane); if (vsWindowFrame == null) { return(false); } vsWindowFrame.Show(); documentWasOpened = true; // At this point, the persistent span may have "become valid" due to the document open. // If not, then ask ourselves for the tags which will create the persistent span. if (!this.PersistentSpanValid()) { if (!SdkUIUtilities.TryGetTextViewFromFrame(vsWindowFrame, out ITextView textView)) { return(false); } var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel)); if (componentModel == null) { return(false); } IPersistentSpanFactory persistentSpanFactory = componentModel.GetService <IPersistentSpanFactory>(); if (persistentSpanFactory == null) { return(false); } if (!this.TryCreatePersistentSpan(textView.TextBuffer, persistentSpanFactory)) { return(false); } } } if (!this.PersistentSpanValid()) { return(false); } // Now, if the span IS valid it doesn't mean that the editor is visible, so make sure we open the document // for the user if needed. // But before we try to call "open document" let's see if we can find an active view because calling // "open document" is super slow (which causes keyboard navigation from items in the SARIF explorer to be slow // IF "open document" is called every time. if (!documentWasOpened || !SdkUIUtilities.TryGetActiveViewForTextBuffer(this.persistentSpan.Span.TextBuffer, out IWpfTextView wpfTextView)) { IVsWindowFrame vsWindowFrame = SdkUIUtilities.OpenDocument(ServiceProvider.GlobalProvider, this.resolvedFullFilePath, usePreviewPane); if (vsWindowFrame == null) { return(false); } vsWindowFrame.Show(); if (!SdkUIUtilities.TryGetActiveViewForTextBuffer(this.persistentSpan.Span.TextBuffer, out wpfTextView)) { return(false); } } ITextSnapshot currentSnapshot = this.persistentSpan.Span.TextBuffer.CurrentSnapshot; // Note that "GetSpan" is not really a great name. What is actually happening // is the "Span" that "GetSpan" is called on is "mapped" onto the passed in // text snapshot. In essence what this means is take the "persistent span" // that we have and "replay" any edits that have occurred and return a new // span. So, if the span is no longer relevant (lets say the text has been deleted) // then you'll get back an empty span. SnapshotSpan trackingSpanSnapshot = this.persistentSpan.Span.GetSpan(currentSnapshot); // If the caret is already in the text within the marker, don't re-select it // otherwise users cannot move the caret in the region. // If the caret isn't in the marker, move it there. if (!trackingSpanSnapshot.Contains(wpfTextView.Caret.Position.BufferPosition) && !trackingSpanSnapshot.IsEmpty) { wpfTextView.Selection.Select(trackingSpanSnapshot, isReversed: false); wpfTextView.Caret.MoveTo(trackingSpanSnapshot.End); wpfTextView.Caret.EnsureVisible(); if (moveFocusToCaretLocation) { wpfTextView.VisualElement.Focus(); } } return(true); }
public void OpenDetailsToolWindow(TreeViewArtifact Artifact) { string METHOD = CLASS + "OpenDetailsToolWindow"; try { //Find the existing window.. toolSpiraExplorerDetails window = this.FindExistingToolWindow(Artifact, true); if (window != null) { //If the window is hidden and is not in an unsaved state, reload window contents. // If window is not hidden, simply bring it to foreground. // If window is not created, load window contents. // If window is hidden and in an unsaved state, simply bring it to foreground. //See if we need to reset the content. if (!window.IsContentSet || (window.IsHidden && !window.IsChanged)) { //Generate the details screen. object detailContent = null; switch (Artifact.ArtifactType) { case TreeViewArtifact.ArtifactTypeEnum.Incident: frmDetailsIncident detIncident = new frmDetailsIncident(Artifact, window); detailContent = detIncident; break; case TreeViewArtifact.ArtifactTypeEnum.Requirement: frmDetailsRequirement detRequirement = new frmDetailsRequirement(Artifact, window); detailContent = detRequirement; break; case TreeViewArtifact.ArtifactTypeEnum.Task: frmDetailsTask detTask = new frmDetailsTask(Artifact, window); detailContent = detTask; break; } //Set toolwindow's content. if (detailContent != null) { ((cntrlDetailsForm)window.FormControl).Content = detailContent; } } //Get the frame. IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame; windowFrame.SetProperty((int)__VSFPROPID.VSFPROPID_FrameMode, VSFRAMEMODE.VSFM_MdiChild); Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show()); ((dynamic)((cntrlDetailsForm)window.FormControl).Content).IsHidden = false; } else { //Log an error. Logger.LogMessage(METHOD, "Could not create window.", EventLogEntryType.Error); MessageBox.Show(StaticFuncs.getCultureResource.GetString("app_General_WindowOpenErrorMessage"), StaticFuncs.getCultureResource.GetString("app_General_WindowOpenError"), MessageBoxButton.OK, MessageBoxImage.Error); } } catch (Exception ex) { Logger.LogMessage(ex, "OpenDetailsToolWindow()"); MessageBox.Show(StaticFuncs.getCultureResource.GetString("app_General_UnexpectedError"), StaticFuncs.getCultureResource.GetString("app_General_ApplicationShortName"), MessageBoxButton.OK, MessageBoxImage.Error); } }
///-------------------------------------------------------------------------------- /// <summary> /// This function is called when the user clicks the menu item that shows the /// tool window. See the Initialize method to see how the menu item is associated to /// this function using the OleMenuCommandService service and the MenuCommand class. /// </summary> ///-------------------------------------------------------------------------------- private void ShowSolutionBuilderWindow(object sender, EventArgs e) { try { // show solution builder SolutionBuilderPane.Clear(); // Get the instance number 0 of this tool window. This window is single instance so this instance // is actually the only one. // The last flag is set to true so that if the tool window does not exists it will be created. SolutionBuilderWindow window = this.FindToolWindow(typeof(SolutionBuilderWindow), 0, false) as SolutionBuilderWindow; if (window == null) { window = this.CreateToolWindow(typeof(SolutionBuilderWindow), 0) as SolutionBuilderWindow; if ((null == window) || (null == window.Frame)) { throw new NotSupportedException(Resources.CanNotCreateWindow); } } // wire up solution builder window events window.Control.ProgressChanged -= SolutionBuilderControl_ProgressChanged; window.Control.ProgressChanged += new SolutionBuilderControl.StatusChangeEventHandler(SolutionBuilderControl_ProgressChanged); window.Control.StatusChanged -= SolutionBuilderControl_StatusChanged; window.Control.StatusChanged += new SolutionBuilderControl.StatusChangeEventHandler(SolutionBuilderControl_StatusChanged); window.Control.OutputChanged -= SolutionBuilderControl_OutputChanged; window.Control.OutputChanged += new SolutionBuilderControl.StatusChangeEventHandler(SolutionBuilderControl_OutputChanged); window.Control.OpenOutputSolutionRequested -= SolutionBuilderControl_OpenOutputSolutionRequested; window.Control.OpenOutputSolutionRequested += new SolutionBuilderControl.SolutionEventHandler(SolutionBuilderControl_OpenOutputSolutionRequested); window.Control.ShowSolutionDesignerRequested -= SolutionBuilderControl_ShowSolutionDesignerRequested; window.Control.ShowSolutionDesignerRequested += new SolutionBuilderControl.SolutionEventHandler(SolutionBuilderControl_ShowSolutionDesignerRequested); // show designer window ShowSolutionDesignerWindow(); // show getting started help if (window.Control.DataContext is BuilderViewModel) { (window.Control.DataContext as BuilderViewModel).ResourcesFolder.ShowGettingStartedHelp(); } // TODO: remove this later window.DesignerWindow = this.FindToolWindow(typeof(SolutionDesignerWindow), 0, false) as SolutionDesignerWindow; // if solution is already open, load it CheckOpenCurrentSolution(); IVsWindowFrame windowFrame = (IVsWindowFrame)window.Frame; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(windowFrame.Show()); // put solution builder output to output pane SolutionBuilderPane.OutputString("Solution Builder shown."); } catch (System.Exception ex) { Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Error showing solution builder: {0}", ex.ToString())); // put exception message in output pane string message = ex.Message; System.Exception exception = ex.InnerException; while (exception != null) { message += "\r\n" + exception.Message; exception = exception.InnerException; } SolutionBuilderPane.OutputString(message); } }
/// <include file='doc\VsShellUtilities.uex' path='docs/doc[@for="VsShellUtilities.OpenDocumentWithSpecificEditor"]/*' /> /// <devdoc> /// Open a document using a specific editor. /// </devdoc> /// <param name="provider">The service provider.</param> /// <param name="fullPath">Full path to the document.</param> /// <param name="editorType">Unique identifier of the editor type.</param> /// <param name="logicalView">In MultiView case determines view to be activated by IVsMultiViewDocumentView. For a list of logical view GUIDS, see constants starting with LOGVIEWID_ defined in NativeMethods class</param> /// <param name="hierarchy">Reference to the IVsUIHierarchy interface of the project that can open the document.</param> /// <param name="itemID"> Reference to the hierarchy item identifier of the document in the project.</param> /// <param name="windowFrame">A reference to the window frame that is mapped to the document.</param> public static void OpenDocumentWithSpecificEditor(IServiceProvider provider, string fullPath, Guid editorType, Guid logicalView, out IVsUIHierarchy hierarchy, out uint itemID, out IVsWindowFrame windowFrame) { windowFrame = null; itemID = VSConstants.VSITEMID_NIL; hierarchy = null; if (provider == null) { throw new ArgumentException("provider"); } if (String.IsNullOrEmpty(fullPath)) { throw new ArgumentException("fullPath"); } //open document IVsUIShellOpenDocument shellOpenDoc = provider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IVsRunningDocumentTable pRDT = provider.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable; string physicalView = null; if (pRDT != null && shellOpenDoc != null) { ErrorHandler.ThrowOnFailure(shellOpenDoc.MapLogicalView(ref editorType, ref logicalView, out physicalView)); // See if the requested editor is already open with the requested view. IntPtr punkDocData = IntPtr.Zero; uint docCookie; IVsHierarchy ppIVsHierarchy; try { ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, fullPath, out ppIVsHierarchy, out itemID, out punkDocData, out docCookie)); int pfOpen; uint flags = (uint)__VSIDOFLAGS.IDO_ActivateIfOpen; int hr = shellOpenDoc.IsSpecificDocumentViewOpen((IVsUIHierarchy)ppIVsHierarchy, itemID, fullPath, ref editorType, physicalView, flags, out hierarchy, out itemID, out windowFrame, out pfOpen); if (ErrorHandler.Succeeded(hr) && pfOpen == 1) { return; } } finally { if (punkDocData != IntPtr.Zero) { Marshal.Release(punkDocData); } } IOleServiceProvider psp; uint editorFlags = (uint)__VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_UseEditor | (uint)__VSSPECIFICEDITORFLAGS.VSSPECIFICEDITOR_DoOpen; ErrorHandler.ThrowOnFailure(shellOpenDoc.OpenDocumentViaProjectWithSpecific(fullPath, editorFlags, ref editorType, physicalView, ref logicalView, out psp, out hierarchy, out itemID, out windowFrame)); if (windowFrame != null) ErrorHandler.ThrowOnFailure(windowFrame.Show()); psp = null; } }
protected virtual void GotoSource(VSOBJGOTOSRCTYPE gotoType) { // We do not support the "Goto Reference" if (VSOBJGOTOSRCTYPE.GS_REFERENCE == gotoType) { return; } // There is no difference between definition and declaration, so here we // don't check for the other flags. IVsWindowFrame frame = null; IntPtr documentData = FindDocDataFromRDT(); try { // Now we can try to open the editor. We assume that the owner hierarchy is // a project and we want to use its OpenItem method. IVsProject3 project = ownerHierarchy as IVsProject3; if (null == project) { return; } Guid viewGuid = VSConstants.LOGVIEWID_Code; ErrorHandler.ThrowOnFailure(project.OpenItem(fileId, ref viewGuid, documentData, out frame)); } finally { if (IntPtr.Zero != documentData) { Marshal.Release(documentData); documentData = IntPtr.Zero; } } // Make sure that the document window is visible. ErrorHandler.ThrowOnFailure(frame.Show()); // Get the code window from the window frame. object docView; ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out docView)); IVsCodeWindow codeWindow = docView as IVsCodeWindow; if (null == codeWindow) { object docData; ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData)); codeWindow = docData as IVsCodeWindow; if (null == codeWindow) { return; } } // Get the primary view from the code window. IVsTextView textView; ErrorHandler.ThrowOnFailure(codeWindow.GetPrimaryView(out textView)); // Set the cursor at the beginning of the declaration. ErrorHandler.ThrowOnFailure(textView.SetCaretPos(sourceSpan.iStartLine, sourceSpan.iStartIndex)); // Make sure that the text is visible. TextSpan visibleSpan = new TextSpan(); visibleSpan.iStartLine = sourceSpan.iStartLine; visibleSpan.iStartIndex = sourceSpan.iStartIndex; visibleSpan.iEndLine = sourceSpan.iEndLine; visibleSpan.iEndIndex = sourceSpan.iEndIndex; ErrorHandler.ThrowOnFailure(textView.EnsureSpanVisible(visibleSpan)); }
private int OpenItem(bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame frame, WindowFrameShowAction windowFrameAction) { frame = null; if (this.ProjectMgr == null || this.ProjectMgr.IsClosed) { return VSConstants.E_FAIL; } int result = VSConstants.S_OK; uint[] ppItemId = new uint[1]; ppItemId[0] = this.ID; int open; IVsUIHierarchy project; string fullPath = GetMkDocument(); // check if the file exists if (!System.IO.File.Exists(fullPath)) { // TODO Inform clients that we have an invalid item (wrong icon) //// Inform clients that we have an invalid item (wrong icon) //this.Node.OnInvalidateItems(this.Node.Parent); return VSConstants.S_FALSE; } IVsUIShellOpenDocument sod = (this.ProjectMgr as CogaenEditProject).Site.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (sod != null) { try { // try to get hold of the open file sod.IsDocumentOpen(this.ProjectMgr , this.ID , GetMkDocument() , ref logicalView /* LOGVIEWID_Code to show xml behind */ , (uint)__VSIDOFLAGS.IDO_ActivateIfOpen , out project , ppItemId , out frame , out open); // file is not open if (open == 0) { // TODO load doc data Load(fullPath, 0, 0); docDataExisting = Marshal.GetIUnknownForObject(ObjectBuilder); if (openWith) { result = sod.OpenStandardEditor((uint)__VSOSEFLAGS.OSE_UseOpenWithDialog//(uint)__VSOSEFLAGS.OSE_ChooseBestStdEditor , GetMkDocument() , ref logicalView /* VSConstants.LOGVIEWID.Code_guid for xml behind*/ , Caption , this.ProjectMgr , this.ID // TODO pass docData!!!! , docDataExisting , this.ProjectMgr.Site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider , out frame); } else { __VSOSEFLAGS openFlags = 0; if (newFile) { openFlags |= __VSOSEFLAGS.OSE_OpenAsNewFile; } openFlags |= __VSOSEFLAGS.OSE_ChooseBestStdEditor; if (editorType != Guid.Empty) { result = sod.OpenSpecificEditor(editorFlags , fullPath , ref editorType , physicalView , ref logicalView , Caption , this.ProjectMgr , this.ID , docDataExisting , this.ProjectMgr.Site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider , out frame); } else { result = sod.OpenStandardEditor((uint)openFlags , GetMkDocument() , ref logicalView /* VSConstants.LOGVIEWID.Code_guid for xml behind*/ , Caption , this.ProjectMgr , this.ID , docDataExisting , this.ProjectMgr.Site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider , out frame); } } if (result != VSConstants.S_OK && result != VSConstants.S_FALSE && result != VSConstants.OLE_E_PROMPTSAVECANCELLED) { ErrorHandler.ThrowOnFailure(result); } // eventually show window if (frame != null) { object var; if (newFile) { ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var)); IVsPersistDocData persistDocData = (IVsPersistDocData)var; ErrorHandler.ThrowOnFailure(persistDocData.SetUntitledDocPath(fullPath)); } var = null; ErrorHandler.ThrowOnFailure(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var)); this.DocCookie = (uint)(int)var; if (windowFrameAction == WindowFrameShowAction.Show) { ErrorHandler.ThrowOnFailure(frame.Show()); } else if (windowFrameAction == WindowFrameShowAction.ShowNoActivate) { ErrorHandler.ThrowOnFailure(frame.ShowNoActivate()); } else if (windowFrameAction == WindowFrameShowAction.Hide) { ErrorHandler.ThrowOnFailure(frame.Hide()); } } } // file is already open else { ObjectBuilder = Marshal.GetObjectForIUnknown(docDataExisting) as ObjectBuilder; Marshal.Release(docDataExisting); if (frame != null) { if (windowFrameAction == WindowFrameShowAction.Show) { ErrorHandler.ThrowOnFailure(frame.Show()); } else if (windowFrameAction == WindowFrameShowAction.ShowNoActivate) { ErrorHandler.ThrowOnFailure(frame.ShowNoActivate()); } else if (windowFrameAction == WindowFrameShowAction.Hide) { ErrorHandler.ThrowOnFailure(frame.Hide()); } } } } catch (COMException e) { Trace.WriteLine("Exception e:" + e.Message); result = e.ErrorCode; CloseWindowFrame(ref frame); } } return result; }
private void SelectNodeWithProperties(CFGNode node) { IVsWindowFrame frame = null; if (frame == null) { var shell = _parent.GetVsService(typeof(SVsUIShell)) as IVsUIShell; if (shell != null) { var guidPropertyBrowser = new Guid(ToolWindowGuids.PropertyBrowser); shell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fForceCreate, ref guidPropertyBrowser, out frame); } } if (frame != null) { frame.Show(); } var selContainer = new Microsoft.VisualStudio.Shell.SelectionContainer(); var items = new List <CFGNode>(); items.Add(node); selContainer.SelectedObjects = items; ITrackSelection track = _parent.GetVsService(typeof(STrackSelection)) as ITrackSelection; if (track != null) { track.OnSelectChange(selContainer); } if ((Keyboard.Modifiers & ModifierKeys.Control) > 0) { // If control is pressed then to nothing } else { foreach (var v in GraphControl.Graph.Vertices) { if (v.IsSelected) { v.Deselect(); } } DecorateVerticesBackground(); } IVsStatusbar statusBar = (IVsStatusbar)_parent.GetVsService(typeof(SVsStatusbar)); // 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(node.MethodName + " (" + node.SourceCodeMappingString + ")"); // Freeze the status bar. statusBar.FreezeOutput(1); }
private int Open(bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr docDataExisting, out IVsWindowFrame windowFrame, WindowFrameShowAction windowFrameAction) { windowFrame = null; if(this.Node == null || this.Node.ProjectMgr == null || this.Node.ProjectMgr.IsClosed) { return VSConstants.E_FAIL; } Debug.Assert(this.Node != null, "No node has been initialized for the document manager"); Debug.Assert(this.Node.ProjectMgr != null, "No project manager has been initialized for the document manager"); Debug.Assert(this.Node is FileNode, "Node is not FileNode object"); int returnValue = VSConstants.S_OK; string caption = this.GetOwnerCaption(); string fullPath = this.GetFullPathForDocument(); // Make sure that the file is on disk before we open the editor and display message if not found if(!((FileNode)this.Node).IsFileOnDisk(true)) { // Inform clients that we have an invalid item (wrong icon) this.Node.OnInvalidateItems(this.Node.Parent); // Bail since we are not able to open the item // Do not return an error code otherwise an internal error message is shown. The scenario for this operation // normally is already a reaction to a dialog box telling that the item has been removed. return VSConstants.S_FALSE; } IVsUIShellOpenDocument uiShellOpenDocument = this.Node.ProjectMgr.Site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; IOleServiceProvider serviceProvider = this.Node.ProjectMgr.Site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider; try { this.Node.ProjectMgr.OnOpenItem(fullPath); int result = VSConstants.E_FAIL; if(openWith) { result = uiShellOpenDocument.OpenStandardEditor((uint)__VSOSEFLAGS.OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } else { __VSOSEFLAGS openFlags = 0; if(newFile) { openFlags |= __VSOSEFLAGS.OSE_OpenAsNewFile; } //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid // of the node being opened, otherwise the debugger doesn't work. if(editorType != Guid.Empty) { result = uiShellOpenDocument.OpenSpecificEditor(editorFlags, fullPath, ref editorType, physicalView, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } else { openFlags |= __VSOSEFLAGS.OSE_ChooseBestStdEditor; result = uiShellOpenDocument.OpenStandardEditor((uint)openFlags, fullPath, ref logicalView, caption, this.Node.ProjectMgr, this.Node.ID, docDataExisting, serviceProvider, out windowFrame); } } if(result != VSConstants.S_OK && result != VSConstants.S_FALSE && result != VSConstants.OLE_E_PROMPTSAVECANCELLED) { ErrorHandler.ThrowOnFailure(result); } if(windowFrame != null) { object var; if(newFile) { ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var)); IVsPersistDocData persistDocData = (IVsPersistDocData)var; ErrorHandler.ThrowOnFailure(persistDocData.SetUntitledDocPath(fullPath)); } var = null; ErrorHandler.ThrowOnFailure(windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocCookie, out var)); this.Node.DocCookie = (uint)(int)var; if(windowFrameAction == WindowFrameShowAction.Show) { ErrorHandler.ThrowOnFailure(windowFrame.Show()); } else if(windowFrameAction == WindowFrameShowAction.ShowNoActivate) { ErrorHandler.ThrowOnFailure(windowFrame.ShowNoActivate()); } else if(windowFrameAction == WindowFrameShowAction.Hide) { ErrorHandler.ThrowOnFailure(windowFrame.Hide()); } } } catch(COMException e) { Trace.WriteLine("Exception e:" + e.Message); returnValue = e.ErrorCode; CloseWindowFrame(ref windowFrame); } return returnValue; }
public static void OpenItem(IServiceProvider site, bool newFile, bool openWith, uint editorFlags, ref Guid editorType, string physicalView, ref Guid logicalView, IntPtr punkDocDataExisting, IVsHierarchy pHierarchy, uint hierarchyId, out IVsWindowFrame windowFrame) { windowFrame = null; IntPtr docData = punkDocDataExisting; try { uint itemid = hierarchyId; object pvar; pHierarchy.GetProperty(hierarchyId, (int)__VSHPROPID.VSHPROPID_Caption, out pvar); string caption = (string)pvar; string fullPath = null; if (punkDocDataExisting != IntPtr.Zero && punkDocDataExisting.ToInt64() != -1L) { fullPath = VsShell.GetFilePath(punkDocDataExisting); } if (fullPath == null) { string dir; pHierarchy.GetProperty((uint)VsConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectDir, out pvar); dir = (string)pvar; pHierarchy.GetProperty(hierarchyId, (int)__VSHPROPID.VSHPROPID_SaveName, out pvar); // todo: what if the path is a URL? fullPath = dir != null ? Path.Combine(dir,(string)pvar) : (string)pvar; } HierarchyNode node = pHierarchy as HierarchyNode; IVsUIHierarchy pRootHierarchy = node == null ? (IVsUIHierarchy) pHierarchy : node.projectMgr; IVsUIHierarchy pVsUIHierarchy = pRootHierarchy; IVsUIShellOpenDocument doc = site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument; const uint OSE_ChooseBestStdEditor = 0x20000000; const uint OSE_UseOpenWithDialog = 0x10000000; const uint OSE_OpenAsNewFile = 0x40000000; if (openWith) { IOleServiceProvider psp = site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider; doc.OpenStandardEditor(OSE_UseOpenWithDialog, fullPath, ref logicalView, caption, pVsUIHierarchy, itemid, docData, psp, out windowFrame); } else { // First we see if someone else has opened the requested view of the file. IVsRunningDocumentTable pRDT = site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (pRDT != null) { uint docCookie; IVsHierarchy ppIVsHierarchy; pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, fullPath, out ppIVsHierarchy, out itemid, out docData, out docCookie); if (ppIVsHierarchy != null && docCookie != VsConstants.VSDOCCOOKIE_NIL && pHierarchy != ppIVsHierarchy && pVsUIHierarchy != ppIVsHierarchy) { // not opened by us, so call IsDocumentOpen with the right IVsUIHierarchy so we avoid the // annoying "This document is opened by another project" message prompt. pVsUIHierarchy = (IVsUIHierarchy)ppIVsHierarchy; itemid = (uint)VsConstants.VSITEMID_SELECTION; } ppIVsHierarchy = null; } IVsUIHierarchy ppHierOpen; uint[] pitemidOpen = new uint[1]; int pfOpen; doc.IsDocumentOpen(pVsUIHierarchy, itemid, fullPath, ref logicalView, (uint)__VSIDOFLAGS.IDO_ActivateIfOpen, out ppHierOpen, pitemidOpen, out windowFrame, out pfOpen); if (pfOpen == 1 && editorType != Guid.Empty) { if (windowFrame != null) { Guid currentEditor; windowFrame.GetGuidProperty((int)__VSFPROPID.VSFPROPID_guidEditorType, out currentEditor); if (currentEditor == editorType) { goto done; } } windowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_PromptSave); windowFrame = null; pfOpen = 0; } if (pfOpen != 1) { uint openFlags = 0; if (newFile) openFlags |= OSE_OpenAsNewFile; //NOTE: we MUST pass the IVsProject in pVsUIHierarchy and the itemid // of the node being opened, otherwise the debugger doesn't work. IOleServiceProvider psp = site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider; if (editorType != Guid.Empty) { doc.OpenSpecificEditor(editorFlags, fullPath, ref editorType, physicalView, ref logicalView, caption, pRootHierarchy, hierarchyId, docData, psp, out windowFrame); } else { openFlags |= OSE_ChooseBestStdEditor; doc.OpenStandardEditor(openFlags, fullPath, ref logicalView, caption, pRootHierarchy, hierarchyId, docData, psp, out windowFrame); } if (windowFrame != null) { if (newFile) { object var; windowFrame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out var); IVsPersistDocData ppd = (IVsPersistDocData)var; ppd.SetUntitledDocPath(fullPath); } } } } done: if (windowFrame != null) windowFrame.Show(); } catch (COMException e) { if ((uint)e.ErrorCode != (uint)OleErrors.OLE_E_PROMPTSAVECANCELLED) { #if DEBUG MessageBox.Show(e.Message); #endif } } catch (Exception e) { if (e != null) { #if DEBUG MessageBox.Show(e.Message); #endif } if (docData != punkDocDataExisting && docData != IntPtr.Zero) { Marshal.Release(docData); } } }