Example #1
0
        internal static bool IsDirty(IVsPersistDocData docData)
        {
            int pfDirty;

            ErrorHandler.ThrowOnFailure(docData.IsDocDataDirty(out pfDirty));
            return(pfDirty > 0);
        }
Example #2
0
        // ----------------------------------------------------------------------------------
        /// <summary>
        /// Initialize the editor
        /// </summary>
        // ----------------------------------------------------------------------------------
        private void InitializeEditor(string scriptName)
        {
            Guid guid_microsoft_csharp_editor = new Guid("{A6C744A8-0E4A-4FC6-886A-064283054674}");
            Guid guid_microsoft_csharp_editor_with_encoding = new Guid("{08467b34-b90f-4d91-bdca-eb8c8cf3033a}");
            Guid editorType      = guid_microsoft_csharp_editor;// VSConstants.VsEditorFactoryGuid.TextEditor_guid;
            Guid logicalViewGuid = Microsoft.VisualStudio.VSConstants.LOGVIEWID.Primary_guid;

            IVsWindowFrame ppWindowFrame = null;

            try
            {
                var psp      = (System.IServiceProvider)ReplEditorPackage.CurrentPackage;
                var fileName = System.IO.Path.Combine(VSTools.ScriptsDirectory, scriptName);
                ppWindowFrame = Microsoft.VisualStudio.Shell.VsShellUtilities.OpenDocumentWithSpecificEditor(psp, fileName, editorType, logicalViewGuid);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("REPLException : " + ex.ToString());
                //System.Windows.MessageBox.Show(ex.ToString());
            }
            if (ppWindowFrame != null)
            {
                _ViewAdapter          = VsShellUtilities.GetTextView(ppWindowFrame);
                _childWindowFrame     = ppWindowFrame;
                _TextViewHost         = _EditorAdapterFactory.GetWpfTextViewHost(_ViewAdapter);
                _docData              = VSTools.GetPersistDocData(_TextViewHost);
                this.leftSide.Content = _TextViewHost;
            }
        }
Example #3
0
        ///-------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Returns the current contents of a document
        /// </summary>
        ///-------------------------------------------------------------------------------------------------------------
        public string GetDocumentText()
        {
            string            text    = null;
            IVsPersistDocData docData = null;

            try
            {
                // Get or create the buffer
                IVsTextLines buffer = GetRunningDocumentTextBuffer();
                if (buffer == null)
                {
                    docData = CreateDocumentData();
                    buffer  = docData as IVsTextLines;
                }

                // get the text from the buffer
                if (buffer != null)
                {
                    IVsTextStream textStream = buffer as IVsTextStream;
                    if (textStream != null)
                    {
                        int length;
                        int hr = textStream.GetSize(out length);
                        if (ErrorHandler.Succeeded(hr))
                        {
                            if (length > 0)
                            {
                                IntPtr pText = Marshal.AllocCoTaskMem((length + 1) * 2);
                                try
                                {
                                    hr = textStream.GetStream(0, length, pText);
                                    if (ErrorHandler.Succeeded(hr))
                                    {
                                        text = Marshal.PtrToStringUni(pText);
                                    }
                                }
                                finally
                                {
                                    Marshal.FreeCoTaskMem(pText);
                                }
                            }
                            else
                            {
                                text = string.Empty;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (docData != null)
                {
                    docData.Close();
                }
            }

            return(text);
        }
Example #4
0
 private static bool IsDirty(IVsPersistDocData pdd)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     if (pdd.IsDocDataDirty(out int result) == VSConstants.S_OK)
     {
         return(result > 0);
     }
     return(true);
 }
Example #5
0
        public void Suspend()
        {
            if (this.fSuspending)
            {
                return;
            }

            try  {
                IVsRunningDocumentTable pRDT = (IVsRunningDocumentTable)this.site.QueryService(VsConstants.SID_SVsRunningDocumentTable, typeof(IVsRunningDocumentTable));
                IntPtr          docData;
                IVsHierarchy    pIVsHierarchy;
                uint            itemId;
                uint            uiVsDocCookie;
                IVsFileChangeEx vsFileChange;


                if (pRDT == null)
                {
                    return;
                }

                pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock,
                                         this.strDocumentFileName, out pIVsHierarchy, out itemId,
                                         out docData, out uiVsDocCookie);

                if ((uiVsDocCookie == VsConstants.VSDOCCOOKIE_NIL) || docData == IntPtr.Zero)
                {
                    return;
                }

                vsFileChange = (IVsFileChangeEx)this.site.QueryService(VsConstants.SID_SVsFileChangeEx, typeof(IVsFileChangeEx));

                if (vsFileChange != null)
                {
                    this.fSuspending = true;
                    vsFileChange.IgnoreFile(0, this.strDocumentFileName, (int)1);
                    if (docData != IntPtr.Zero)
                    {
                        try  {
                            // if interface is not supported, return null
                            IVsPersistDocData ppIVsPersistDocData = (IVsPersistDocData)Marshal.GetObjectForIUnknown(docData);
                            this.fileChangeControl = (IVsDocDataFileChangeControl)ppIVsPersistDocData;
                            if (this.fileChangeControl != null)
                            {
                                this.fileChangeControl.IgnoreFileChanges(1);
                            }
                        }
                        catch  {
                        };
                    }
                }
            }
            catch  {
            }
            return;
        }
Example #6
0
        internal static void Save(IVsPersistDocData docData)
        {
            int    canceled;
            string newDocumentStateScope;

            if (docData.SaveDocData(VSSAVEFLAGS.VSSAVE_Save, out newDocumentStateScope, out canceled) != VSConstants.S_OK)
            {
                LogDebug("error while saving C# script document");
            }
        }
Example #7
0
        internal static void SaveAs(IWpfTextViewHost host, string oldScriptName, ref string fileName)
        {
            IVsPersistDocData vsPersistDocData = GetPersistDocData(host);

            SaveAs(oldScriptName, ref fileName, ServiceProvider.GlobalProvider);
            if (vsPersistDocData != null)
            {
                Save(vsPersistDocData);
            }
        }
Example #8
0
 private void LoadScript(string scriptName)
 {
     if (_childWindowFrame != null)
     {
         _childWindowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_SaveIfDirty);
     }
     _TextViewHost = null;
     _ViewAdapter  = null;
     _docData      = null;
     HostCSharpEditor();
 }
Example #9
0
        /// <summary>
        /// Gets a value indicating whether this document is reloadable.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is reloadable; otherwise, <c>false</c>.
        /// </value>
        public bool IsReloadable()
        {
            IVsPersistDocData pdd = RawDocument as IVsPersistDocData;

            if (pdd == null)
            {
                return(false);
            }

            int reloadable;

            return(SafeSucceeded(pdd.IsDocDataReloadable, out reloadable) && (reloadable != 0));
        }
Example #10
0
 /// <summary>
 /// Silently saves an open document
 /// </summary>
 /// <param name="saveIfDirty">Save the open document only if it is dirty</param>
 /// <remarks>The call to SaveDocData may return Microsoft.VisualStudio.Shell.Interop.PFF_RESULTS.STG_S_DATALOSS to indicate some characters could not be represented in the current codepage</remarks>
 public virtual void Save(bool saveIfDirty)
 {
     if (saveIfDirty && IsDirty)
     {
         IVsPersistDocData persistDocData = DocData;
         if (persistDocData != null)
         {
             string name;
             int    cancelled;
             ErrorHandler.ThrowOnFailure(persistDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out name, out cancelled));
         }
     }
 }
        private async Task InitializeTextBufferAsync()
        {
            (IVsHierarchy unusedHier, uint unusedId, IVsPersistDocData docData, uint unusedCookie) =
                await _shellUtilities.GetRDTDocumentInfoAsync(_serviceProvider, FilePath).ConfigureAwait(false);

            _docData = docData;

            await _threadingService.SwitchToUIThread();

            _textBuffer = (IVsTextBuffer)_docData;

            var textBufferAdapter = _editorAdaptersService.GetDocumentBuffer(_textBuffer);

            Assumes.True(_textDocumentService.TryGetTextDocument(textBufferAdapter, out _textDocument));
        }
Example #12
0
        /// <summary>
        /// Gets a value indicating whether this document is reloadable.
        /// </summary>
        /// <value>
        ///     <c>true</c> if this instance is reloadable; otherwise, <c>false</c>.
        /// </value>
        public bool IsReloadable()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            IVsPersistDocData pdd = RawDocument as IVsPersistDocData;

            if (pdd == null)
            {
                return(false);
            }

            int reloadable;

            return(SafeSucceeded(pdd.IsDocDataReloadable, out reloadable) && (reloadable != 0));
        }
Example #13
0
        internal static IVsPersistDocData GetPersistDocData(IWpfTextViewHost host)
        {
            var svc = EditorAdaptersFactoryService;

            if (svc == null)
            {
                LogDebug("unable to get service 'EditorAdaptersFactoryService'");
            }
            var          view = svc.GetViewAdapter(host.TextView);
            IVsTextLines vsTextLines;

            ErrorHandler.ThrowOnFailure(view.GetBuffer(out vsTextLines));
            IVsPersistDocData vsPersistDocData = (IVsPersistDocData)vsTextLines;

            return(vsPersistDocData);
        }
        public static bool IsDocumentDirty(string documentPath, out IVsPersistDocData persistDocData)
        {
            var serviceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_dte);

            IVsHierarchy vsHierarchy;
            uint itemId, docCookie;
            VsShellUtilities.GetRDTDocumentInfo(
                serviceProvider, documentPath, out vsHierarchy, out itemId, out persistDocData, out docCookie);
            if (persistDocData != null)
            {
                int isDirty;
                persistDocData.IsDocDataDirty(out isDirty);
                return isDirty == 1;
            }

            return false;
        }
Example #15
0
        /// <summary>
        /// Returns TRUE if open and dirty. Note that documents can be open without a
        /// window frame so be careful. Returns the DocData and doc cookie if requested
        /// </summary>
        /// <param name="document">document path</param>
        /// <param name="pHier">hierarchy</param>
        /// <param name="ppDocData">doc data associated with document</param>
        /// <param name="cookie">item cookie</param>
        /// <returns>True if FIle is dirty</returns>
        private bool VerifyFileDirtyInRdt(string document, out IVsHierarchy pHier, out IVsPersistDocData ppDocData, out uint cookie)
        {
            int ret = 0;

            pHier     = null;
            ppDocData = null;
            cookie    = 0;

            IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;

            if (rdt != null)
            {
                IntPtr       docData  = IntPtr.Zero;
                uint         dwCookie = 0;
                IVsHierarchy srpHier;
                uint         itemid = VSConstants.VSITEMID_NIL;

                try
                {
                    ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, document, out srpHier, out itemid, out docData, out dwCookie));
                    IVsPersistHierarchyItem srpIVsPersistHierarchyItem = srpHier as IVsPersistHierarchyItem;
                    if (srpIVsPersistHierarchyItem != null)
                    {
                        // Found in the RDT. See if it is dirty
                        try
                        {
                            ErrorHandler.ThrowOnFailure(srpIVsPersistHierarchyItem.IsItemDirty(itemid, docData, out ret));
                            cookie    = dwCookie;
                            ppDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData;
                        }
                        finally
                        {
                            pHier = srpHier;
                        }
                    }
                }
                finally
                {
                    if (docData != IntPtr.Zero)
                    {
                        Marshal.Release(docData);
                    }
                }
            }
            return(ret == 1);
        }
Example #16
0
        /// <summary>
        /// Saves the document if it is dirty.
        /// </summary>
        /// <param name="filePath">The absolute path to the file.</param>
        public void SaveIfDirty(string filePath)
        {
            DocumentInfo docInfo = this.FindByPath(filePath);

            if (docInfo != null && docInfo.IsDirty && docInfo.SupportsInterface(typeof(IVsPersistDocData)))
            {
                string            newPath;
                int               saveCanceled;
                IVsPersistDocData persistDocData = docInfo.DocumentData as IVsPersistDocData;
                Tracer.Assert(persistDocData != null, "DocumentInfo.SupportsInterface returned true when it shouldn't have.");
                if (persistDocData != null)
                {
                    int hr = persistDocData.SaveDocData(VSSAVEFLAGS.VSSAVE_SilentSave, out newPath, out saveCanceled);
                    Tracer.WriteLineIf(classType, "SaveIfDirty", Tracer.Level.Information, NativeMethods.Succeeded(hr), "Successfully saved '{0}'.", filePath);
                    NativeMethods.ThrowOnFailure(hr);
                }
            }
        }
        public static bool IsDocumentDirty(string documentPath, out IVsPersistDocData persistDocData)
        {
            var serviceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_dte);

            IVsHierarchy vsHierarchy;
            uint         itemId, docCookie;

            VsShellUtilities.GetRDTDocumentInfo(
                serviceProvider, documentPath, out vsHierarchy, out itemId, out persistDocData, out docCookie);
            if (persistDocData != null)
            {
                int isDirty;
                persistDocData.IsDocDataDirty(out isDirty);
                return(isDirty == 1);
            }

            return(false);
        }
Example #18
0
        ///-------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// If the document is open, it returns the IVsTextLines.
        /// </summary>
        ///-------------------------------------------------------------------------------------------------------------
        public IVsTextLines GetRunningDocumentTextBuffer()
        {
            IVsTextLines buffer = null;

            IVsPersistDocData docData = GetRunningDocumentData();
            if (docData != null)
            {
                buffer = docData as IVsTextLines;
                if (buffer == null)
                {
                    IVsTextBufferProvider provider = docData as IVsTextBufferProvider;
                    if (provider != null)
                    {
                        provider.GetTextBuffer(out buffer);
                    }
                }
            }

            return buffer;
        }
Example #19
0
 ///-------------------------------------------------------------------------------------------------------------
 /// <summary>
 /// Creates and loads the document data
 /// (You must Close() it when done)
 /// </summary>
 ///-------------------------------------------------------------------------------------------------------------
 public IVsPersistDocData CreateDocumentData()
 {
     if (IsFile())
     {
         string fullPath = FullPath();
         if (!string.IsNullOrEmpty(fullPath))
         {
             IOleServiceProvider serviceProvider = (IOleServiceProvider)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(IOleServiceProvider));
             IVsPersistDocData   docData         = WAUtilities.CreateSitedInstance <IVsPersistDocData>(serviceProvider, typeof(VsTextBufferClass).GUID);
             if (docData != null)
             {
                 int hr = docData.LoadDocData(fullPath);
                 if (ErrorHandler.Succeeded(hr))
                 {
                     return(docData);
                 }
             }
         }
     }
     return(null);
 }
Example #20
0
        /// <summary>
        /// Get document properties from RDT
        /// </summary>
        private void GetDocInfo(
            out bool isOpen,       // true if the doc is opened
            out bool isDirty,      // true if the doc is dirty
            out bool isOpenedByUs, // true if opened by our project
            out uint docCookie,    // VSDOCCOOKIE if open
            out IVsPersistDocData persistDocData)
        {
            isOpen         = isDirty = isOpenedByUs = false;
            docCookie      = (uint)ShellConstants.VSDOCCOOKIE_NIL;
            persistDocData = null;

            if (this.node == null || this.node.ProjectMgr == null || this.node.ProjectMgr.IsClosed)
            {
                return;
            }

            IVsHierarchy hierarchy;
            uint         vsitemid = VSConstants.VSITEMID_NIL;

            VsShellUtilities.GetRDTDocumentInfo(this.node.ProjectMgr.Site, this.node.Url, out hierarchy, out vsitemid, out persistDocData, out docCookie);

            if (hierarchy == null || docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL)
            {
                return;
            }

            isOpen = true;
            // check if the doc is opened by another project
            if (Utilities.IsSameComObject(this.node.ProjectMgr, hierarchy))
            {
                isOpenedByUs = true;
            }

            if (persistDocData != null)
            {
                int isDocDataDirty;
                ErrorHandler.ThrowOnFailure(persistDocData.IsDocDataDirty(out isDocDataDirty));
                isDirty = (isDocDataDirty != 0);
            }
        }
Example #21
0
        /// <summary>
        /// Reloads file buffer without displaying a GUI dialog.
        /// </summary>
        public static void SilentlyReloadFile(string path)
        {
            if (string.IsNullOrEmpty(path))
            {
                return;
            }

            IVsHierarchy ppHier;
            uint         pitemid;
            IntPtr       pPunkDocData;
            uint         pdwCookie;
            int          hr = IVsRunningDocumentTable.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, path,
                                                                          out ppHier, out pitemid, out pPunkDocData, out pdwCookie);

            Marshal.ThrowExceptionForHR(hr);

            if (pPunkDocData != IntPtr.Zero)
            {
                IVsPersistDocData d = (IVsPersistDocData)Marshal.GetObjectForIUnknown(pPunkDocData);
                hr = d.ReloadDocData(0);
                Marshal.ThrowExceptionForHR(hr);
            }
        }
Example #22
0
        ///-------------------------------------------------------------------------------------------------------------
        /// <summary>
        /// If the document is open, it returns the IVsPersistDocData for it.
        /// </summary>
        ///-------------------------------------------------------------------------------------------------------------
        public IVsPersistDocData GetRunningDocumentData()
        {
            IVsPersistDocData persistDocData = null;

            IntPtr docData = IntPtr.Zero;
            try
            {
                docData = GetRunningDocData();
                if (docData != IntPtr.Zero)
                {
                    persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData;
                }
            }
            finally
            {
                if (docData != IntPtr.Zero)
                {
                    Marshal.Release(docData);
                }
            }

            return persistDocData;
        }
Example #23
0
        public void Suspend()
        {
            if (this.isSuspending)
            {
                return;
            }

            IntPtr docData = IntPtr.Zero;

            try
            {
                IVsRunningDocumentTable rdt = this.site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;

                IVsHierarchy    hierarchy;
                uint            itemId;
                uint            docCookie;
                IVsFileChangeEx fileChange;


                if (rdt == null)
                {
                    return;
                }

                ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, this.documentFileName, out hierarchy, out itemId, out docData, out docCookie));

                if ((docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL) || docData == IntPtr.Zero)
                {
                    return;
                }

                fileChange = this.site.GetService(typeof(SVsFileChangeEx)) as IVsFileChangeEx;

                if (fileChange != null)
                {
                    this.isSuspending = true;
                    ErrorHandler.ThrowOnFailure(fileChange.IgnoreFile(0, this.documentFileName, (int)1));
                    if (docData != IntPtr.Zero)
                    {
                        IVsPersistDocData persistDocData = null;

                        // if interface is not supported, return null
                        object unknown = Marshal.GetObjectForIUnknown(docData);
                        if (unknown is IVsPersistDocData)
                        {
                            persistDocData = (IVsPersistDocData)unknown;
                            if (persistDocData is IVsDocDataFileChangeControl)
                            {
                                this.fileChangeControl = (IVsDocDataFileChangeControl)persistDocData;
                                if (this.fileChangeControl != null)
                                {
                                    ErrorHandler.ThrowOnFailure(this.fileChangeControl.IgnoreFileChanges(1));
                                }
                            }
                        }
                    }
                }
            }
            catch (InvalidCastException e)
            {
                Trace.WriteLine("Exception" + e.Message);
            }
            finally
            {
                if (docData != IntPtr.Zero)
                {
                    Marshal.Release(docData);
                }
            }
            return;
        }
        // ----------------------------------------------------------------------------------
        /// <summary>
        /// Initialize the editor
        /// </summary>
        // ----------------------------------------------------------------------------------
        private void InitializeEditor(string scriptName)
        {
            Guid guid_microsoft_csharp_editor = new Guid("{A6C744A8-0E4A-4FC6-886A-064283054674}");
            Guid guid_microsoft_csharp_editor_with_encoding = new Guid("{08467b34-b90f-4d91-bdca-eb8c8cf3033a}");
            Guid editorType = guid_microsoft_csharp_editor;// VSConstants.VsEditorFactoryGuid.TextEditor_guid;
            Guid logicalViewGuid = Microsoft.VisualStudio.VSConstants.LOGVIEWID.Primary_guid;

            IVsWindowFrame ppWindowFrame = null;
            try
            {
                var psp = (System.IServiceProvider)ReplEditorPackage.CurrentPackage;
                var fileName = System.IO.Path.Combine(VSTools.ScriptsDirectory, scriptName);
                ppWindowFrame = Microsoft.VisualStudio.Shell.VsShellUtilities.OpenDocumentWithSpecificEditor(psp, fileName, editorType, logicalViewGuid);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("REPLException : " + ex.ToString());
                //System.Windows.MessageBox.Show(ex.ToString());
            }
            if (ppWindowFrame != null)
            {
                _ViewAdapter = VsShellUtilities.GetTextView(ppWindowFrame);
                _childWindowFrame = ppWindowFrame;
                _TextViewHost = _EditorAdapterFactory.GetWpfTextViewHost(_ViewAdapter);
                _docData = VSTools.GetPersistDocData(_TextViewHost);
                this.leftSide.Content = _TextViewHost;
            }
        }
Example #25
0
        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
                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;

            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;
                this.CloseWindowFrame(ref windowFrame);
            }

            return(returnValue);
        }
Example #26
0
        void GetRDTDocumentInfo(string pszDocumentName, out IVsHierarchy ppIVsHierarchy, out uint pitemid, out IVsPersistDocData ppIVsPersistDocData, out uint pVsDocCookie){
            ppIVsHierarchy = null;
            pitemid = VsConstants.VSITEMID_NIL;
            ppIVsPersistDocData = null;
            pVsDocCookie = VsConstants.VSDOCCOOKIE_NIL;
            if (pszDocumentName == null || pszDocumentName == "")
                return;
            // Get the document info.
            IVsRunningDocumentTable pRDT = this.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
            if (pRDT == null) return;

            IntPtr docData;
            pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, pszDocumentName, out ppIVsHierarchy, out pitemid, out docData, out pVsDocCookie);


            if (docData != IntPtr.Zero){
                try{
                    // if interface is not supported, return null
                    ppIVsPersistDocData = (IVsPersistDocData)Marshal.GetObjectForIUnknown(docData);
                } catch{
                }
                ;
            }
        }
Example #27
0
        public void Suspend()
        {
            if (mIsSuspending)
            {
                return;
            }

            mDocData = IntPtr.Zero;
            try
            {
                IVsRunningDocumentTable rdt = mSite.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
                if (rdt == null)
                {
                    return;
                }

                ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, mDocumentFileName,
                                                                    out IVsHierarchy hierarchy, out uint itemId, out mDocData, out uint docCookie));

                if ((docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL) || mDocData == IntPtr.Zero)
                {
                    return;
                }

                IVsFileChangeEx fileChange = mSite.GetService(typeof(SVsFileChangeEx)) as IVsFileChangeEx;
                if (fileChange == null)
                {
                    return;
                }

                mIsSuspending = true;
                ErrorHandler.ThrowOnFailure(fileChange.IgnoreFile(0, mDocumentFileName, 1));
                if (mDocData == IntPtr.Zero)
                {
                    return;
                }

                mPersistDocData = null;
                object unknown = Marshal.GetObjectForIUnknown(mDocData);
                if (!(unknown is IVsPersistDocData))
                {
                    return;
                }

                mPersistDocData = (IVsPersistDocData)unknown;
                if (!(mPersistDocData is IVsDocDataFileChangeControl))
                {
                    return;
                }

                mFileChangeControl = (IVsDocDataFileChangeControl)mPersistDocData;
                if (mFileChangeControl != null)
                {
                    ErrorHandler.ThrowOnFailure(mFileChangeControl.IgnoreFileChanges(1));
                }
            }
            catch (InvalidCastException e)
            {
                Trace.WriteLine("Exception" + e.Message);
            }
            finally
            {
                if (mDocData != IntPtr.Zero)
                {
                    Marshal.Release(mDocData);
                }
            }
        }
Example #28
0
        /// <summary>
        /// Get document properties from RDT
        /// </summary>
        public virtual void GetDocInfo(
			out bool isOpen,     // true if the doc is opened
			out bool isDirty,    // true if the doc is dirty
			out bool isOpenedByUs, // true if opened by our project
			out uint docCookie, // VSDOCCOOKIE if open
			out IVsPersistDocData persistDocData)
        {
            isOpen = isDirty = isOpenedByUs = false;
            docCookie = (uint)ShellConstants.VSDOCCOOKIE_NIL;
            persistDocData = null;

            if(this.node == null || this.node.ProjectManager == null || this.node.ProjectManager.IsClosed)
            {
                return;
            }

            IVsHierarchy hierarchy;
            uint vsitemid = VSConstants.VSITEMID_NIL;

            VsShellUtilities.GetRDTDocumentInfo(this.node.ProjectManager.Site, this.node.Url, out hierarchy, out vsitemid, out persistDocData, out docCookie);

            if(hierarchy == null || docCookie == (uint)ShellConstants.VSDOCCOOKIE_NIL)
            {
                return;
            }

            isOpen = true;
            // check if the doc is opened by another project
            if(Utilities.IsSameComObject(this.node.ProjectManager.InteropSafeIVsHierarchy, hierarchy))
            {
                isOpenedByUs = true;
            }

            if(persistDocData != null)
            {
                int isDocDataDirty;
                ErrorHandler.ThrowOnFailure(persistDocData.IsDocDataDirty(out isDocDataDirty));
                isDirty = (isDocDataDirty != 0);
            }
        }
Example #29
0
        /// <summary>
        /// Returns TRUE if open and dirty. Note that documents can be open without a
        /// window frame so be careful. Returns the DocData and doc cookie if requested
        /// </summary>
        /// <param name="document">document path</param>
        /// <param name="pHier">hierarchy</param>
        /// <param name="ppDocData">doc data associated with document</param>
        /// <param name="cookie">item cookie</param>
        /// <returns>True if FIle is dirty</returns>
        private bool VerifyFileDirtyInRdt(string document, out IVsHierarchy pHier, out IVsPersistDocData ppDocData, out uint cookie)
        {
            int ret = 0;
            pHier = null;
            ppDocData = null;
            cookie = 0;

            IVsRunningDocumentTable rdt = this.projectMgr.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
            if (rdt != null)
            {
                IntPtr docData;
                uint dwCookie = 0;
                IVsHierarchy srpHier;
                uint itemid = VSConstants.VSITEMID_NIL;

                ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, document, out srpHier, out itemid, out docData, out dwCookie));
                IVsPersistHierarchyItem srpIVsPersistHierarchyItem = srpHier as IVsPersistHierarchyItem;
                if (srpIVsPersistHierarchyItem != null)
                {
                    // Found in the RDT. See if it is dirty
                    try
                    {
                        ErrorHandler.ThrowOnFailure(srpIVsPersistHierarchyItem.IsItemDirty(itemid, docData, out ret));
                        cookie = dwCookie;
                        ppDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData;
                    }
                    finally
                    {
                        if (docData != IntPtr.Zero)
                        {
                            Marshal.Release(docData);
                        }

                        pHier = srpHier;
                    }
                }
            }
            return (ret == 1);
        }
Example #30
0
        public static IVsShellUtilitiesHelper ImplementGetRDTInfo(string expectedFilePath, IVsPersistDocData retDocData)
        {
            var utilities = new Mock <IVsShellUtilitiesHelper>(MockBehavior.Strict);

            utilities.Setup(u => u.GetRDTDocumentInfoAsync(It.IsAny <IServiceProvider>(), expectedFilePath))
            .Returns(Task.FromResult <(IVsHierarchy, uint, IVsPersistDocData, uint)>((null, 0, retDocData, 0)));
            return(utilities.Object);
        }
 private void LoadScript(string scriptName)
 {
     if (_childWindowFrame != null)
     {
         _childWindowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_SaveIfDirty);
     }
     _TextViewHost = null;
     _ViewAdapter = null;
     _docData = null;
     HostCSharpEditor();
 }
        /// <include file='doc\VsShellUtilities.uex' path='docs/doc[@for="VsShellUtilities.GetRDTDocumentInfo"]/*' />
        /// <devdoc>
        /// Get a reference to the IVsPersistDocData interface associated to a document in the Running Document Table.
        /// </devdoc>
        /// <param name="site">The service provider.</param>
        /// <param name="documentName">Path to the document.</param>
        /// <param name="hierarchy">[out, optional] Reference to the IVsHierarchy interface for the project who owns the document.</param>
        /// <param name="itemid">[out, optional] Reference to an item identifier in the hierarchy. </param>
        /// <param name="persistDocData">[out] A reference to the IVsPersistDocData interface associated to the document</param>
        /// <param name="docCookie">[out, optional] A reference to an abstract handle to the document. </param>
        public static void GetRDTDocumentInfo(IServiceProvider site, string documentName, out IVsHierarchy hierarchy, out uint itemid, out IVsPersistDocData persistDocData, out uint docCookie)
        {
            hierarchy = null;
            itemid = VSConstants.VSITEMID_NIL;
            persistDocData = null;
            docCookie = (uint)ShellConstants.VSDOCCOOKIE_NIL;

            if (site == null)
            {
                throw new ArgumentException("site");
            }

            if (String.IsNullOrEmpty(documentName))
            {
                throw new ArgumentException("documentName");
            }

            // Get the document info.
            IVsRunningDocumentTable rdt = site.GetService(typeof(IVsRunningDocumentTable)) as IVsRunningDocumentTable;
            if (rdt == null) return;

            IntPtr docData = IntPtr.Zero;
            try
            {
                ErrorHandler.ThrowOnFailure(rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, documentName, out hierarchy, out itemid, out docData, out docCookie));

                if (docData != IntPtr.Zero)
                {
                    // if interface is not supported, return null
                    persistDocData = Marshal.GetObjectForIUnknown(docData) as IVsPersistDocData;
                }
            }
            finally
            {

                if (docData != IntPtr.Zero)
                {
                    Marshal.Release(docData);
                }
            }
        }
Example #33
0
        // File node properties.
        void GetDocInfo(out bool pfOpen,     // true if the doc is opened
                        out bool pfDirty,    // true if the doc is dirty
                        out bool pfOpenByUs, // true if opened by our project
                        out uint pVsDocCookie, out IVsPersistDocData ppIVsPersistDocData){// VSDOCCOOKIE if open
            pfOpen = pfDirty = pfOpenByUs = false;
            pVsDocCookie = VsConstants.VSDOCCOOKIE_NIL;

            IVsHierarchy srpIVsHierarchy;
            uint vsitemid = VsConstants.VSITEMID_NIL;

            GetRDTDocumentInfo(this.FullPath, out srpIVsHierarchy, out vsitemid, out ppIVsPersistDocData, out pVsDocCookie);

            if (srpIVsHierarchy == null || pVsDocCookie == VsConstants.VSDOCCOOKIE_NIL)
                return;

            pfOpen = true;
            // check if the doc is opened by another project
            if ((IVsHierarchy)this == srpIVsHierarchy || (IVsHierarchy)this.projectMgr == srpIVsHierarchy){
                pfOpenByUs = true;
            }

            if (ppIVsPersistDocData != null){
                int pf;
                ppIVsPersistDocData.IsDocDataDirty(out pf);
                pfDirty = (pf != 0);
            }
        }
Example #34
0
 internal static void Save(IVsPersistDocData docData)
 {
     int canceled;
     string newDocumentStateScope;
     if (docData.SaveDocData(VSSAVEFLAGS.VSSAVE_Save, out newDocumentStateScope, out canceled) != VSConstants.S_OK)
     {
         LogDebug("error while saving C# script document");
     }
 }
        public int CreateEditorInstance(
            uint grfCreateDoc,
            string pszMkDocument,
            string pszPhysicalView,
            IVsHierarchy pvHier,
            uint itemid,
            IntPtr punkDocDataExisting,
            out IntPtr ppunkDocView,
            out IntPtr ppunkDocData,
            out string pbstrEditorCaption,
            out Guid pguidCmdUI,
            out int pgrfCDW)
        {
            // Initialize to null
            ppunkDocView       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pbstrEditorCaption = null;
            pguidCmdUI         = GuidList.guidPartEditorFactory;
            pgrfCDW            = (int)_VSRDTFLAGS.RDT_DontSaveAs;

            try
            {
                // Validate inputs
                if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
                {
                    Debug.Assert(false, "Only Open or Silent is valid");
                    return(VSConstants.E_INVALIDARG);
                }

                PackageEditorPane existingPackageEditor = null;
                if (punkDocDataExisting != IntPtr.Zero)
                {
                    existingPackageEditor = Marshal.GetObjectForIUnknown(punkDocDataExisting) as PackageEditorPane;
                    if (existingPackageEditor == null)
                    {
                        // The user is trying to open our editor on an existing DocData which is not our editor.
                        // This editor does not support other editors simultaneously editing the same file.
                        return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                    }
                }

                if (pszPhysicalView == null)
                {
                    if (punkDocDataExisting != IntPtr.Zero)
                    {
                        // An XML fragment editor was already editing our DocData, and we are trying to open the main editor on it now.
                        // Just return the existing DocData object.
                        ppunkDocView       = Marshal.GetIUnknownForObject(existingPackageEditor);
                        ppunkDocData       = Marshal.GetIUnknownForObject(existingPackageEditor);
                        pbstrEditorCaption = string.Empty;
                        return(VSConstants.S_OK);
                    }
                    // Open the main editor (the normal scenario).
                    PackageEditorPane editor = new PackageEditorPane(myPackage);
                    ppunkDocView       = Marshal.GetIUnknownForObject(editor);
                    ppunkDocData       = Marshal.GetIUnknownForObject(editor);
                    pbstrEditorCaption = string.Empty;
                    return(VSConstants.S_OK);
                }

                // If physical view is non-null, create an editor window on an xml fragment.

                // Verify that the base document is created

                IVsRunningDocumentTable runningDocTable = (IVsRunningDocumentTable)this.GetService(typeof(SVsRunningDocumentTable));
                int hr = runningDocTable.FindAndLockDocument(
                    (uint)_VSRDTFLAGS.RDT_NoLock,
                    pszMkDocument,
                    out IVsHierarchy hierarchy,
                    out uint itemIdFindAndLock,
                    out IntPtr docDataFindAndLock,
                    out uint docCookieFindAndLock
                    );

                string xml = string.Empty;
                if (VSConstants.S_OK != hr) // can't find document in RDT.
                {
                    // We are being asked to open a sub document before the main document is open.
                    // Let's create the main and put it in the RDT with a temporary EditLock that
                    // we will release after the sub document window is created.
                    using (PackageEditorPane editor = new PackageEditorPane(myPackage))
                    {
                        IVsPersistDocData mainDocData = editor;
                        mainDocData.LoadDocData(pszMkDocument);
                        // TODO editor.TemporaryLockDocument(runningDocTable, pvHier, itemid, pszMkDocument);
                        xml = editor.GetXml(pszPhysicalView);
                    }
                }
                else
                {
                    // get xml from open editor.
                    if (docDataFindAndLock != IntPtr.Zero)
                    {
                        Marshal.Release(docDataFindAndLock);
                    }
                    if (existingPackageEditor != null)
                    {
                        xml = existingPackageEditor.GetXml(pszPhysicalView);
                    }
                }

                // Use ILocalRegistry to create text buffer and code window
                ILocalRegistry localRegistry = (ILocalRegistry)this.GetService(typeof(ILocalRegistry));
                Debug.Assert(null != localRegistry);

                // Create the document (text buffer)
                IntPtr vsTextLines   = IntPtr.Zero;
                Guid   guidTextLines = typeof(IVsTextLines).GUID;
                ErrorHandler.ThrowOnFailure(
                    localRegistry.CreateInstance(typeof(VsTextBufferClass).GUID, null, ref guidTextLines, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out vsTextLines)
                    );
                IVsTextLines textLines = (IVsTextLines)Marshal.GetObjectForIUnknown(vsTextLines);

                // Create the codewindow (editor)
                IntPtr vsCodeWindow   = IntPtr.Zero;
                Guid   guidCodeWindow = typeof(IVsCodeWindow).GUID;
                ErrorHandler.ThrowOnFailure(
                    localRegistry.CreateInstance(typeof(VsCodeWindowClass).GUID, null, ref guidCodeWindow, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out vsCodeWindow)
                    );
                IVsCodeWindow codeWindow = Marshal.GetObjectForIUnknown(vsCodeWindow) as IVsCodeWindow;

                // Site it, so it can find/query for various services
                IObjectWithSite textLinesWithSite = (IObjectWithSite)textLines;

                // Site the TextBuffer with an IOleServiceProvider
                IOleServiceProvider pOleSeviceProvider;
                pOleSeviceProvider = (IOleServiceProvider)this.vsServiceProvider.GetService(typeof(IOleServiceProvider));
                textLinesWithSite.SetSite(pOleSeviceProvider);

                ErrorHandler.ThrowOnFailure(
                    textLines.InitializeContent(xml, xml.Length)
                    );

                // Attach buffer to code window
                ErrorHandler.ThrowOnFailure(
                    codeWindow.SetBuffer(textLines)
                    );

                // Set the language service to the XML language service to get syntax highlighting
                Guid xmlLanguageServiceGuid = new Guid("{f6819a78-a205-47b5-be1c-675b3c7f0b8e}");
                textLines.SetLanguageServiceID(ref xmlLanguageServiceGuid);

                // If the project system has specified the language service clear the auto detect flag to ensure that we use the preferred service
                IVsUserData userData = (IVsUserData)textLines;
                Guid        vsBufferDetectLangSIDGuid = new Guid("{17F375AC-C814-11d1-88AD-0000F87579D2}");
                object      flagObject = false;
                userData.SetData(ref vsBufferDetectLangSIDGuid, flagObject);

                ppunkDocView       = vsCodeWindow; // refcnt from CreateEditorInstance
                ppunkDocData       = vsTextLines;  // refcnt from CreateEditorInstance
                pbstrEditorCaption = " (" + pszPhysicalView + ")";
                pgrfCDW           |= (int)__VSCREATEDOCWIN.CDW_fAltDocData;

                return(VSConstants.S_OK);
            }
            catch (Exception error)
            {
                System.Windows.Forms.MessageBox.Show(error.Message);
            }
            return(VSConstants.E_INVALIDARG);
        }
Example #36
0
 internal static bool IsDirty(IVsPersistDocData docData)
 {
     int pfDirty;
     ErrorHandler.ThrowOnFailure(docData.IsDocDataDirty(out pfDirty));
     return pfDirty > 0;
 }
Example #37
0
        private void DisplayDgml(XElement dgml)
        {
            var filePath = Path.Combine(Path.GetTempPath(), "Syntax.dgml");

            uint           docItemId;
            IVsUIHierarchy docUIHierarchy;
            IVsWindowFrame docWindowFrame;

            // Check whether the file is already open in the 'design' view.
            // If the file is already open in the desired view then we will update the
            // contents of the file on disk with the new directed syntax graph and load
            // this new graph into the already open view of the file.
            if (VsShellUtilities.IsDocumentOpen(
                    DTE2ServiceProvider, filePath, GuidList.GuidVsDesignerViewKind,
                    out docUIHierarchy, out docItemId, out docWindowFrame) && docWindowFrame != null)
            {
                IVsHierarchy docHierarchy;
                uint         docCookie;
                IntPtr       docDataIUnknownPointer;

                if (RunningDocumentTable.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, filePath,
                                                             out docHierarchy, out docItemId,
                                                             out docDataIUnknownPointer,
                                                             out docCookie) == VSConstants.S_OK &&
                    docDataIUnknownPointer != null)
                {
                    IntPtr persistDocDataServicePointer;
                    var    persistDocDataServiceGuid = typeof(IVsPersistDocData).GUID;

                    if (Marshal.QueryInterface(docDataIUnknownPointer, ref persistDocDataServiceGuid,
                                               out persistDocDataServicePointer) == 0 &&
                        persistDocDataServicePointer != null)
                    {
                        try
                        {
                            IVsPersistDocData persistDocDataService =
                                (IVsPersistDocData)Marshal.GetObjectForIUnknown(persistDocDataServicePointer);

                            if (persistDocDataService != null)
                            {
                                const int TRUE = -1, FALSE = 0;

                                // The below call ensures that there are no pop-ups from Visual Studio
                                // prompting the user to reload the file each time it is changed.
                                FileChangeService.IgnoreFile(0, filePath, TRUE);

                                // Update the file on disk with the new directed syntax graph.
                                dgml.Save(filePath);

                                // The below calls ensure that the file is refreshed inside Visual Studio
                                // so that the latest contents are displayed to the user.
                                FileChangeService.SyncFile(filePath);
                                persistDocDataService.ReloadDocData((uint)_VSRELOADDOCDATA.RDD_IgnoreNextFileChange);

                                // Re-enable pop-ups from Visual Studio prompting the user to reload the file
                                // in case the file is ever changed by some other process.
                                FileChangeService.IgnoreFile(0, filePath, FALSE);

                                // Make sure the directed syntax graph window is visible but don't give it focus.
                                docWindowFrame.ShowNoActivate();
                            }
                        }
                        finally
                        {
                            Marshal.Release(persistDocDataServicePointer);
                        }
                    }
                }
            }
            else
            {
                // File is not open in the 'design' view. But it may be open in the 'xml' view.
                // If the file is open in any other view than 'design' view then we will close it
                // so that there are no pop-ups from Visual Studio about the file already being open.
                if (VsShellUtilities.IsDocumentOpen(
                        DTE2ServiceProvider, filePath, Guid.Empty,
                        out docUIHierarchy, out docItemId, out docWindowFrame) && docWindowFrame != null)
                {
                    docWindowFrame.CloseFrame((uint)__FRAMECLOSE.FRAMECLOSE_NoSave);
                }

                // Update the file on disk with the new directed syntax graph.
                dgml.Save(filePath);

                // Open the new directed syntax graph in the 'design' view.
                VsShellUtilities.OpenDocument(
                    DTE2ServiceProvider, filePath, GuidList.GuidVsDesignerViewKind,
                    out docUIHierarchy, out docItemId, out docWindowFrame);
            }
        }
Example #38
0
        /// <summary>
        /// Reloads the document and optionally clears the undo state
        /// </summary>
        /// <param name="clearUndo">if set to <c>true</c> [clear undo].</param>
        /// <returns><c>true</c> if the document is reloaded, otherwise false</returns>
        public bool Reload(bool clearUndo)
        {
            if (_disposed)
            {
                return(false);
            }

            if (!IsDocumentInitialized)
            {
                return(true); // Not loaded, so no reload necessary!
            }
            int  reloadCookie = _reloadTick;
            bool wasDirty     = IsDirty;

            IVsPersistDocData vsPersistDocData = RawDocument as IVsPersistDocData;

            if (vsPersistDocData != null)
            {
                // This method is valid on all text editors and probably many other editors

                uint flags = 0;
                if (clearUndo)
                {
                    flags |= (uint)_VSRELOADDOCDATA.RDD_RemoveUndoStack;
                }

                bool ok;

                // Temporarily suspend our ignore 'lock' as without that documents
                // don't reload properly.

                if (_ignoring)
                {
                    EnsureIgnored(false);
                }

                try
                {
                    ok = SafeSucceeded(vsPersistDocData.ReloadDocData, flags);
                }
                finally
                {
                    EnsureIgnored(_ignored > 0);
                }

                if (ok)
                {
                    if (_disposed || (reloadCookie != _reloadTick) || (wasDirty != IsDirty))
                    {
                        return(true);
                    }
                }
            }

            IVsPersistHierarchyItem2 vsPersistHierarchyItem2 = RawDocument as IVsPersistHierarchyItem2;

            if (vsPersistHierarchyItem2 != null)
            {
                // This route works for some project types and at least the solution
                bool assumeOk = (_rawDocument is IVsSolution);

                if (SafeSucceeded(vsPersistHierarchyItem2.ReloadItem, VSItemId.Root, (uint)0))
                {
                    if (assumeOk || _disposed || reloadCookie != _reloadTick)
                    {
                        return(true);
                    }
                }
            }


            vsPersistHierarchyItem2 = Hierarchy as IVsPersistHierarchyItem2;

            if (vsPersistHierarchyItem2 != null &&
                SafeSucceeded(vsPersistHierarchyItem2.ReloadItem, ItemId, (uint)0))
            {
                // Our parent reloaded us
                return(true);
            }

            return(false); // We can't be reloaded by ourselves.. Let our caller reload our parent instead
        }
Example #39
0
        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;

            Assumes.Present(uiShellOpenDocument);

            IOleServiceProvider serviceProvider = this.Node.ProjectMgr.Site.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider;

            Assumes.Present(serviceProvider);

            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);
        }
        private void DisplayDgml(XElement dgml)
        {
            uint           docItemId, cookie;
            IVsUIHierarchy docUIHierarchy;
            IVsWindowFrame docWindowFrame;
            IVsHierarchy   docHierarchy;
            IntPtr         docDataIUnknownPointer;
            const int      TRUE = -1;

            if (string.IsNullOrWhiteSpace(dgmlFilePath))
            {
                var folderPath = Path.Combine(Path.GetTempPath(),
                                              "Syntax-" + System.Diagnostics.Process.GetCurrentProcess().Id.ToString());
                Directory.CreateDirectory(folderPath);
                dgmlFilePath = Path.Combine(folderPath, "Syntax.dgml");
            }

            // Check whether the file is already open in the 'design' view.
            // If the file is already open in the desired view then we will update the
            // contents of the file on disk with the new directed syntax graph and load
            // this new graph into the already open view of the file.
            if (VsShellUtilities.IsDocumentOpen(
                    ServiceProvider.GlobalProvider, dgmlFilePath, GuidList.GuidVsDesignerViewKind,
                    out docUIHierarchy, out docItemId, out docWindowFrame) && docWindowFrame != null)
            {
                if (RunningDocumentTable.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, dgmlFilePath,
                                                             out docHierarchy, out docItemId,
                                                             out docDataIUnknownPointer,
                                                             out cookie) == VSConstants.S_OK)
                {
                    IntPtr persistDocDataServicePointer;
                    var    persistDocDataServiceGuid = typeof(IVsPersistDocData).GUID;

                    if (Marshal.QueryInterface(docDataIUnknownPointer, ref persistDocDataServiceGuid,
                                               out persistDocDataServicePointer) == 0)
                    {
                        try
                        {
                            IVsPersistDocData persistDocDataService =
                                (IVsPersistDocData)Marshal.GetObjectForIUnknown(persistDocDataServicePointer);

                            if (persistDocDataService != null)
                            {
                                // The below call ensures that there are no pop-ups from Visual Studio
                                // prompting the user to reload the file each time it is changed.
                                FileChangeService.IgnoreFile(0, dgmlFilePath, TRUE);

                                // Update the file on disk with the new directed syntax graph.
                                dgml.Save(dgmlFilePath);

                                // The below calls ensure that the file is refreshed inside Visual Studio
                                // so that the latest contents are displayed to the user.
                                FileChangeService.SyncFile(dgmlFilePath);
                                persistDocDataService.ReloadDocData((uint)_VSRELOADDOCDATA.RDD_IgnoreNextFileChange);

                                // Make sure the directed syntax graph window is visible but don't give it focus.
                                docWindowFrame.ShowNoActivate();
                            }
                        }
                        finally
                        {
                            Marshal.Release(persistDocDataServicePointer);
                        }
                    }
                }
            }
            else
            {
                // Update the file on disk with the new directed syntax graph.
                dgml.Save(dgmlFilePath);

                // Open the new directed syntax graph in the 'design' view.
                VsShellUtilities.OpenDocument(
                    ServiceProvider.GlobalProvider, dgmlFilePath, GuidList.GuidVsDesignerViewKind,
                    out docUIHierarchy, out docItemId, out docWindowFrame);

                // Register event handler to ensure that directed syntax graph file is deleted when the solution is closed.
                // This ensures that the file won't be persisted in the .suo file and that it therefore won't get re-opened
                // when the solution is re-opened.
                SolutionService.AdviseSolutionEvents(this, out cookie);
            }
        }