/// <summary> /// Gets IVsTextView for a file /// </summary> /// <param name="file">File path</param> /// <param name="forceOpen">Whether the file should be opened, if it's closed</param> /// <param name="activate">Whether the window frame should be activated (focused)</param> public static IVsTextView GetTextViewForFile(string file, bool forceOpen, bool activate) { if (string.IsNullOrEmpty(file)) { throw new ArgumentNullException("file"); } IVsWindowFrame frame = GetWindowFrameForFile(file, forceOpen); if (frame != null) { if (forceOpen || activate) { frame.Show(); } if (activate) { VsShellUtilities.GetWindowObject(frame).Activate(); } return(VsShellUtilities.GetTextView(frame)); } else { throw new Exception("Cannot get window frame for " + file); } }
/// <summary> /// Closes all invisible windows /// </summary> public static void CloseInvisibleWindows(object ofAuthor, bool saveIfClosed) { List <string> toDelete = new List <string>(); try { suppressFileClosedEvent = true; foreach (var pair in invisibleWindows) { if (pair.Value == ofAuthor || ofAuthor == null) { IVsWindowFrame frame = GetWindowFrameForFile(pair.Key, false); if (frame != null) { var window = VsShellUtilities.GetWindowObject(frame); if (!window.Visible) { try { window.Detach(); } catch { } window.Close(saveIfClosed ? vsSaveChanges.vsSaveChangesYes : vsSaveChanges.vsSaveChangesNo); VLOutputWindow.VisualLocalizerPane.WriteLine("\tClosing invisible window: " + Path.GetFileName(pair.Key)); } } toDelete.Add(pair.Key); } } foreach (string path in toDelete) { invisibleWindows.Remove(path); } } finally { suppressFileClosedEvent = false; } }
public static void SelectSpanInCodeWindow(FileLinePositionSpan span) { // If the path is not available we cannot jump to it if (string.IsNullOrEmpty(span.Path)) { return; } // Check if the document is opened, if not open it. IVsUIHierarchy hierarchy; uint itemId; IVsWindowFrame windowFrame; if (!VsShellUtilities.IsDocumentOpen(ServiceProvider.GlobalProvider, span.Path, VSConstants.LOGVIEWID_Any, out hierarchy, out itemId, out windowFrame)) { VsShellUtilities.OpenDocument(ServiceProvider.GlobalProvider, span.Path, VSConstants.LOGVIEWID_Primary, out hierarchy, out itemId, out windowFrame); } var window = VsShellUtilities.GetWindowObject(windowFrame); window.SetFocus(); var textView = VsShellUtilities.GetTextView(windowFrame); textView.SetSelection(span.StartLinePosition.Line, span.StartLinePosition.Character, span.EndLinePosition.Line, span.EndLinePosition.Character); }
/// <summary> /// Opens the file item in the specified view. /// </summary> /// <param name="ViewKind">Specifies the view kind in which to open the item (file)</param> /// <returns>Window object</returns> public override EnvDTE.Window Open(string viewKind) { return(UIThread.DoOnUIThread(delegate() { if (this.Node == null || this.Node.ProjectMgr == null || this.Node.ProjectMgr.IsClosed || this.Node.ProjectMgr.Site == null) { throw new InvalidOperationException(); } IVsWindowFrame windowFrame = null; IntPtr docData = IntPtr.Zero; using (AutomationScope scope = new AutomationScope(this.Node.ProjectMgr.Site)) { try { // Validate input params Guid logicalViewGuid = VSConstants.LOGVIEWID_Primary; try { if (!(String.IsNullOrEmpty(viewKind))) { logicalViewGuid = new Guid(viewKind); } } catch (FormatException) { // Not a valid guid throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidGuid, CultureInfo.CurrentUICulture), "viewKind"); } uint itemid; IVsHierarchy ivsHierarchy; uint docCookie; IVsRunningDocumentTable rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; Debug.Assert(rdt != null, " Could not get running document table from the services exposed by this project"); if (rdt == null) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.Node.Url, out ivsHierarchy, out itemid, out docData, out docCookie)); // Open the file using the IVsProject3 interface ErrorHandler.ThrowOnFailure(this.Node.ProjectMgr.OpenItem(this.Node.ID, ref logicalViewGuid, docData, out windowFrame)); } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } } // Get the automation object and return it return ((windowFrame != null) ? VsShellUtilities.GetWindowObject(windowFrame) : null); })); }
public static EnvDTE.Window dte_Window(this ToolWindowPane toolWindowPane) { return(new VisualStudio_2010().invokeOnThread( () => { IVsWindowFrame windowFrame = (IVsWindowFrame)toolWindowPane.Frame; return VsShellUtilities.GetWindowObject(windowFrame); })); }
/// <summary> /// Opens the file item in the specified view. /// </summary> /// <param name="ViewKind">Specifies the view kind in which to open the item (file)</param> /// <returns>Window object</returns> public override EnvDTE.Window Open(string viewKind) { CheckProjectIsValid(); IVsWindowFrame windowFrame = null; var docData = IntPtr.Zero; using (var scope = new AutomationScope(this.Node.ProjectMgr.Site)) { this.Node.ProjectMgr.Site.GetUIThread().Invoke(() => { try { // Validate input params var logicalViewGuid = VSConstants.LOGVIEWID_Primary; try { if (!(string.IsNullOrEmpty(viewKind))) { logicalViewGuid = new Guid(viewKind); } } catch (FormatException) { // Not a valid guid throw new ArgumentException(SR.GetString(SR.ParameterMustBeAValidGuid), "viewKind"); } uint itemid; IVsHierarchy ivsHierarchy; uint docCookie; var rdt = this.Node.ProjectMgr.Site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable; if (rdt == null) { throw new InvalidOperationException("Could not get running document table from the services exposed by this project"); } ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.Node.Url, out ivsHierarchy, out itemid, out docData, out docCookie)); // Open the file using the IVsProject interface // We get the outer hierarchy so that projects can customize opening. var project = this.Node.ProjectMgr.GetOuterInterface <IVsProject>(); ErrorHandler.ThrowOnFailure(project.OpenItem(this.Node.ID, ref logicalViewGuid, docData, out windowFrame)); } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); } } }); } // Get the automation object and return it return((windowFrame != null) ? VsShellUtilities.GetWindowObject(windowFrame) : null); }
public int OnBeforeDocumentWindowShow(uint docCookie, int fFirstShow, IVsWindowFrame pFrame) { if (VSGestureService.Current.VSGestureInfo.UserSettings.EnableVSGesture == false) { return(VSConstants.S_OK); } var win = VsShellUtilities.GetWindowObject(pFrame); if (win == null) { return(VSConstants.S_OK); } var view = VsShellUtilities.GetTextView(pFrame); if (view == null) { return(VSConstants.S_OK); } IDesignerHost host = win.Object as IDesignerHost; var handler = view.GetWindowHandle(); var hwnd = handler; if (list.ContainsKey(hwnd) == true) { return(VSConstants.S_OK); } GestureNativeWindow window = new GestureNativeWindow(hwnd); list.Add(hwnd, window); if (VSGestureService.Current.VSGestureInfo.UserSettings.EnableVSGestureAlram == true) { // Welcome 메시지 VSGesture.Controls.frmWelcome frm = new Umc.Core.Tools.VSGesture.Controls.frmWelcome(); frm.ShowInTaskbar = false; frm.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; frm.Show(); VSGestureService.Current.VSGestureInfo.UserSettings.EnableVSGestureAlram = false; VSGestureService.Current.VSGestureInfo = VSGestureService.Current.VSGestureInfo; } return(VSConstants.S_OK); }
/// <summary> /// Closes the window of edited file /// </summary> public static void CloseFile(string path) { if (path == null) { throw new ArgumentNullException("path"); } var window = VsShellUtilities.GetWindowObject(GetWindowFrameForFile(path, false)); try { window.Detach(); } catch { } window.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo); }
// returns the Document associated with the given IVsWindowFrame // public static Document DocumentFromWindowFrame(IVsWindowFrame wf) { ThreadHelper.ThrowIfNotOnUIThread(); var w = VsShellUtilities.GetWindowObject(wf); if (w == null) { return(null); } return(w.Document); }
private void HostCSharpEditor() { if (_TextViewHost == null) { InitializeEditor(_CurrentScriptName); } if (_childWindowFrame != null) { //because VsShellUtilities.OpenDocumentWithSpecificEditor call Show, i should cause hide, before changing parent _childWindowFrame.Hide(); var window = VsShellUtilities.GetWindowObject(parentWindowFrame); _childWindowFrame.SetProperty((int)__VSFPROPID2.VSFPROPID_ParentHwnd, window.HWnd); _childWindowFrame.SetProperty((int)__VSFPROPID2.VSFPROPID_ParentFrame, parentWindowFrame); } }
/// <summary> Get all known <see cref="IVsWindowFrame"/>, lazily, that are active/on-screen. </summary> private Dictionary <Window, IVsWindowFrame> GetActiveWindowToFramesLookup(Window activeWindow) { var actives = from frame in GetFrames() let window = VsShellUtilities.GetWindowObject(frame) where window != null where (frame as WindowFrame)?.OnScreen == true || window == activeWindow select new { window, frame }; var windowToFrameLookup = new Dictionary <Window, IVsWindowFrame>(); foreach (var active in actives) { windowToFrameLookup[active.window] = active.frame; } return(windowToFrameLookup); }
/// <summary> /// Returns true if the file's editor window is visible /// </summary> public static bool IsFileVisible(string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentNullException("path"); } IVsWindowFrame frame = DocumentViewsManager.GetWindowFrameForFile(path, false); if (frame == null) { return(false); } Window win = VsShellUtilities.GetWindowObject(frame); if (win == null) { return(false); } return(win.Visible); }
/// <summary> /// Generic test for the "(selection)" commands /// </summary> /// <param name="target">Command to process</param> /// <param name="file">File path</param> /// <param name="view"></param> /// <param name="lines"></param> /// <param name="getExpected">Function that returns list of expected results for specified file path</param> protected void GenericSelectionTest(AbstractBatchCommand_Accessor target, string file, IVsTextView view, IVsTextLines lines, Func <string, List <AbstractResultItem> > getExpected) { Agent.EnsureSolutionOpen(); int lineCount; lines.GetLineCount(out lineCount); Random rnd = new Random(); for (int i = 0; i < 20; i++) { // initialize selection range int beginLine = rnd.Next(lineCount); int endLine = beginLine + rnd.Next(Math.Min(lineCount, beginLine + i) - beginLine); int beginLineLength, endLineLength; lines.GetLengthOfLine(beginLine, out beginLineLength); lines.GetLengthOfLine(endLine, out endLineLength); int beginColumn = rnd.Next(beginLineLength); int endColumn = beginLine == endLine ? beginColumn + (rnd.Next(Math.Min(endLineLength, beginColumn + i) - beginColumn)) : rnd.Next(endLineLength); if (beginLine == endLine && beginColumn == endColumn) { endColumn++; } // set the selection view.SetSelection(beginLine, beginColumn, endLine, endColumn); target.InitializeSelection(); // obtain the list of expected results List <AbstractResultItem> expectedList = new List <AbstractResultItem>(); foreach (AbstractResultItem expected in getExpected(file)) { if (!target.IsItemOutsideSelection(expected)) { expectedList.Add(expected); } } // run the command target.ProcessSelection(true); // compare the results if (target is BatchMoveCommand_Accessor) { ValidateResults(expectedList, (target as BatchMoveCommand_Accessor).Results); } else if (target is BatchInlineCommand_Accessor) { ValidateResults(expectedList, (target as BatchInlineCommand_Accessor).Results); } else { Assert.Fail("Unkown parent command type"); } Assert.IsTrue(expectedList.Count == 0 || VLDocumentViewsManager.IsFileLocked(file)); VLDocumentViewsManager.ReleaseLocks(); Assert.IsFalse(VLDocumentViewsManager.IsFileLocked(file)); } // close the window Window win = VsShellUtilities.GetWindowObject(VLDocumentViewsManager.GetWindowFrameForFile(file, false)); win.Detach(); win.Close(vsSaveChanges.vsSaveChangesNo); }
private void EnsureControl(SolutionExplorerWindow solutionExplorerWindow) { if (_treeViewControl != null && _treeViewControl.IsValid) { return; } EnvDTE.Window window; try { window = VsShellUtilities.GetWindowObject(solutionExplorerWindow.SolutionExplorerFrame); } catch (COMException) { return; } string expCaption = window.Caption; IntPtr handle = IntPtr.Zero; if (window.HWnd != 0) { // We've got the parent handle = (IntPtr)window.HWnd; } else { EnvDTE.Window hostWindow = window.LinkedWindowFrame; if (hostWindow != null) { handle = SearchForSolutionExplorer((IntPtr)hostWindow.HWnd, expCaption); } if (handle == IntPtr.Zero) { hostWindow = window.DTE.MainWindow; if (hostWindow != null) { handle = SearchForSolutionExplorer((IntPtr)hostWindow.HWnd, expCaption); } } if (handle == IntPtr.Zero) { handle = SearchFloatingPalettes(expCaption); } } if (handle == IntPtr.Zero) { return; // Not found :( } IntPtr uiHierarchy = NativeMethods.FindWindowEx(handle, IntPtr.Zero, UIHIERARCHY, null); IntPtr treeHwnd = NativeMethods.FindWindowEx(uiHierarchy, IntPtr.Zero, TREEVIEW, null); if (treeHwnd == IntPtr.Zero) { return; } this._treeViewControl = new Win32TreeView(treeHwnd); }
/// <summary> /// Generic test method /// </summary> /// <param name="openFiles">True if the files should be opened first</param> /// <param name="fullName">True if the "Use full names" policy should be applied</param> /// <param name="mark">True if the "Mark with VL_NO_LOC policy should be applied"</param> /// <param name="testFiles">Files to test</param> /// <param name="targetFiles">ResX files where resources can be moved</param> private void InternalFileMoveTest(bool openFiles, bool fullName, bool mark, string[] testFiles, string[] targetFiles) { // backup the files Dictionary <string, string> backups = CreateBackupsOf(testFiles); // run the "batch move" command to get result items List <CodeStringResultItem> items = BatchMoveLookup(testFiles); // open the necessary files SetFilesOpened(testFiles, openFiles); // initialize ResX destination files Dictionary <string, ResXProjectItem> resxItems = InitResxItems(targetFiles, Agent.GetDTE().Solution.FindProjectItem(testFiles[0]).ContainingProject); // initialize the "batch move" tool window and grid Dictionary <ResXProjectItem, int> resxCounts; Dictionary <ProjectItem, int> sourceItemCounts; int expectedToBeMarked; BatchMoveToResourcesToolWindow_Accessor window = InitBatchToolWindow(resxItems.Values.ToList(), items, fullName, mark, out resxCounts, out sourceItemCounts, out expectedToBeMarked); try { // execute window.RunClick(null, null); VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchMoveCommand), false); // verify every ResX file contains the correct number of resources foreach (ResXProjectItem target in resxItems.Values) { Assert.AreEqual(resxCounts.ContainsKey(target) ? resxCounts[target] : 0, GetResourcesCountIn(target)); } // run the "inline" command to verify all references are valid int checkedCount = resxCounts.Sum((pair) => { return(pair.Value); }); List <CodeReferenceResultItem> inlineResults = BatchInlineLookup(testFiles); VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchInlineCommand), false); Assert.AreEqual(checkedCount, inlineResults.Count); // test if every unchecked string result item was marked if (mark) { int markedAfter = BatchMoveLookup(testFiles).Count((item) => { return(item.IsMarkedWithUnlocalizableComment); }); VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchMoveCommand), false); Assert.AreEqual(expectedToBeMarked, markedAfter, "mark"); } // test if qualified name was really used if (fullName) { foreach (var result in inlineResults) { AspNetCodeReferenceResultItem citem = result as AspNetCodeReferenceResultItem; if (citem == null || !citem.ComesFromWebSiteResourceReference) { Assert.AreEqual(result.OriginalReferenceText, result.FullReferenceText); } } } // check if no import statement has been added twice foreach (string path in testFiles) { CheckForDuplicateUsings(path); } if (openFiles) { // use undo manager to revert the changes foreach (string file in testFiles) { var win = VsShellUtilities.GetWindowObject(VLDocumentViewsManager.GetWindowFrameForFile(file, false)); ProjectItem pitem = Agent.GetDTE().Solution.FindProjectItem(file); int count = sourceItemCounts.ContainsKey(pitem) ? sourceItemCounts[pitem] : 0; IOleUndoManager manager; VLDocumentViewsManager.GetTextLinesForFile(file, false).GetUndoManager(out manager); List <IOleUndoUnit> list = manager.RemoveTopFromUndoStack(count); foreach (AbstractUndoUnit unit in list) { unit.Undo(); } Assert.AreEqual(File.ReadAllText(backups[file]), File.ReadAllText(file)); } // check that all changes were fully reverted int sum = resxItems.Values.Sum((item) => { return(GetResourcesCountIn(item)); }); Assert.AreEqual(0, sum); } } finally { // close the files SetFilesOpened(testFiles, false); // restore the backups RestoreBackups(backups); // clear ResX files foreach (ResXProjectItem target in resxItems.Values) { ClearFile(target); } VLDocumentViewsManager.CloseInvisibleWindows(typeof(BatchMoveCommand), false); } }
public void Capture() { if (SEViewControl != null && SEViewControl.IsValid) { return; } EnvDTE.Window window; try { SolutionExplorer = FindSolutionExplorerFrame(); window = VsShellUtilities.GetWindowObject(SolutionExplorer); } catch (COMException) { // for VS2010 - WPF Shell compatibility (we cannot find the solution explorer frame there) return; } string expCaption = window.Caption; IntPtr handle = IntPtr.Zero; if (window.HWnd != IntPtr.Zero) { // We've got the parent handle = (IntPtr)window.HWnd; } else { EnvDTE.Window hostWindow = window.LinkedWindowFrame; if (hostWindow != null) { handle = FindSolutionExplorerWnd((IntPtr)hostWindow.HWnd, expCaption); } if (handle == IntPtr.Zero) { hostWindow = window.DTE.MainWindow; if (hostWindow != null) { handle = FindSolutionExplorerWnd((IntPtr)hostWindow.HWnd, expCaption); } } if (handle == IntPtr.Zero) { handle = FindInVBFloatingPalettes(expCaption); } } if (handle == IntPtr.Zero) { return; // Not found :( } IntPtr uiHierarchy = NativeTreeView.FindWindowEx(handle, IntPtr.Zero, UIHIERARCHY, null); IntPtr treeHwnd = NativeTreeView.FindWindowEx(uiHierarchy, IntPtr.Zero, TREEVIEW, null); if (treeHwnd == IntPtr.Zero) { return; } SEViewControl = new NativeTreeView(treeHwnd); SetGlyphs(); }
private void SetMergeDiffWindowsToFloatOnly() { if (vMergePackage.MergeToolWindowIsVisible) { return; } IVsWindowFrame[] frames = new IVsWindowFrame[1]; uint numFrames; IEnumWindowFrames ppenum; UIShell.GetDocumentWindowEnum(out ppenum); while (ppenum.Next(1, frames, out numFrames) == VSConstants.S_OK && numFrames == 1) { var frame = frames[0] as IVsWindowFrame; object title; frame.GetProperty((int)__VSFPROPID.VSFPROPID_Caption, out title); var window = VsShellUtilities.GetWindowObject(frame); if (window.Caption.StartsWith("Merge - ") || window.Caption.StartsWith("Diff - ")) { if (!_attachedFrames.ContainsKey(frame)) { window.IsFloating = true; var windowEvents = new ToolWindowEvents(frame); windowEvents.OnDockableChange = (fDockable, x, y, w, h) => { if (_attachedFrames.ContainsKey(frame) && !_attachedFrames[frame]) { try { _attachedFrames[frame] = true; if (fDockable) { window.IsFloating = true; } } catch (Exception) { } finally { _attachedFrames[frame] = false; } } return(VSConstants.S_OK); }; windowEvents.OnClose = (options) => { windowEvents.OnDockableChange = null; windowEvents.OnClose = null; _attachedFrames.Remove(frame); windowEvents.Dispose(); return(VSConstants.S_OK); }; try { frame.SetProperty((int)__VSFPROPID.VSFPROPID_ViewHelper, windowEvents); _attachedFrames[frame] = false; } catch (Exception ex) { SimpleLogger.Log(ex, true); } } } } }