Beispiel #1
0
        private T GetService <T>(ITextBuffer textBuffer, Type serviceType)
        {
            var vsBuffer = adaptersFactory.GetBufferAdapter(textBuffer);

            if (vsBuffer == null)
            {
                return(default(T));
            }

            Guid            guidServiceProvider = VSConstants.IID_IUnknown;
            IObjectWithSite objectWithSite      = vsBuffer as IObjectWithSite;
            IntPtr          ptrServiceProvider  = IntPtr.Zero;

            objectWithSite.GetSite(ref guidServiceProvider, out ptrServiceProvider);
            Microsoft.VisualStudio.OLE.Interop.IServiceProvider serviceProvider =
                (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)Marshal.GetObjectForIUnknown(ptrServiceProvider);

            Guid   guidService   = serviceType.GUID;
            Guid   guidInterface = typeof(T).GUID;
            IntPtr ptrObject     = IntPtr.Zero;

            int hr = serviceProvider.QueryService(ref guidService, ref guidInterface, out ptrObject);

            if (ErrorHandler.Failed(hr) || ptrObject == IntPtr.Zero)
            {
                return(default(T));
            }

            T result = (T)Marshal.GetObjectForIUnknown(ptrObject);

            Marshal.Release(ptrObject);

            return(result);
        }
Beispiel #2
0
        /// <summary>
        /// Here we simply host the visual studio core text editor.
        /// </summary>
        public virtual int CreateEditorInstance(uint createDocFlags, string moniker,
                                                string physicalView, IVsHierarchy pHier, uint itemid, IntPtr existingDocData,
                                                out IntPtr docView, out IntPtr docData, out string editorCaption,
                                                out Guid cmdUI, out int cancelled)
        {
            cancelled     = 0;
            cmdUI         = Guid.Empty;
            docData       = IntPtr.Zero;
            docView       = IntPtr.Zero;
            editorCaption = null;
            string ext = Path.GetExtension(moniker).ToLower();

            if (ext.StartsWith("."))
            {
                ext = ext.Substring(1);
            }
            bool takeover = CheckAllFileTypes() && !this.IsRegisteredExtension(ext);

            if (takeover && !IsOurKindOfFile(moniker))
            {
                return((int)VsConstants.VS_E_UNSUPPORTEDFORMAT);
            }

            IVsTextLines buffer = null;

            if (existingDocData != IntPtr.Zero)
            {
                buffer = (IVsTextLines)Marshal.GetTypedObjectForIUnknown(existingDocData, typeof(IVsTextLines));
            }
            else
            {
                buffer = (IVsTextLines)VsShell.CreateInstance(this.site, ref VsConstants.CLSID_VsTextBuffer, ref VsConstants.IID_IVsTextLines, typeof(IVsTextLines));
            }

            IObjectWithSite objWithSite = (IObjectWithSite)buffer;

            objWithSite.SetSite(this.site);

            object window = CreateEditorView(moniker, buffer, physicalView, out editorCaption, out cmdUI);

            if (takeover)
            {
                Guid langSid = GetLanguageSID();
                if (langSid != Guid.Empty)
                {
                    buffer.SetLanguageServiceID(ref langSid);
                    IVsUserData vud = (IVsUserData)buffer;
                    vud.SetData(ref VsConstants.GUID_VsBufferDetectLangSID, false);
                }
                // todo: for some reason my commands are disabled when we go through this
                // code path...
            }

            docView = Marshal.GetIUnknownForObject(window);
            docData = Marshal.GetIUnknownForObject(buffer);

            // VS core editor is the primary command handler
            cancelled = 0;
            return(0);
        }
Beispiel #3
0
        /// <summary>
        /// Creates an object
        /// </summary>
        /// <param name="localRegistry">Establishes a locally-registered COM object relative to the local Visual Studio registry hive</param>
        /// <param name="clsid">GUID if object to be created</param>
        /// <param name="iid">GUID assotiated with specified System.Type</param>
        /// <returns>An object</returns>
        public object CreateObject(ILocalRegistry localRegistry, Guid clsid, Guid iid)
        {
            object objectInstance;
            IntPtr unknown = IntPtr.Zero;

            int hr = localRegistry.CreateInstance(clsid, null, ref iid, (uint)CLSCTX.CLSCTX_INPROC_SERVER, out unknown);

            if (hr != VSConstants.S_OK)
            {
                Marshal.ThrowExceptionForHR(hr);
            }

            try
            {
                objectInstance = Marshal.GetObjectForIUnknown(unknown);
            }
            finally
            {
                if (unknown != IntPtr.Zero)
                {
                    Marshal.Release(unknown);
                }
            }

            // Try to site object instance
            IObjectWithSite objectWithSite = objectInstance as IObjectWithSite;

            if (objectWithSite != null)
            {
                objectWithSite.SetSite(psp);
            }

            return(objectInstance);
        }
        /// <summary>
        /// Writes a url file representing the current navigation state of a browser
        /// </summary>
        /// <param name="browser">The IWebBrowser2 for which to write the url file</param>
        /// <param name="filePath">The path to the url file</param>
        public void WriteForBrowser(IWebBrowser2 browser, string filePath)
        {
            IObjectWithSite site = internetShortcut as IObjectWithSite;

            site.SetSite(browser);
            IPersistFile file = internetShortcut as IPersistFile;

            file.Save(filePath, false);
        }
Beispiel #5
0
        private void Setup()
        {
            int hr;

            m_ifg = new FilterGraph() as IFilterGraph2;
            IObjectWithSite iows = m_ifg as IObjectWithSite;

            hr = iows.SetSite(new foo());
            DsError.ThrowExceptionForHR(hr);
        }
        private void SiteObject(IObjectWithSite objectWithSite)
        {
            if (objectWithSite == null)
            {
                return;
            }

            var oleServiceProvider = (IOleServiceProvider)GetService(typeof(IOleServiceProvider));

            objectWithSite.SetSite(oleServiceProvider);
        }
Beispiel #7
0
        /// <summary>
        /// Create an instance of the BlackListManager
        /// </summary>
        /// <param name="graphBuilder">The Filter Graph to register on.</param>
        public BlackListManager(IGraphBuilder graphBuilder)
        {
            if (graphBuilder == null)
            {
                throw new ArgumentNullException("graphBuilder");
            }

            IObjectWithSite ows = (IObjectWithSite)graphBuilder;

            int hr = ows.SetSite(this);

            DsError.ThrowExceptionForHR(hr);

            this.blackList = new List <Guid>();
        }
Beispiel #8
0
        private void Config()
        {
            int           hr;
            IBaseFilter   pFilter;
            IFilterGraph2 ifg = new FilterGraph() as IFilterGraph2;

            IObjectWithSite iows = ifg as IObjectWithSite;

            //hr = iows.SetSite(this);

            DsDevice[] devs = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice);
            hr = ifg.AddSourceFilterForMoniker(devs[0].Mon, null, "asdf", out pFilter);
            IPin pPin = DsFindPin.ByDirection(pFilter, PinDirection.Output, 1);

            hr = ((IGraphBuilder)ifg).Render(pPin);
            DsError.ThrowExceptionForHR(hr);
        }
Beispiel #9
0
        private void CreateCodeEditor()
        {
            Guid clsidTextBuffer = typeof(VsTextBufferClass).GUID;
            Guid iidTextBuffer   = VSConstants.IID_IUnknown;

            TextBuffer = (IVsTextBuffer)MySqlDataProviderPackage.Instance.CreateInstance(
                ref clsidTextBuffer,
                ref iidTextBuffer,
                typeof(object));
            if (TextBuffer == null)
            {
                throw new Exception("Failed to create core editor");
            }

            // first we need to site our buffer
            IObjectWithSite textBufferSite = TextBuffer as IObjectWithSite;

            if (textBufferSite != null)
            {
                textBufferSite.SetSite(psp);
            }

            // then we need to tell our buffer not to attempt to autodetect the
            // language settings
            IVsUserData userData = TextBuffer as IVsUserData;
            Guid        g        = EditorFactory.GuidVSBufferDetectLangSid;
            int         result   = userData.SetData(ref g, false);

            Guid          clsidCodeWindow = typeof(VsCodeWindowClass).GUID;
            Guid          iidCodeWindow   = typeof(IVsCodeWindow).GUID;
            IVsCodeWindow pCodeWindow     = (IVsCodeWindow)MySqlDataProviderPackage.Instance.CreateInstance(
                ref clsidCodeWindow,
                ref iidCodeWindow,
                typeof(IVsCodeWindow));

            if (pCodeWindow == null)
            {
                throw new Exception("Failed to create core editor");
            }

            // Give the text buffer to the code window.
            // We are giving up ownership of the text buffer!
            pCodeWindow.SetBuffer((IVsTextLines)TextBuffer);

            CodeWindow = pCodeWindow;
        }
Beispiel #10
0
        private void Config()
        {
            int         hr;
            IBaseFilter pFilter;
            object      o;

            IFilterGraph ifg = new FilterGraph() as IFilterGraph;

            IObjectWithSite iows = ifg as IObjectWithSite;

            hr = iows.SetSite(this);
            hr = iows.GetSite(typeof(IAMFilterGraphCallback).GUID, out o);
            hr = ((IGraphBuilder)ifg).AddSourceFilter("DirectShowLib.dll", null, out pFilter);
            IPin pPin = DsFindPin.ByDirection(pFilter, PinDirection.Output, 0);

            hr = ((IGraphBuilder)ifg).Render(pPin);
            //hr = ((IGraphBuilder)ifg).RenderFile("DirectShowLib.dll", null);
            DsError.ThrowExceptionForHR(hr);
        }
Beispiel #11
0
        /// <include file='doc\WindowPane.uex' path='docs/doc[@for="WindowPane.IVsWindowPane.SetSite"]/*' />
        /// <internalonly/>
        /// <devdoc>
        /// IVsWindowPane implementation.
        /// </devdoc>
        int IVsWindowPane.SetSite(IOleServiceProvider p)
        {
            // The siting mechanism works as follows:  If the
            // parent provider provides ServiceProviderHierarchy
            // as a service we will insert our service provider in
            // the WindowPaneSite slot of the hierarchy.
            // If, however, it does not provide
            // this service, we will create a new
            // ServiceProvider that will be used to resolve
            // services through this site.
            //
            if (_provider != null)
            {
                _provider.Dispose();
                _provider = null;
            }

            IObjectWithSite          ows = GetService(typeof(IObjectWithSite)) as IObjectWithSite;
            ServiceProviderHierarchy serviceHierarchy = GetService(typeof(ServiceProviderHierarchy)) as ServiceProviderHierarchy;

            if (serviceHierarchy != null)
            {
                ServiceProvider sp = (p == null ? null : new ServiceProvider(p));
                serviceHierarchy[ServiceProviderHierarchyOrder.WindowPaneSite] = sp;
            }
            else if (ows != null)
            {
                ows.SetSite(p);
            }
            else
            {
                if (p != null)
                {
                    _provider = new ServiceProvider(p);
                }
            }

            if (p != null)
            {
                Initialize();
            }
            return(NativeMethods.S_OK);
        }
        internal static InterfaceType CreateSitedInstance <InterfaceType>(System.IServiceProvider serviceProvider, Guid clsid)
            where InterfaceType : class
        {
            InterfaceType interfaceType = OleServiceProviderExtensions.CreateInstance <InterfaceType>(serviceProvider, clsid);

            if (interfaceType != null)
            {
                IObjectWithSite objectWithSite = (object)interfaceType as IObjectWithSite;
                Microsoft.VisualStudio.OLE.Interop.IServiceProvider service = serviceProvider.GetService <Microsoft.VisualStudio.OLE.Interop.IServiceProvider>();
                if (objectWithSite == null || service == null)
                {
                    interfaceType = default(InterfaceType);
                }
                else
                {
                    objectWithSite.SetSite(service);
                }
            }
            return(interfaceType);
        }
Beispiel #13
0
        ///--------------------------------------------------------------------------------------------
        /// <summary>
        /// Helper to create an instance from the local registry given a CLSID Guid
        /// </summary>
        ///--------------------------------------------------------------------------------------------
        public static InterfaceType CreateSitedInstance <InterfaceType>(IServiceProvider serviceProvider, Guid clsid) where InterfaceType : class
        {
            InterfaceType instance = CreateInstance <InterfaceType>(serviceProvider, clsid);

            if (instance != null)
            {
                IObjectWithSite     sitedObject = instance as IObjectWithSite;
                IOleServiceProvider site        = GetService <IOleServiceProvider>(serviceProvider);
                if (sitedObject != null && site != null)
                {
                    sitedObject.SetSite(site);
                }
                else
                {
                    instance = null;                     // failed to site
                }
            }

            return(instance);
        }
Beispiel #14
0
        public static Microsoft.VisualStudio.OLE.Interop.IServiceProvider GetServiceProvider(this IVsTextBuffer buffer)
        {
            IntPtr pUnk = IntPtr.Zero;

            try
            {
                IObjectWithSite objectWithSite = buffer as IObjectWithSite;

                Guid gUID = typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider).GUID;
                objectWithSite.GetSite(ref gUID, out pUnk);
                return(Marshal.GetObjectForIUnknown(pUnk) as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
            }
            finally
            {
                if (pUnk != IntPtr.Zero)
                {
                    Marshal.Release(pUnk);
                }
            }
        }
        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)
        {
            ppunkDocView       = new System.IntPtr();
            ppunkDocData       = new System.IntPtr();
            pguidCmdUI         = Guid.Empty;
            pgrfCDW            = 0;
            pbstrEditorCaption = null;

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

            if (punkDocDataExisting != IntPtr.Zero)
            {
                return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            // create VsTextBuffer object
            Guid         guidTextLines   = typeof(IVsTextLines).GUID;
            Guid         clsidTextBuffer = typeof(VsTextBufferClass).GUID;
            IVsTextLines vsTextLines     = (IVsTextLines)TBEdit.Instance.CreateInstance(ref clsidTextBuffer, ref guidTextLines, typeof(IVsTextLines));

            // site it, so it can qs for various services
            IObjectWithSite ows = (IObjectWithSite)vsTextLines;

            ows.SetSite(vsServiceProvider);

            // create the tabbed multi-view editor
            TBEditor newEditor = new TBEditor(vsTextLines);

            ppunkDocData       = Marshal.GetIUnknownForObject(vsTextLines);
            ppunkDocView       = Marshal.GetIUnknownForObject(newEditor);
            pbstrEditorCaption = "";

            return(VSConstants.S_OK);
        }
        /// <summary>
        /// Gets the text view lines from the doc data.
        /// </summary>
        protected virtual IVsTextLines?GetTextBuffer(IntPtr docDataExisting, string filename)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            IVsTextLines?textLines;

            if (docDataExisting == IntPtr.Zero)
            {
                // Create a new IVsTextLines buffer.
                Type textLinesType = typeof(IVsTextLines);
                Guid riid          = textLinesType.GUID;
                Guid clsid         = typeof(VsTextBufferClass).GUID;
                textLines = _package.CreateInstance(ref clsid, ref riid, textLinesType) as IVsTextLines;

                // set the buffer's site
                IObjectWithSite objectWithSite = (IObjectWithSite)textLines !;
                objectWithSite.SetSite(_serviceProvider?.GetService(typeof(IOleServiceProvider)));
            }
            else
            {
                // Use the existing text buffer
                object?dataObject = Marshal.GetObjectForIUnknown(docDataExisting);
                textLines = dataObject as IVsTextLines;
                if (textLines == null)
                {
                    // Try get the text buffer from textbuffer provider
                    if (dataObject is IVsTextBufferProvider textBufferProvider)
                    {
                        textBufferProvider.GetTextBuffer(out textLines);
                    }
                }
                if (textLines == null)
                {
                    // Unknown docData type then, so we have to force VS to close the other editor.
                    throw Marshal.GetExceptionForHR(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                }
            }
            return(textLines);
        }
Beispiel #17
0
        private static System.IServiceProvider GetServiceProviderFromTextBuffer(ITextBuffer textBuffer)
        {
            if (textBuffer.Properties.ContainsProperty(typeof(IVsTextBuffer)))
            {
                IObjectWithSite objectWithSite = textBuffer.Properties.GetProperty <IObjectWithSite>(typeof(IVsTextBuffer));
                if (objectWithSite != null)
                {
                    Guid   serviceProviderGuid = typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider).GUID;
                    IntPtr ppServiceProvider   = IntPtr.Zero;
                    // Get the service provider pointer using the Guid of the OleInterop ServiceProvider
                    objectWithSite.GetSite(ref serviceProviderGuid, out ppServiceProvider);

                    if (ppServiceProvider != IntPtr.Zero)
                    {
                        // Create a System.ServiceProvider with the OleInterop ServiceProvider
                        OleInterop.IServiceProvider oleInteropServiceProvider = (OleInterop.IServiceProvider)Marshal.GetObjectForIUnknown(ppServiceProvider);
                        return(new Microsoft.VisualStudio.Shell.ServiceProvider(oleInteropServiceProvider));
                    }
                }
            }

            return(null);
        }
        internal static IVsWindowFrame GetWindowFrame(this IVsTextView textView)
        {
            IObjectWithSite objWithSite         = (IObjectWithSite)textView;
            var             serviceProviderGuid = typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider).GUID;

            IntPtr serviceProviderPointer;

            objWithSite.GetSite(ref serviceProviderGuid, out serviceProviderPointer);
            var serviceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)Marshal.GetObjectForIUnknown(serviceProviderPointer);

            Marshal.Release(serviceProviderPointer);

            serviceProviderGuid = typeof(SVsWindowFrame).GUID;
            var    interfaceGuid = typeof(IVsWindowFrame).GUID;
            IntPtr windowFramePointer;

            serviceProvider.QueryService(ref serviceProviderGuid, ref interfaceGuid, out windowFramePointer);

            var windowFrame = (IVsWindowFrame)Marshal.GetObjectForIUnknown(windowFramePointer);

            Marshal.Release(windowFramePointer);

            return(windowFrame);
        }
Beispiel #19
0
        /// <summary>
        /// Used by the editor factory architecture to create editors that support
        /// data/view separation.
        /// </summary>
        public int CreateEditorInstance(
            uint grfCreateDoc,
            string pszMkDocument,
            string pszPhysicalView,
            IVsHierarchy pvHier,
            uint itemid,
            System.IntPtr punkDocDataExisting,
            out System.IntPtr ppunkDocView,
            out System.IntPtr ppunkDocData,
            out string pbstrEditorCaption,
            out System.Guid pguidCmdUI,
            out int pgrfCDW)
        {
            int retval = VSConstants.E_FAIL;

            // Initialize these to empty to start with
            ppunkDocView       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pbstrEditorCaption = "";
            pguidCmdUI         = Guid.Empty;
            pgrfCDW            = 0;

            if ((grfCreateDoc & (VSConstants.CEF_OPENFILE |
                                 VSConstants.CEF_SILENT)) == 0)
            {
                throw new ArgumentException("Only Open or Silent is valid");
            }
            if (punkDocDataExisting != IntPtr.Zero)
            {
                return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            // Instantiate a text buffer of type VsTextBuffer.
            // Note: we only need an IUnknown (object) interface for
            // this invocation.
            Guid   clsidTextBuffer = typeof(VsTextBufferClass).GUID;
            Guid   iidTextBuffer   = VSConstants.IID_IUnknown;
            object pTextBuffer     = parentPackage.CreateInstance(
                ref clsidTextBuffer,
                ref iidTextBuffer,
                typeof(object));

            if (pTextBuffer != null)
            {
                // "Site" the text buffer with the service provider we were
                // provided.
                IObjectWithSite textBufferSite = pTextBuffer as IObjectWithSite;
                if (textBufferSite != null)
                {
                    textBufferSite.SetSite(this.serviceProvider);
                }
                VsTextBuffer textBuffer = pTextBuffer as VsTextBuffer;

                // Get the language settings from options page
                Guid guidLangSvc = Guid.Empty;
                LanguageServiceOptionsPage options = parentPackage.GetLanguageServiceOptions();
                switch (options.LanguageServiceSetting)
                {
                case LanguageService.None:
                    break;

                case LanguageService.VB:
                    guidLangSvc = GuidList.guidVBLangSvc;
                    break;

                case LanguageService.CS:
                    guidLangSvc = GuidList.guidCSharpLangSvc;
                    break;

                case LanguageService.XML:
                    guidLangSvc = GuidList.guidXmlLangSvc;
                    break;

                default:
                    break;
                }

                // Set language service ID
                int hr = textBuffer.SetLanguageServiceID(ref guidLangSvc);

                IVsUserData usrData = pTextBuffer as IVsUserData;
                //     Gets a GUID value in Microsoft.VisualStudio.TextManager.Interop.IVsUserData
                //     that, when set to false, will stop the core editor for searching for a different
                //     language service.
                Guid guidVSBufferDetectLangSid = Microsoft.VisualStudio.Package.EditorFactory.GuidVSBufferDetectLangSid;
                usrData.SetData(ref guidVSBufferDetectLangSid, false);


                // Instantiate a code window of type IVsCodeWindow.
                Guid          clsidCodeWindow = typeof(VsCodeWindowClass).GUID;
                Guid          iidCodeWindow   = typeof(IVsCodeWindow).GUID;
                IVsCodeWindow pCodeWindow     =
                    (IVsCodeWindow)this.parentPackage.CreateInstance(
                        ref clsidCodeWindow,
                        ref iidCodeWindow,
                        typeof(IVsCodeWindow));
                if (pCodeWindow != null)
                {
                    // Give the text buffer to the code window.
                    // We are giving up ownership of the text buffer!
                    pCodeWindow.SetBuffer((IVsTextLines)pTextBuffer);

                    // Now tell the caller about all this new stuff
                    // that has been created.
                    ppunkDocView = Marshal.GetIUnknownForObject(pCodeWindow);
                    ppunkDocData = Marshal.GetIUnknownForObject(pTextBuffer);

                    // Specify the command UI to use so keypresses are
                    // automatically dealt with.
                    pguidCmdUI = VSConstants.GUID_TextEditorFactory;

                    // This caption is appended to the filename and
                    // lets us know our invocation of the core editor
                    // is up and running.
                    pbstrEditorCaption = " [CSVSPackageInvokeCoreEditor]";

                    retval = VSConstants.S_OK;
                }
            }
            return(retval);
        }
Beispiel #20
0
        /// <summary>
        /// Create an instance of the custom editor
        /// </summary>
        /// <param name="grfCreateDoc">Behaviour Flags</param>
        /// <param name="pszMkDocument">Document to be opened.</param>
        /// <param name="pszPhysicalView">Name of the view</param>
        /// <param name="pvHier">Pointer to the IVSHierarchy</param>
        /// <param name="itemid">Item ID for this instance</param>
        /// <param name="punkDocDataExisting">This parameter is used to determine if a document buffer (DocData object) has already been created</param>
        /// <param name="ppunkDocView">Pointer to the IUnknown interface for the DocView object</param>
        /// <param name="ppunkDocData">Pointer to the IUnknown interface for the DocData object</param>
        /// <param name="pbstrEditorCaption">Caption mentioned by the editor for the doc window</param>
        /// <param name="pguidCmdUI">the Command UI Guid. Any UI element that is visible in the editor has to use this GUID. This is specified in the .vsct file</param>
        /// <param name="pgrfCDW">Flags for CreateDocumentWindow</param>
        /// <returns></returns>
        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 variables.
            ppunkDocView       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pguidCmdUI         = GuidList.guidVSNDK_PackageEditorFactory;
            pgrfCDW            = 0;
            pbstrEditorCaption = null;
            IVsTextLines textBuffer = null;

            /// Validate Inputs
            if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
            {
                return(VSConstants.E_INVALIDARG);
            }

            if (punkDocDataExisting == IntPtr.Zero)
            { /// File is not open yet.  Create a new text buffer object.
                /// get the ILocalRegistry interface so we can use it to
                /// create the text buffer from the shell's local registry
                try
                {
                    ILocalRegistry localRegistry = (ILocalRegistry)GetService(typeof(SLocalRegistry));
                    if (localRegistry != null)
                    { /// Successfully created
                        IntPtr ptr;
                        Guid   iid = typeof(IVsTextLines).GUID;
                        Guid   CLSID_VsTextBuffer = typeof(VsTextBufferClass).GUID;
                        localRegistry.CreateInstance(CLSID_VsTextBuffer, null, ref iid, 1 /*CLSCTX_INPROC_SERVER*/, out ptr);
                        try
                        {
                            textBuffer = Marshal.GetObjectForIUnknown(ptr) as IVsTextLines;
                        }
                        finally
                        {
                            Marshal.Release(ptr); // Release RefCount from CreateInstance call
                        }

                        // It is important to site the TextBuffer object
                        IObjectWithSite objWSite = (IObjectWithSite)textBuffer;
                        if (objWSite != null)
                        {
                            Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleServiceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)GetService(typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider));
                            objWSite.SetSite(oleServiceProvider);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Can not get IVsCfgProviderEventsHelper" + ex.Message);
                    throw;
                }
            }
            else
            { /// File is already open.  Verify open document is a Text Buffer
                /// QI existing buffer for text lines
                textBuffer = Marshal.GetObjectForIUnknown(punkDocDataExisting) as IVsTextLines;
                if (textBuffer == null)
                {
                    return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                }
            }

            /// Create the Document (editor)
            EditorPane NewEditor = new EditorPane(vsServiceProvider, editorPackage, pszMkDocument, textBuffer);

            ppunkDocView       = Marshal.GetIUnknownForObject(NewEditor);
            ppunkDocData       = Marshal.GetIUnknownForObject(textBuffer);
            pbstrEditorCaption = "";
            return(VSConstants.S_OK);
        }
        public int CreateEditorInstance(
            uint grfCreateDoc,
            string pszMkDocument,
            string pszPhysicalView,
            IVsHierarchy pvHier,
            uint itemid,
            System.IntPtr punkDocDataExisting,
            out System.IntPtr ppunkDocView,
            out System.IntPtr ppunkDocData,
            out string pbstrEditorCaption,
            out Guid pguidCmdUI,
            out int pgrfCDW)
        {
            // Initialize to null
            ppunkDocView       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pguidCmdUI         = GuidList.guidVsTemplateDesignerEditorFactory;
            pgrfCDW            = 0;
            pbstrEditorCaption = null;

            // Validate inputs
            if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
            {
                return(VSConstants.E_INVALIDARG);
            }

            IVsTextLines textBuffer = null;

            if (punkDocDataExisting == IntPtr.Zero)
            {
                // punkDocDataExisting is null which means the file is not yet open.
                // We need to create a new text buffer object

                // get the ILocalRegistry interface so we can use it to
                // create the text buffer from the shell's local registry
                try
                {
                    ILocalRegistry localRegistry = (ILocalRegistry)GetService(typeof(SLocalRegistry));
                    if (localRegistry != null)
                    {
                        IntPtr ptr;
                        Guid   iid = typeof(IVsTextLines).GUID;
                        Guid   CLSID_VsTextBuffer = typeof(VsTextBufferClass).GUID;
                        localRegistry.CreateInstance(CLSID_VsTextBuffer, null, ref iid, 1 /*CLSCTX_INPROC_SERVER*/, out ptr);
                        try
                        {
                            textBuffer = Marshal.GetObjectForIUnknown(ptr) as IVsTextLines;
                        }
                        finally
                        {
                            Marshal.Release(ptr); // Release RefCount from CreateInstance call
                        }

                        // It is important to site the TextBuffer object
                        IObjectWithSite objWSite = (IObjectWithSite)textBuffer;
                        if (objWSite != null)
                        {
                            Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleServiceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)GetService(typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider));
                            objWSite.SetSite(oleServiceProvider);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Can not get IVsCfgProviderEventsHelper" + ex.Message);
                    throw;
                }
            }
            else
            {
                // punkDocDataExisting is *not* null which means the file *is* already open.
                // We need to verify that the open document is in fact a TextBuffer. If not
                // then we need to return the special error code VS_E_INCOMPATIBLEDOCDATA which
                // causes the user to be prompted to close the open file. If the user closes the
                // file then we will be called again with punkDocDataExisting as null

                // QI existing buffer for text lines
                textBuffer = Marshal.GetObjectForIUnknown(punkDocDataExisting) as IVsTextLines;
                if (textBuffer == null)
                {
                    return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                }
            }

            // Create the Document (editor)
            EditorPane NewEditor = new EditorPane(editorPackage, pszMkDocument, textBuffer);

            ppunkDocView       = Marshal.GetIUnknownForObject(NewEditor);
            ppunkDocData       = Marshal.GetIUnknownForObject(textBuffer);
            pbstrEditorCaption = "";
            return(VSConstants.S_OK);
        }
        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);
        }
        private void SiteObject(IObjectWithSite objectWithSite)
        {
            if (objectWithSite == null)
            {
                return;
            }

            var oleServiceProvider = (IOleServiceProvider)GetService(typeof(IOleServiceProvider));
            objectWithSite.SetSite(oleServiceProvider);
        }
Beispiel #24
0
        /// <include file='doc\EditorFactory.uex' path='docs/doc[@for="EditorFactory.CreateEditorInstance"]/*' />
        /// <summary>
        /// This method checks to see if the specified file is one that your editor supports
        /// and if so, creates the core text editor and associated your language service
        /// with it.  To figure out if the file is one that your editor supports it performs
        /// the following check:
        /// <list>
        /// <item>
        /// Call IsRegisteredExtension to see if the file extension is explicitly
        /// registered to your editor.
        /// </item>
        /// <item>
        /// Call GetUserDefinedEditor to see if the user has explicitly mapped the
        /// extension to your editor.
        /// </item>
        /// <item>
        /// If your editor registered the "*" extension, then it also calls
        /// IsFileExtensionWeShouldEditAnyway and IsOurFileFormat to let you sniff
        /// the file and see if you think it contains stuff that your editor recognizes
        /// </item>
        /// </list>
        /// If all this is true then it goes ahead with the next step which is to
        /// get an IVsTextLines buffer and set it up as follows:
        /// <list>
        /// <item>
        /// If existingDocData is non-null then it checks to see if it can get an
        /// IVsTextLines buffer from this docData, and if not, returns VS_E_INCOMPATIBLEDOCDATA.
        /// Otherwise it creates a new VsTextBufferClass.
        /// </item>
        /// Calls IVsUserData.SetData on the IVsTextLines buffer with any code page prompt
        /// flags you have provided via the CodePagePrompt property.
        /// </list>
        /// <list>
        /// Calls SetLanguageServiceID to pass in your language service Guid and
        /// sets the GuidVSBufferDetectLangSid IVsUserData to false to stop the core
        /// text editor from looking up a different language service.
        /// </list>
        /// Lastly it calls CreateEditorView to create the docView.
        /// </summary>
        public virtual int CreateEditorInstance(uint createDocFlags, string moniker, string physicalView, IVsHierarchy pHier, uint itemid, IntPtr existingDocData, out IntPtr docView, out IntPtr docData, out string editorCaption, out Guid cmdUI, out int cancelled)
        {
            docView       = IntPtr.Zero;
            docData       = IntPtr.Zero;
            editorCaption = null;
            cmdUI         = Guid.Empty;
            cancelled     = 0;
            int hr = VSErr.S_OK;

            if (this.promptFlags == __PROMPTONLOADFLAGS.codepagePrompt && existingDocData != IntPtr.Zero)
            {
                //since we are trying to open with encoding just return
                hr = (int)VSConstants.VS_E_INCOMPATIBLEDOCDATA;
                goto cleanup;
            }

            bool takeover = false;

            if (!string.IsNullOrEmpty(moniker))
            {
                string ext = Path.GetExtension(moniker);
                docData       = IntPtr.Zero;
                docView       = IntPtr.Zero;
                editorCaption = null;

                bool openSpecific = (createDocFlags & (uint)__VSCREATEEDITORFLAGS2.CEF_OPENSPECIFIC) != 0;

                bool isOurs        = IsRegisteredExtension(ext);
                bool isUserDefined = (GetUserDefinedEditor(ext) == this.GetType().GUID);

                // If this file extension belongs to a different language service, then we should not open it,
                // unless the user specifically requested our editor in the Open With... dialog.
                if (!isOurs && !isUserDefined && !this.IsFileExtensionWeShouldEditAnyway(ext) && !openSpecific)
                {
                    return(VSConstants.VS_E_UNSUPPORTEDFORMAT);
                }

                takeover = (CheckAllFileTypes() && !isOurs);
                if (takeover && !isOurs && !isUserDefined && !openSpecific)
                {
                    if (!IsOurFileFormat(moniker))
                    {
                        return(VSConstants.VS_E_UNSUPPORTEDFORMAT);
                    }
                }
            }

            IVsTextLines buffer = null;

            if (existingDocData != IntPtr.Zero)
            {
                object dataObject = Marshal.GetObjectForIUnknown(existingDocData);
                buffer = dataObject as IVsTextLines;
                if (buffer == null)
                {
                    IVsTextBufferProvider bp = dataObject as IVsTextBufferProvider;
                    if (bp != null)
                    {
                        Marshal.ThrowExceptionForHR(bp.GetTextBuffer(out buffer));
                    }
                }
                if (buffer == null)
                {
                    // unknown docData type then, so we have to force VS to close the other editor.
                    hr = VSConstants.VS_E_INCOMPATIBLEDOCDATA;
                    goto cleanup;
                }
            }
            else
            {
                // Create a new IVsTextLines buffer.
                Type textLinesType = typeof(IVsTextLines);
                Guid riid          = textLinesType.GUID;
                Guid clsid         = typeof(VsTextBufferClass).GUID;
                buffer = (IVsTextLines)package.CreateInstance(ref clsid, ref riid, textLinesType);
                if (!string.IsNullOrEmpty(moniker))
                {
                    IVsUserData iud = buffer as IVsUserData;
                    if (iud != null)
                    {
                        Guid GUID_VsBufferMoniker = typeof(IVsUserData).GUID;
                        // Must be set in time for language service GetColorizer call in case the colorizer
                        // is file name dependent.
                        Marshal.ThrowExceptionForHR(iud.SetData(ref GUID_VsBufferMoniker, moniker));
                    }
                }
                IObjectWithSite ows = buffer as IObjectWithSite;
                if (ows != null)
                {
                    ows.SetSite(this.site.GetService(typeof(IOleServiceProvider)));
                }
            }

            if (this.promptFlags == __PROMPTONLOADFLAGS.codepagePrompt && buffer is IVsUserData)
            {
                IVsUserData iud = (IVsUserData)buffer;
                Guid        GUID_VsBufferEncodingPromptOnLoad = new Guid(0x99ec03f0, 0xc843, 0x4c09, 0xbe, 0x74, 0xcd, 0xca, 0x51, 0x58, 0xd3, 0x6c);
                Marshal.ThrowExceptionForHR(iud.SetData(ref GUID_VsBufferEncodingPromptOnLoad, (uint)this.CodePagePrompt));
            }

            Guid langSid = GetLanguageServiceGuid();

            if (langSid != Guid.Empty)
            {
                Guid vsCoreSid = new Guid("{8239bec4-ee87-11d0-8c98-00c04fc2ab22}");
                Guid currentSid;
                Marshal.ThrowExceptionForHR(buffer.GetLanguageServiceID(out currentSid));
                // If the language service is set to the default SID, then
                // set it to our language
                if (currentSid == vsCoreSid)
                {
                    Marshal.ThrowExceptionForHR(buffer.SetLanguageServiceID(ref langSid));
                }
                else if (currentSid != langSid)
                {
                    // Some other language service has it, so return VS_E_INCOMPATIBLEDOCDATA
                    hr = VSConstants.VS_E_INCOMPATIBLEDOCDATA;
                    goto cleanup;
                }

                takeover = true;
            }

            if (takeover)
            {
                IVsUserData vud = (IVsUserData)buffer;
                Guid        bufferDetectLang = GuidVSBufferDetectLangSid;
                Marshal.ThrowExceptionForHR(vud.SetData(ref bufferDetectLang, false));
            }

            if (existingDocData != IntPtr.Zero)
            {
                docData = existingDocData;
                Marshal.AddRef(docData);
            }
            else
            {
                docData = Marshal.GetIUnknownForObject(buffer);
            }
            docView = CreateEditorView(moniker, buffer, physicalView, out editorCaption, out cmdUI);

            if (docView == IntPtr.Zero)
            {
                // We couldn't create the view, so return this special error code so
                // VS can try another editor factory.
                hr = VSConstants.VS_E_UNSUPPORTEDFORMAT;
            }

cleanup:
            if (docView == IntPtr.Zero)
            {
                if (existingDocData != docData && docData != IntPtr.Zero)
                {
                    Marshal.Release(docData);
                    docData = IntPtr.Zero;
                }
            }
            return(hr);
        }
        private IntPtr CreateDesignerView(IVsHierarchy hierarchy, uint itemid, IVsTextLines textLines, ref string editorCaption, ref Guid cmdUI, string documentMoniker)
        {
            // Request the Designer Service
            IVSMDDesignerService designerService = (IVSMDDesignerService)GetService(typeof(IVSMDDesignerService));

            try
            {
                // Get the service provider
                IOleServiceProvider provider = serviceProvider.GetService(typeof(IOleServiceProvider)) as IOleServiceProvider;
                IObjectWithSite     ows      = (IObjectWithSite)textLines;
                ows.SetSite(provider);
                // Create loader for the designer
                LimnorXmlDesignerLoader2 designerLoader = new LimnorXmlDesignerLoader2(documentMoniker, itemid);

                // Create the designer using the provider and the loader
                IVSMDDesigner designer = designerService.CreateDesigner(provider, designerLoader);

                designerLoader.AddComponentChangeEventHandler();

                // Retrieve the design surface
                DesignSurface designSurface = (DesignSurface)designer;

                IDesignerHost dh = (IDesignerHost)designSurface.GetService(typeof(IDesignerHost));
                dh.AddService(typeof(INameCreationService), new NameCreationService());

                IServiceContainer serviceContainer = dh.GetService(typeof(ServiceContainer)) as IServiceContainer;
                dh.AddService(typeof(IDesignerSerializationService), new DesignerSerializationService(serviceContainer));
                //DesignerSerializationService uses CodeDomComponentSerializationService
                CodeDomComponentSerializationService codeDomComponentSerializationService = new CodeDomComponentSerializationService(serviceContainer);
                dh.AddService(typeof(ComponentSerializationService), codeDomComponentSerializationService);

                //LimnorUndoEngine undoEngine = new LimnorUndoEngine(serviceContainer);
                //undoEngine.Enabled = false;//not use undo during loading
                //dh.AddService(typeof(UndoEngine), undoEngine);
                //object v = dh.GetService(typeof(IOleUndoManager));
                //if (v != null)
                //{
                //    object v2 = dh.GetService(typeof(UndoEngine));
                //    if (v2 == null)
                //    {
                //        dh.AddService(typeof(UndoEngine), v);
                //    }
                //}
                // Create pane with this surface
                LimnorXmlPane2 limnorXmlPane = new LimnorXmlPane2(designSurface);//, winControlPME);

                // Get command guid from designer
                cmdUI         = limnorXmlPane.CommandGuid;
                editorCaption = " [Design]";
                if (designerLoader.IsSetup)
                {
                }
                else
                {
                    if (limnorXmlPane.Loader.ObjectMap != null)
                    {
                        limnorXmlPane.BeginApplyConfig();
                    }
                }
                // Return LimnorXmlPane
                return(Marshal.GetIUnknownForObject(limnorXmlPane));
            }
            catch (Exception ex)
            {
                MathNode.Log(ex);
                //Trace.WriteLine("Exception: " + ex.Message);
                // Just rethrow for now
                throw;
            }
        }
Beispiel #26
0
        public int CreateEditorInstance(
            uint grfCreateDoc,                 // Flags determining when to create the editor. Only open and silent flags are valid
            string pszMkDocument,              // path to the file to be opened
            string pszPhysicalView,            // name of the physical view
            IVsHierarchy pvHier,               // pointer to the IVsHierarchy interface
            uint itemid,                       // Item identifier of this editor instance
            System.IntPtr punkDocDataExisting, // This parameter is used to determine if a document buffer (DocData object) has already been created
            out System.IntPtr ppunkDocView,    // Pointer to the IUnknown interface for the DocView object
            out System.IntPtr ppunkDocData,    // Pointer to the IUnknown interface for the DocData object
            out string pbstrEditorCaption,     // Caption mentioned by the editor for the doc window
            out Guid pguidCmdUI,               // the Command UI Guid. Any UI element that is visible in the editor has to use this GUID. This is specified in the .vsct file.
            out int pgrfCDW)                   // Flags for CreateDocumentWindow
        {
            // Initialize to null:
            ppunkDocView       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pguidCmdUI         = GuidList.guidEditorFactory;
            pgrfCDW            = 0;
            pbstrEditorCaption = null;

            // Quit if the project is not of type "C#/XAML for HTML5":
            bool isCSharpXamlForHtml5 = IsCSharpXamlForHtml5(pszMkDocument);

            if (!isCSharpXamlForHtml5)
            {
                return(VSConstants.VS_E_UNSUPPORTEDFORMAT);
            }

            // Validate inputs:
            if ((grfCreateDoc & (VSConstants.CEF_OPENFILE | VSConstants.CEF_SILENT)) == 0)
            {
                return(VSConstants.E_INVALIDARG);
            }


            //TEST:
            if (punkDocDataExisting != IntPtr.Zero)
            {
                return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            IVsTextLines textBuffer = null;

            // punkDocDataExisting is null which means the file is not yet open. We need to create a new text buffer object

            // Get the ILocalRegistry interface so we can use it to create the text buffer from the shell's local registry:
            try
            {
                ILocalRegistry localRegistry = (ILocalRegistry)GetService(typeof(SLocalRegistry));
                if (localRegistry != null)
                {
                    IntPtr ptr;
                    Guid   iid = typeof(IVsTextLines).GUID;
                    Guid   CLSID_VsTextBuffer = typeof(VsTextBufferClass).GUID;
                    localRegistry.CreateInstance(CLSID_VsTextBuffer, null, ref iid, 1, out ptr);
                    try
                    {
                        textBuffer = Marshal.GetObjectForIUnknown(ptr) as IVsTextLines;
                    }
                    finally
                    {
                        Marshal.Release(ptr); // Release RefCount from CreateInstance call
                    }

                    IObjectWithSite objWSite = (IObjectWithSite)textBuffer; // It is important to site the TextBuffer object
                    if (objWSite != null)
                    {
                        Microsoft.VisualStudio.OLE.Interop.IServiceProvider oleServiceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)GetService(typeof(Microsoft.VisualStudio.OLE.Interop.IServiceProvider));
                        objWSite.SetSite(oleServiceProvider);
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Can not get IVsCfgProviderEventsHelper" + ex.Message);
                throw;
            }

            ppunkDocData = Marshal.GetIUnknownForObject(textBuffer);

            var editorControl = new EditorPane(textBuffer, pszMkDocument, pvHier, itemid, pszPhysicalView, ppunkDocData, vsServiceProvider);

            ppunkDocView = Marshal.GetIUnknownForObject(editorControl);

            pbstrEditorCaption = "";
            return(VSConstants.S_OK);
        }
Beispiel #27
0
        /// <summary>
        /// Invokes the specified generator
        /// </summary>
        /// <param name="fileNode">The node on which to invoke the generator.</param>
        protected internal virtual void InvokeGenerator(FileNode fileNode)
        {
            if (fileNode == null)
            {
                throw new ArgumentNullException("fileNode");
            }

            SingleFileGeneratorNodeProperties nodeproperties = fileNode.NodeProperties as SingleFileGeneratorNodeProperties;

            if (nodeproperties == null)
            {
                throw new InvalidOperationException();
            }

            string customToolProgID = nodeproperties.CustomTool;

            if (string.IsNullOrEmpty(customToolProgID))
            {
                return;
            }

            string customToolNamespace = nodeproperties.CustomToolNamespace;

            try
            {
                if (!this.runningGenerator)
                {
                    //Get the buffer contents for the current node
                    string moniker = fileNode.GetMkDocument();

                    this.runningGenerator = true;

                    //Get the generator
                    IVsSingleFileGenerator generator;
                    int generateDesignTimeSource;
                    int generateSharedDesignTimeSource;
                    int generateTempPE;
                    SingleFileGeneratorFactory factory = new SingleFileGeneratorFactory(this.projectMgr.ProjectGuid, this.projectMgr.Site);
                    ErrorHandler.ThrowOnFailure(factory.CreateGeneratorInstance(customToolProgID, out generateDesignTimeSource, out generateSharedDesignTimeSource, out generateTempPE, out generator));

                    //Check to see if the generator supports siting
                    IObjectWithSite objWithSite = generator as IObjectWithSite;
                    if (objWithSite != null)
                    {
                        objWithSite.SetSite(fileNode.OleServiceProvider);
                    }

                    //Determine the namespace
                    if (string.IsNullOrEmpty(customToolNamespace))
                    {
                        customToolNamespace = this.ComputeNamespace(moniker);
                    }

                    //Run the generator
                    IntPtr[] output = new IntPtr[1];
                    output[0] = IntPtr.Zero;
                    uint   outPutSize;
                    string extension;
                    ErrorHandler.ThrowOnFailure(generator.DefaultExtension(out extension));

                    //Find if any dependent node exists
                    string        dependentNodeName = Path.GetFileNameWithoutExtension(fileNode.FileName) + extension;
                    HierarchyNode dependentNode     = fileNode.FirstChild;
                    while (dependentNode != null)
                    {
                        if (string.Compare(dependentNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon), fileNode.FileName, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            dependentNodeName = ((FileNode)dependentNode).FileName;
                            break;
                        }

                        dependentNode = dependentNode.NextSibling;
                    }

                    //If you found a dependent node.
                    if (dependentNode != null)
                    {
                        //Then check out the node and dependent node from SCC
                        if (!this.CanEditFile(dependentNode.GetMkDocument()))
                        {
                            throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                        }
                    }
                    else //It is a new node to be added to the project
                    {
                        // Check out the project file if necessary.
                        if (!this.projectMgr.QueryEditProjectFile(false))
                        {
                            throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                        }
                    }
                    IVsTextStream stream;
                    string        inputFileContents = this.GetBufferContents(moniker, out stream);

                    ErrorHandler.ThrowOnFailure(generator.Generate(moniker, inputFileContents, customToolNamespace, output, out outPutSize, this));
                    byte[] data = new byte[outPutSize];

                    if (output[0] != IntPtr.Zero)
                    {
                        Marshal.Copy(output[0], data, 0, (int)outPutSize);
                        Marshal.FreeCoTaskMem(output[0]);
                    }

                    //Todo - Create a file and add it to the Project
                    this.UpdateGeneratedCodeFile(fileNode, data, (int)outPutSize, dependentNodeName);
                }
            }
            finally
            {
                this.runningGenerator = false;
            }
        }
 /// <summary>Extension method to simplify using the <see cref="IObjectWithSite.GetSite"/> method.</summary>
 /// <typeparam name="T">Type of the interface to get.</typeparam>
 /// <param name="ows">An <see cref="IObjectWithSite"/> instance.</param>
 /// <returns>Receives the interface pointer requested in <typeparamref name="T"/>.</returns>
 public static T GetSite <T>(this IObjectWithSite ows) where T : class
 {
     ows.GetSite(typeof(T).GUID, out var pSite).ThrowIfFailed(); return((T)pSite);
 }
        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)
        {
            int retval = VSConstants.E_FAIL;

            // Initialize these to empty to start with
            ppunkDocView       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pbstrEditorCaption = "";
            pguidCmdUI         = Guid.Empty;
            pgrfCDW            = 0;

            if ((grfCreateDoc & (VSConstants.CEF_OPENFILE |
                                 VSConstants.CEF_SILENT)) == 0)
            {
                throw new ArgumentException("Only Open or Silent is valid");
            }
            if (punkDocDataExisting != IntPtr.Zero)
            {
                return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            // Instantiate a text buffer of type VsTextBuffer.
            // Note: we only need an IUnknown (object) interface for
            // this invocation.
            Guid   clsidTextBuffer = typeof(VsTextBufferClass).GUID;
            Guid   iidTextBuffer   = VSConstants.IID_IUnknown;
            object pTextBuffer     = pTextBuffer = parentPackage.CreateInstance(
                ref clsidTextBuffer,
                ref iidTextBuffer,
                typeof(object));

            if (pTextBuffer != null)
            {
                // "Site" the text buffer with the service provider we were
                // provided.
                IObjectWithSite textBufferSite = pTextBuffer as IObjectWithSite;
                if (textBufferSite != null)
                {
                    textBufferSite.SetSite(this.serviceProvider);
                }

                // Instantiate a code window of type IVsCodeWindow.
                Guid          clsidCodeWindow = typeof(VsCodeWindowClass).GUID;
                Guid          iidCodeWindow   = typeof(IVsCodeWindow).GUID;
                IVsCodeWindow pCodeWindow     =
                    (IVsCodeWindow)this.parentPackage.CreateInstance(
                        ref clsidCodeWindow,
                        ref iidCodeWindow,
                        typeof(IVsCodeWindow));
                if (pCodeWindow != null)
                {
                    // Give the text buffer to the code window.
                    // We are giving up ownership of the text buffer!
                    pCodeWindow.SetBuffer((IVsTextLines)pTextBuffer);

                    // Now tell the caller about all this new stuff
                    // that has been created.
                    ppunkDocView = Marshal.GetIUnknownForObject(pCodeWindow);
                    ppunkDocData = Marshal.GetIUnknownForObject(pTextBuffer);

                    // Specify the command UI to use so keypresses are
                    // automatically dealt with.
                    pguidCmdUI = VSConstants.GUID_TextEditorFactory;

                    // This caption is appended to the filename and
                    // lets us know our invocation of the core editor
                    // is up and running.
                    pbstrEditorCaption = " [PlantUml]";

                    retval = VSConstants.S_OK;
                }
            }
            return(retval);
        }
Beispiel #30
0
        protected internal virtual void InvokeGeneratorEx(FileNode fileNode, String document, bool runEvenIfNotDirty)
        {
            base.InvokeGenerator(fileNode);
            Utilities.ArgumentNotNull("fileNode", fileNode);

            SingleFileGeneratorNodeProperties nodeproperties = fileNode.NodeProperties as SingleFileGeneratorNodeProperties;

            if (nodeproperties == null)
            {
                throw new InvalidOperationException();
            }

            string customToolProgID = nodeproperties.CustomTool;

            if (string.IsNullOrEmpty(customToolProgID))
            {
                return;
            }

            // not sure what to do if BuildAction is set to "MSBuild:Compile".  IronPython doesn't handle this correctly either.
            // This build action is set for .xaml files but doing nothing doesn't seem to cause problems, so for now we ignore this
            // generator type and do nothing too.  If we don't do this, we get lots of message boxes when the clsid of this non-existent
            // single file generator isn't found.

            // We should try to find out what the proper action is here.  There is no "MSBuild:Compile" entry in the registry
            // for the C# or VB project system single file generators, so there must be some special handling for this build type
            // otherwise it would just be blank.  Naturally, the IronPython sample isn't any help here.

            if (customToolProgID.StartsWith("MSBuild:Compile", StringComparison.OrdinalIgnoreCase))
            {
                var project = fileNode.ProjectMgr as XSharpProjectNode;
                if (project.IsXamlFile(document))
                {
                    // need to generate the .g.prg file.
                    project.Build(project.CurrentConfig.ConfigCanonicalName, "BuildGenerateSources"); //  BuildGenerateSources
                }
                // The C# project system then calls a InvokeMsBuild method with the following contents

                /*
                 * HRESULT CVsProjBaseFileNode::InvokeMSBuildTarget(_In_z_ LPCWSTR wszMSBuildTarget)
                 * {
                 *  HRESULT hr = NOERROR;
                 *
                 *  if (wszMSBuildTarget != NULL)
                 *  {
                 *      CLangBuildMgr *pBuildMgr = GetProject()->GetBuildMgr();
                 *      CComPtr<MSBuildEngine::IProject> srpMSBuildProject = pBuildMgr->GetMSBuildProject();
                 *
                 *      if (CXMakeHelper::DoesTargetExist(srpMSBuildProject, wszMSBuildTarget) && pBuildMgr->HasPassedSecurityChecks())
                 *      {
                 *          // Initialize the build engine for this project and configuration.
                 *          CSmartMSBuildInitializer smsbi;
                 *          CLangProjectConfig *pProjConfig = pBuildMgr->GetConfigs()->GetActiveConfig();
                 *          hr = smsbi.Initialize(pBuildMgr, pProjConfig);
                 *
                 *          if (SUCCEEDED(hr))
                 *          {
                 *              // Build the specified target in the MSBuild project.
                 *              hr = pBuildMgr->BuildTarget(wszMSBuildTarget);
                 *          }
                 *
                 *          // Don't bother keeping the return value here--we want to
                 *          // return failure from Initialize or BuildTarget instead.
                 *          smsbi.Restore(pBuildMgr);
                 *      }
                 *  }
                 *
                 *  return hr;
                 * }
                 */
                return;
            }

            string customToolNamespace = nodeproperties.CustomToolNamespace;

            try
            {
                if (!this.runningGenerator)
                {
                    //Find if any dependent node exists
                    string        dependentNodeName = null;
                    HierarchyNode dependentNode     = fileNode.FirstChild;

                    while (dependentNode != null)
                    {
                        string dependentUpon = dependentNode.ItemNode.GetMetadata(ProjectFileConstants.DependentUpon);

                        if (!String.IsNullOrEmpty(dependentUpon))
                        {
                            if (!Path.IsPathRooted(dependentUpon))
                            {
                                dependentUpon = Path.Combine(Path.GetDirectoryName(fileNode.Url), dependentUpon);
                            }

                            if (string.Compare(dependentUpon, fileNode.Url, StringComparison.OrdinalIgnoreCase) == 0)
                            {
                                dependentNodeName = ((FileNode)dependentNode).FileName;
                                break;
                            }
                        }

                        dependentNode = dependentNode.NextSibling;
                    }

                    bool outputOutOfDate = dependentNodeName == null;

                    if ((!runEvenIfNotDirty) && !outputOutOfDate)
                    {
                        string generatedFile = Path.Combine(Path.GetDirectoryName(fileNode.GetMkDocument()), dependentNodeName);

                        outputOutOfDate = !File.Exists(generatedFile);

                        if (!outputOutOfDate)
                        {
                            outputOutOfDate = File.GetLastWriteTime(fileNode.GetMkDocument()) > File.GetLastWriteTime(generatedFile);

                            if (!outputOutOfDate)
                            {
                                IVsHierarchy      rdtHier;
                                IVsPersistDocData perDocData;
                                uint cookie;
                                outputOutOfDate = this.VerifyFileDirtyInRdt(document, out rdtHier, out perDocData, out cookie);
                            }
                        }
                    }

                    //if (runEvenIfNotDirty || outputOutOfDate)
                    {
                        //Get the buffer contents for the current node
                        string moniker = fileNode.GetMkDocument();

                        this.runningGenerator = true;
                        anyGeneratorsRunning++;

                        //Get the generator
                        IVsSingleFileGenerator generator;
                        int generateDesignTimeSource;
                        int generateSharedDesignTimeSource;
                        int generateTempPE;
                        SingleFileGeneratorFactory factory = new SingleFileGeneratorFactory(this.ProjectMgr.ProjectGuid, this.ProjectMgr.Site);
                        ErrorHandler.ThrowOnFailure(factory.CreateGeneratorInstance(customToolProgID, out generateDesignTimeSource, out generateSharedDesignTimeSource, out generateTempPE, out generator));

                        //Check to see if the generator supports siting
                        IObjectWithSite objWithSite = generator as IObjectWithSite;
                        if (objWithSite != null)
                        {
                            objWithSite.SetSite(fileNode.OleServiceProvider);
                        }

                        //Determine the namespace
                        if (string.IsNullOrEmpty(customToolNamespace))
                        {
                            customToolNamespace = this.ComputeNamespace(moniker);
                        }

                        //Run the generator
                        IntPtr[] output = new IntPtr[1];
                        output[0] = IntPtr.Zero;
                        uint outPutSize;

                        if (dependentNodeName == null)
                        {
                            string extension = null;
                            try
                            {
                                generator.DefaultExtension(out extension);
                            }
                            catch (Exception e)
                            {
                                if (System.Diagnostics.Debugger.IsAttached)
                                {
                                    Debug.WriteLine(e);
                                }
                            }
                            if (!String.IsNullOrEmpty(extension))
                            {
                                dependentNodeName = Path.GetFileNameWithoutExtension(fileNode.FileName) + extension;
                            }
                            else
                            {
                                dependentNodeName = fileNode.FileName;
                            }
                        }


                        //If you found a dependent node.
                        if (dependentNode != null)
                        {
                            //Then check out the node and dependent node from SCC
                            if (!this.CanEditFile(dependentNode.GetMkDocument()))
                            {
                                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                            }
                        }
                        else //It is a new node to be added to the project
                        {
                            // Check out the project file if necessary.
                            if (!this.ProjectMgr.QueryEditProjectFile(false))
                            {
                                throw Marshal.GetExceptionForHR(VSConstants.OLE_E_PROMPTSAVECANCELLED);
                            }
                        }
                        IVsTextStream stream;
                        string        inputFileContents = this.GetBufferContents(moniker, out stream);

                        var    res  = generator.Generate(moniker, inputFileContents, customToolNamespace, output, out outPutSize, this);
                        byte[] data = new byte[outPutSize];

                        if (output[0] != IntPtr.Zero)
                        {
                            Marshal.Copy(output[0], data, 0, (int)outPutSize);
                            Marshal.FreeCoTaskMem(output[0]);
                        }

                        //Todo - Create a file and add it to the Project
                        string fileToAdd = this.UpdateGeneratedCodeFile(fileNode, data, (int)outPutSize, dependentNodeName, dependentNode);
                    }
                }
            }
            finally
            {
                this.runningGenerator = false;
                anyGeneratorsRunning--;
            }
        }
 /// <summary>
 /// Initializes a new instance of the
 /// <see cref="GlobalDataSetGenerator"/> class.
 /// </summary>
 public GlobalDataSetGenerator()
 {
     this.msDataSetGenerator     = GetGenerator(MSDataSetGeneratorGuid);
     this.msDataSetGeneratorRN   = (IVsRefactorNotify)this.msDataSetGenerator;
     this.msDataSetGeneratorSite = (IObjectWithSite)this.msDataSetGenerator;
 }