Exemple #1
0
        public static String GetFileName(ITextBuffer buffer)
        {
            IVsTextBuffer adapter;

            if (buffer.Properties.TryGetProperty(typeof(IVsTextBuffer), out adapter))
            {
                IPersistFileFormat pff = adapter as IPersistFileFormat;
                if (pff != null)
                {
                    String filename;
                    uint   formatIndex;
                    try {
                        int hr = pff.GetCurFile(out filename, out formatIndex);
                        // some windows will return E_NOTIMPL
                        if (hr == Constants.E_NOTIMPL)
                        {
                            return(null);
                        }
                        CheckError(hr, "GetCurFile");
                    } catch (NotImplementedException) {
                        // Lovely stuff: SecondaryVsTextBuffer will
                        // fail with a NIE instead of returning E_NOTIMPL O_0
                        filename = null;
                    }
                    return(filename);
                }
            }
            return(null);
        }
        /// <summary>
        ///     Attempt to determine the name of the file represented by the specified text buffer.
        /// </summary>
        /// <param name="textBuffer">
        ///     The text buffer.
        /// </param>
        /// <returns>
        ///     The file name, or <c>null</c> if the file name could not be determined.
        /// </returns>
        public static string GetFileName(this ITextBuffer textBuffer)
        {
            if (textBuffer == null)
            {
                throw new ArgumentNullException(nameof(textBuffer));
            }

            IVsTextBuffer bufferAdapter;

            textBuffer.Properties.TryGetProperty(typeof(IVsTextBuffer), out bufferAdapter);
            if (bufferAdapter == null)
            {
                return(null);
            }

            IPersistFileFormat persistFileFormat = bufferAdapter as IPersistFileFormat;

            if (persistFileFormat == null)
            {
                return(null);
            }

            string fileName = null;

            int hr = persistFileFormat.GetCurFile(out fileName, out _);

            ErrorHandler.ThrowOnFailure(hr);

            return(fileName);
        }
        /// <summary>
        /// Saves the hierarchy item to disk.
        /// </summary>
        /// <param name="dwSave">Flags whose values are taken from the VSSAVEFLAGS enumeration.</param>
        /// <param name="silentSaveAsName">File name to be applied when dwSave is set to VSSAVE_SilentSave. </param>
        /// <param name="itemid">Item identifier of the hierarchy item saved from VSITEMID. </param>
        /// <param name="punkDocData">Pointer to the IUnknown interface of the hierarchy item saved.</param>
        /// <param name="pfCancelled">TRUE if the save action was canceled. </param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
        public override int SaveItem(VSSAVEFLAGS dwSave, string silentSaveAsName, uint itemid, IntPtr punkDocData, out int pfCancelled)
        {
            // Don't ignore/unignore file changes
            // Use Advise/Unadvise to work around rename situations
            try
            {
                this.StopObservingNestedProjectFile();
                Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
                Debug.Assert(punkDocData != IntPtr.Zero, "docData intptr was zero");

                // Get an IPersistFileFormat object from docData object (we don't call release on punkDocData since did not increment its ref count)
                IPersistFileFormat persistFileFormat = Marshal.GetTypedObjectForIUnknown(punkDocData, typeof(IPersistFileFormat)) as IPersistFileFormat;
                Debug.Assert(persistFileFormat != null, "The docData object does not implement the IPersistFileFormat interface");

                IVsUIShell uiShell = this.GetService(typeof(SVsUIShell)) as IVsUIShell;
                string     newName;
                uiShell.SaveDocDataToFile(dwSave, persistFileFormat, silentSaveAsName, out newName, out pfCancelled);

                // When supported do a rename of the nested project here
            }
            finally
            {
                // Succeeded or not we must hook to the file change events
                // Don't ignore/unignore file changes
                // Use Advise/Unadvise to work around rename situations
                this.ObserveNestedProjectFile();
            }

            return(VSConstants.S_OK);
        }
Exemple #4
0
        private static void SaveDocDataToFileCallBack(object caller, CallbackArgs arguments)
        {
            arguments.ReturnValue = VSConstants.S_OK;

            VSSAVEFLAGS        dwSave         = (VSSAVEFLAGS)arguments.GetParameter(0);
            IPersistFileFormat editorInstance = (IPersistFileFormat)arguments.GetParameter(1);
            string             fileName       = (string)arguments.GetParameter(2);

            //Call Save on the EditorInstance depending on the Save Flags
            switch (dwSave)
            {
            case VSSAVEFLAGS.VSSAVE_Save:
            case VSSAVEFLAGS.VSSAVE_SilentSave:
                editorInstance.Save(fileName, 0, 0);
                arguments.SetParameter(3, fileName);        // setting pbstrMkDocumentNew
                arguments.SetParameter(4, 0);               // setting pfSaveCanceled
                break;

            case VSSAVEFLAGS.VSSAVE_SaveAs:
                string newFileName = Environment.GetEnvironmentVariable("SystemDrive") +
                                     Path.DirectorySeparatorChar + "NewTempFile.rtf";
                editorInstance.Save(newFileName, 1, 0);         //Call Save with new file and remember=1
                arguments.SetParameter(3, newFileName);         // setting pbstrMkDocumentNew
                arguments.SetParameter(4, 0);                   // setting pfSaveCanceled
                break;

            case VSSAVEFLAGS.VSSAVE_SaveCopyAs:
                newFileName = Environment.GetEnvironmentVariable("SystemDrive") +
                              Path.DirectorySeparatorChar + "NewTempFile.rtf";
                editorInstance.Save(newFileName, 0, 0);         //Call Save with new file and remember=0
                arguments.SetParameter(3, newFileName);         // setting pbstrMkDocumentNew
                arguments.SetParameter(4, 0);                   // setting pfSaveCanceled
                break;
            }
        }
        /// <summary>
        /// get the full filename (with path) of the provided buffer; returns null if such name does not exist
        /// </summary>
        public static string GetFileName(ITextBuffer buffer)
        {
            try
            {
                if (false)
                {
                    buffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument document);
                    return(document?.FilePath);
                }
                else
                {
                    buffer.Properties.TryGetProperty(typeof(Microsoft.VisualStudio.TextManager.Interop.IVsTextBuffer), out IVsTextBuffer bufferAdapter);
                    if (bufferAdapter != null)
                    {
                        IPersistFileFormat persistFileFormat = bufferAdapter as IPersistFileFormat;

                        string filename = null;
                        if (persistFileFormat != null)
                        {
                            persistFileFormat.GetCurFile(out filename, out uint dummyInteger);
                        }
                        return(filename);
                    }
                }
            } catch (Exception e)
            {
                AsmDudeToolsStatic.Output_ERROR(string.Format("AsmDudeToolsStatic:GetFileName {0}", e.Message));
            }
            return(null);
        }
        public static Project GetCurrentProject(ITextBuffer buffer, IVsEditorAdaptersFactoryService adaptersFactory, SVsServiceProvider serviceProvider)
        {
            IPersistFileFormat persistFileFormat = adaptersFactory.GetBufferAdapter(buffer) as IPersistFileFormat;

            if (persistFileFormat == null)
            {
                return(null);
            }

            string ppzsFilename;
            uint   iii;

            persistFileFormat.GetCurFile(out ppzsFilename, out iii);

            if (String.IsNullOrWhiteSpace(ppzsFilename))
            {
                return(null);
            }

            DTE dte = GetDte(serviceProvider);

            ProjectItem prjItem = dte.Solution.FindProjectItem(ppzsFilename);

            if (prjItem == null)
            {
                return(null);
            }

            return(prjItem.ContainingProject);
        }
Exemple #7
0
        private static void SaveDocDataToFileCallBack(object caller, CallbackArgs arguments)
        {
            arguments.ReturnValue = VSConstants.S_OK;

            VSSAVEFLAGS        dwSave         = (VSSAVEFLAGS)arguments.GetParameter(0);
            IPersistFileFormat editorInstance = (IPersistFileFormat)arguments.GetParameter(1);
            string             fileName       = (string)arguments.GetParameter(2);

            //Call Save on the EditorInstance depending on the Save Flags
            switch (dwSave)
            {
            case VSSAVEFLAGS.VSSAVE_Save:
            case VSSAVEFLAGS.VSSAVE_SilentSave:
                editorInstance.Save(fileName, 0, 0);
                arguments.SetParameter(3, fileName);        // setting pbstrMkDocumentNew
                arguments.SetParameter(4, 0);               // setting pfSaveCanceled
                break;

            case VSSAVEFLAGS.VSSAVE_SaveAs:
                String newFileName = Path.Combine(Path.GetTempPath(), Path.GetFileName(fileName));
                editorInstance.Save(newFileName, 1, 0);         //Call Save with new file and remember=1
                arguments.SetParameter(3, newFileName);         // setting pbstrMkDocumentNew
                arguments.SetParameter(4, 0);                   // setting pfSaveCanceled
                break;

            case VSSAVEFLAGS.VSSAVE_SaveCopyAs:
                newFileName = Path.Combine(Path.GetTempPath(), Path.GetFileName(fileName));
                editorInstance.Save(newFileName, 0, 0);         //Call Save with new file and remember=0
                arguments.SetParameter(3, newFileName);         // setting pbstrMkDocumentNew
                arguments.SetParameter(4, 0);                   // setting pfSaveCanceled
                break;
            }
        }
Exemple #8
0
        /// <summary>
        /// Creates a <see cref="CoverageMargin"/> for a given <see cref="IWpfTextView"/>.
        /// </summary>
        /// <param name="textView">The <see cref="IWpfTextView"/> to attach the margin to.</param>
        public CoverageMargin(IWpfTextView textView, IEditorFormatMap formatMap)
        {
            _textView  = textView;
            _formatMap = formatMap;

            IVsTextBuffer buffer;

            textView.TextBuffer.Properties.TryGetProperty(typeof(IVsTextBuffer), out buffer);
            _fileName = "";
            if (buffer != null)
            {
                IPersistFileFormat fileFormat = buffer as IPersistFileFormat;
                if (fileFormat != null)
                {
                    UInt32 format;
                    fileFormat.GetCurFile(out _fileName, out format);
                }
            }

            _canvas = new Canvas();
            this.Children.Add(_canvas);

            this.ClipToBounds = true;

            OnFormatMappingChanged();

            _textView.ViewportHeightChanged += (sender, args) => DrawLineNumbers();
            _textView.LayoutChanged         += new EventHandler <TextViewLayoutChangedEventArgs>(OnLayoutChanged);
            _formatMap.FormatMappingChanged += (sender, args) => OnFormatMappingChanged();

            this.ToolTip = "To customize coverage margin colors select:\n" +
                           "  Tools -> Options -> Fonts and Colors -> " + CovColorName;
        }
Exemple #9
0
        private static string GetFilePath(IPersistFileFormat persistFileFormat)
        {
            string filePath;
            uint   formatIndex;

            ErrorHelper.ThrowOnFailure(persistFileFormat.GetCurFile(out filePath, out formatIndex));
            return(filePath);
        }
Exemple #10
0
        public static string GetFilePath(IVsTextLines textView)
        {
            IPersistFileFormat fileFormat = (IPersistFileFormat)textView;
            string             path       = null;
            uint format;

            fileFormat.GetCurFile(out path, out format);
            return(path);
        }
Exemple #11
0
        public Colorizer(LanguageService languageService, IVsTextLines buffer)
        {
            this.languageService = languageService;
            this.cachedLine      = -1;
            string             fname       = null;
            uint               formatIndex = 0;
            IPersistFileFormat pff         = (IPersistFileFormat)buffer;

            pff.GetCurFile(out fname, out formatIndex);
            this.scanner = languageService.GetScanner(fname);
            this.buffer  = buffer;
        }
        /// <summary>
        /// Determines whether the hierarchy item changed.
        /// </summary>
        /// <param name="itemId">Item identifier of the hierarchy item contained in VSITEMID</param>
        /// <param name="punkDocData">Pointer to the IUnknown interface of the hierarchy item. </param>
        /// <param name="pfDirty">TRUE if the hierarchy item changed.</param>
        /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns>
        public override int IsItemDirty(uint itemId, IntPtr punkDocData, out int pfDirty)
        {
            Debug.Assert(this.nestedHierarchy != null, "The nested hierarchy object must be created before calling this method");
            Debug.Assert(punkDocData != IntPtr.Zero, "docData intptr was zero");

            // Get an IPersistFileFormat object from docData object
            IPersistFileFormat persistFileFormat = Marshal.GetTypedObjectForIUnknown(punkDocData, typeof(IPersistFileFormat)) as IPersistFileFormat;

            Debug.Assert(persistFileFormat != null, "The docData object does not implement the IPersistFileFormat interface");

            // Call IsDirty on the IPersistFileFormat interface
            ErrorHandler.ThrowOnFailure(persistFileFormat.IsDirty(out pfDirty));

            return(VSConstants.S_OK);
        }
Exemple #13
0
        /// <summary>
        /// Checks whether the specified project is a solution folder
        /// </summary>
        public bool IsSolutionFolderProject(IVsHierarchy pHier)
        {
            IPersistFileFormat pFileFormat = pHier as IPersistFileFormat;

            if (pFileFormat != null)
            {
                Guid guidClassID;
                if (pFileFormat.GetClassID(out guidClassID) == VSConstants.S_OK &&
                    guidClassID.CompareTo(guidSolutionFolderProject) == 0)
                {
                    return(true);
                }
            }

            return(false);
        }
        /// <summary>
        /// Checks whether the specified project is a solution folder
        /// </summary>
        public static async Task <bool> IsSolutionFolderProject(this IVsHierarchy pHier)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IPersistFileFormat pFileFormat = pHier as IPersistFileFormat;

            if (pFileFormat != null)
            {
                Guid guidClassID;
                if (pFileFormat.GetClassID(out guidClassID) == VSConstants.S_OK &&
                    guidClassID.CompareTo(GuidSolutionFolderProject) == 0)
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #15
0
        public string GetFileName(IVsTextView view)
        {
            if (view == null)
            {
                return(null);
            }
            string fname = null;

            try{
                uint         formatIndex;
                IVsTextLines pBuffer;
                view.GetBuffer(out pBuffer);
                IPersistFileFormat pff = (IPersistFileFormat)pBuffer;
                pff.GetCurFile(out fname, out formatIndex);
                pff     = null;
                pBuffer = null;
            }catch {}
            return(fname);
        }
Exemple #16
0
        public ParamStorageTagger(ITextBuffer buffer)
        {
            IVsTextBuffer vsbuffer;

            buffer.Properties.TryGetProperty(typeof(IVsTextBuffer), out vsbuffer);
            _fileName = "";
            if (vsbuffer != null)
            {
                IPersistFileFormat fileFormat = vsbuffer as IPersistFileFormat;
                if (fileFormat != null)
                {
                    UInt32 format;
                    fileFormat.GetCurFile(out _fileName, out format);
                }
            }

            buffer.Changed  += (sender, args) => HandleBufferChanged(args);
            _pendingSnapshot = _currentSnapshot = buffer.CurrentSnapshot;
        }
        /// <summary>
        /// get the full filename (with path) of the provided buffer; returns null if such name does not exist
        /// </summary>
        public static string GetFileName(ITextBuffer buffer)
        {
            buffer.Properties.TryGetProperty(typeof(Microsoft.VisualStudio.TextManager.Interop.IVsTextBuffer), out IVsTextBuffer bufferAdapter);
            if (bufferAdapter != null)
            {
                IPersistFileFormat persistFileFormat = bufferAdapter as IPersistFileFormat;

                string filename = null;
                if (persistFileFormat != null)
                {
                    persistFileFormat.GetCurFile(out filename, out uint dummyInteger);
                }
                return(filename);
            }
            else
            {
                return(null);
            }
        }
Exemple #18
0
        internal static string GetFilePathInternal(object obj)
        {
            string      fname = null;
            int         hr    = 0;
            IVsUserData ud    = obj as IVsUserData;

            if (ud != null)
            {
                object oname;
                Guid   GUID_VsBufferMoniker = typeof(IVsUserData).GUID;
                hr = ud.GetData(ref GUID_VsBufferMoniker, out oname);
                if (Microsoft.VisualStudio.ErrorHandler.Succeeded(hr) && oname != null)
                {
                    fname = oname.ToString();
                }
            }
            if (string.IsNullOrEmpty(fname))
            {
                IPersistFileFormat fileFormat = obj as IPersistFileFormat;
                if (fileFormat != null)
                {
                    uint format;
                    hr = fileFormat.GetCurFile(out fname, out format);
                }
            }
            if (!string.IsNullOrEmpty(fname))
            {
                Microsoft.VisualStudio.Shell.Url url = new Microsoft.VisualStudio.Shell.Url(fname);
                if (!url.Uri.IsAbsoluteUri)
                {
                    // make the file name absolute using app startup path...
                    Microsoft.VisualStudio.Shell.Url baseUrl = new Microsoft.VisualStudio.Shell.Url(Application.StartupPath + Path.DirectorySeparatorChar);
                    url   = new Microsoft.VisualStudio.Shell.Url(baseUrl, fname);
                    fname = url.AbsoluteUrl;
                }
            }
            return(fname);
        }
Exemple #19
0
        /// <summary>
        /// get the full filename (with path) of the provided buffer; returns null if such name does not exist
        /// </summary>
        public static string GetFileName(ITextBuffer buffer)
        {
            try
            {
                if (true)
                {
                    buffer.Properties.TryGetProperty(typeof(ITextDocument), out ITextDocument document);
                    string filename = document?.FilePath;
                    AsmDudeToolsStatic.Output_INFO(string.Format("AsmDudeToolsStatic:GetFileName: retrieving filename {0}", filename));
                    return(filename);
                }
                else // this method had worked in VS 15.6, but ceased working in 15.7. GetCurFile could not be issued from a non UI thread
                {
                    buffer.Properties.TryGetProperty(typeof(Microsoft.VisualStudio.TextManager.Interop.IVsTextBuffer), out IVsTextBuffer bufferAdapter);
                    if (bufferAdapter != null)
                    {
                        IPersistFileFormat persistFileFormat = bufferAdapter as IPersistFileFormat;

                        string filename = null;
                        int?   code     = persistFileFormat?.GetCurFile(out filename, out uint dummyInteger);
                        if (code == Microsoft.VisualStudio.VSConstants.S_OK)
                        {
                            AsmDudeToolsStatic.Output_INFO(string.Format("AsmDudeToolsStatic:GetFileName: retrieving filename {0}", filename));
                            return(filename);
                        }
                        else
                        {
                            AsmDudeToolsStatic.Output_ERROR(string.Format("AsmDudeToolsStatic:GetFileName: retrieving filename yielded error code {0}", code));
                        }
                    }
                }
            } catch (Exception e)
            {
                AsmDudeToolsStatic.Output_ERROR(string.Format("AsmDudeToolsStatic:GetFileName {0}", e.Message));
            }
            return(null);
        }
Exemple #20
0
        static SccProjectType GetProjectType(IVsSccProject2 project)
        {
            IPersistFileFormat pFileFormat = project as IPersistFileFormat;

            if (pFileFormat != null)
            {
                Guid guidClassID;
                if (VSConstants.S_OK != pFileFormat.GetClassID(out guidClassID))
                {
                    return(SccProjectType.Normal);
                }

                if (guidClassID == _solutionFolderProjectId)
                {
                    return(SccProjectType.SolutionFolder);
                }
                else if (guidClassID == _websiteProjectId)
                {
                    return(SccProjectType.WebSite);
                }
            }

            return(SccProjectType.Normal);
        }
        /// <summary>
        /// Gets the variables and directories for the specified project. Variables will be in
        /// the form <c>ProjectName.VariableName</c>.
        /// </summary>
        /// <param name="variables">The <see cref="NameValueCollection"/> to add the variables to.</param>
        /// <param name="hierarchy">The <see cref="IVsHierarchy"/> (project) from which to retrieve the variables.</param>
        private void GetProjectVariables(NameValueCollection variables, IVsHierarchy hierarchy)
        {
            // ProjectX variables
            try
            {
                int hr = NativeMethods.S_OK;

                // Get the project name and directory from the hierarchy.
                object projectNameObj;
                object projectDirObj;
                hr = hierarchy.GetProperty(NativeMethods.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectName, out projectNameObj);
                hr = hierarchy.GetProperty(NativeMethods.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectDir, out projectDirObj);

                // To get the project file path, we have to get an IPersistFileFormat interface from the hierarchy.
                IPersistFileFormat persistFileFormat = hierarchy as IPersistFileFormat;

                // Sometimes the hierarchy doesn't always support all of these requested properties.
                // We have to have all three to properly get all of the project properties.
                if (projectNameObj == null || projectDirObj == null || persistFileFormat == null)
                {
                    Tracer.WriteLine(classType, "GetProjectVariables", Tracer.Level.Warning, "The hierarchy '{0}' does not support one of the VSHPROPID_ProjectName, VSHPROPID_ProjectDir, or IPersistFileFormat properties. Skipping the project variables.", projectNameObj);
                    return;
                }

                // Get the project path.
                string projectPath;
                uint   formatIndex;
                NativeMethods.ThrowOnFailure(persistFileFormat.GetCurFile(out projectPath, out formatIndex));

                // Construct the ProjectX variables from the ones retrieved from the hierarchy.
                string projectName        = (string)projectNameObj;
                string projectDir         = PackageUtility.StripTrailingChar((string)projectDirObj, Path.DirectorySeparatorChar);
                string projectFileName    = Path.GetFileName(projectPath);
                string projectExt         = PackageUtility.EnsureLeadingChar(Path.GetExtension(projectPath), '.');
                string projectDosFileName = this.EncodeDosFileName(projectFileName);

                // The variable name will be in the form ProjectName.VariableName. We have to strip out
                // any illegal characters from the project name since this will be a preprocessor definition.
                string projectPrefix = this.EncodeProjectName(projectName) + ".";

                // Add the ProjectX variables to the collection.
                variables.Add(projectPrefix + "ProjectDir", projectDir);
                variables.Add(projectPrefix + "ProjectDosFileName", projectDosFileName);
                variables.Add(projectPrefix + "ProjectExt", projectExt);
                variables.Add(projectPrefix + "ProjectFileName", projectFileName);
                variables.Add(projectPrefix + "ProjectName", projectName);
                variables.Add(projectPrefix + "ProjectPath", projectPath);

                // TargetX variables
                this.GetTargetVariables(variables, hierarchy, projectPrefix);
            }
            catch (Exception e)
            {
                if (ErrorUtility.IsExceptionUnrecoverable(e))
                {
                    throw;
                }

                Tracer.WriteLineWarning(classType, "GetProjectVariables", "There was an error while trying to get the project variables. Skipping the ProjectX variables. Exception: {0}", e);
            }
        }
Exemple #22
0
 private static string GetFilePath(IPersistFileFormat persistFileFormat)
 {
   string filePath;
   uint formatIndex;
   ErrorHelper.ThrowOnFailure(persistFileFormat.GetCurFile(out filePath, out formatIndex));
   return filePath;
 }
Exemple #23
0
        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);
            }
        }
Exemple #24
0
        private void ProcessFile(string filePath)
        {
            IVsTextBuffer      textBuffer        = null;
            IPersistFileFormat textBufferPersist = null;
            IVsTextStream      textStream        = null;
            IVsUserData        userData          = null;
            IServiceProvider   serviceProvider   = (IServiceProvider)GetService(typeof(IServiceProvider));

            using (DocData docData = new DocData(serviceProvider, filePath))
                try
                {
                    textBuffer = docData.Buffer;
                    userData   = (IVsUserData)textBuffer;
                    Guid VsBufferDetectLangSID = new Guid("{17F375AC-C814-11d1-88AD-0000F87579D2}");
                    Marshal.ThrowExceptionForHR(userData.SetData(ref VsBufferDetectLangSID, false));
                    textBufferPersist = (IPersistFileFormat)textBuffer;
                    textStream        = (IVsTextStream)textBuffer;
                    int fileLenBeforeReplacement = 0;
                    Marshal.ThrowExceptionForHR(textStream.GetSize(out fileLenBeforeReplacement));
                    IntPtr buffer = IntPtr.Zero;
                    try
                    {
                        buffer = Marshal.StringToCoTaskMemUni(this.Content);
                        Marshal.ThrowExceptionForHR(textStream.ReloadStream(0, fileLenBeforeReplacement, buffer, Content.Length));
                    }
                    finally
                    {
                        Marshal.FreeCoTaskMem(buffer);
                        buffer = IntPtr.Zero;
                    }

                    // Get the original encoding as Texteditor detected it.
                    // The Unicode lib packs codePage in the low word and flags (as emmit BOM) in high word.
                    object encObj = null;
                    Guid   VsBufferEncodingVSTFF = new Guid("{16417F39-A6B7-4c90-89FA-770D2C60440B}");
                    Marshal.ThrowExceptionForHR(userData.GetData(ref VsBufferEncodingVSTFF, out encObj));
                    uint encValue = (uint)encObj;
                    // set the desired encoding
                    encValue = 65001 | 0x10000;
                    Marshal.ThrowExceptionForHR(userData.SetData(ref VsBufferEncodingVSTFF, encValue));
                    Marshal.ThrowExceptionForHR(textBufferPersist.Save(filePath, 1, 0));
                    Marshal.ThrowExceptionForHR(textBufferPersist.SaveCompleted(filePath));
                }
                finally
                {
                    //if (userData != null)
                    //{
                    //    Marshal.ReleaseComObject(userData);
                    //}
                    //if (textStream != null)
                    //{
                    //    Marshal.ReleaseComObject(textStream);
                    //}
                    //if (textBufferPersist != null)
                    //{
                    //    Marshal.ReleaseComObject(textBufferPersist);
                    //}
                    //if (textBuffer != null)
                    //{
                    //    Marshal.ReleaseComObject(textBuffer);
                    //}
                }
        }