protected override void InitializeLanguageService(IVsTextLines textLines)
        {
            var userData = textLines as IVsUserData;
            if (userData == null) return;
            var langSid = typeof(PowerShellLanguageInfo).GUID;
            if (langSid == Guid.Empty) return;

            var vsCoreSid = new Guid("{8239bec4-ee87-11d0-8c98-00c04fc2ab22}");
            Guid currentSid;
            ErrorHandler.ThrowOnFailure(textLines.GetLanguageServiceID(out currentSid));
            // If the language service is set to the default SID, then
            // set it to our language
            if (currentSid == vsCoreSid)
            {
                ErrorHandler.ThrowOnFailure(textLines.SetLanguageServiceID(ref langSid));
            }
            else if (currentSid != langSid)
            {
                // Some other language service has it, so return VS_E_INCOMPATIBLEDOCDATA
                throw new COMException("Incompatible doc data", VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            var bufferDetectLang = VSConstants.VsTextBufferUserDataGuid.VsBufferDetectLangSID_guid;
            ErrorHandler.ThrowOnFailure(userData.SetData(ref bufferDetectLang, false));
        }
Example #2
0
        public int OnLoadCompleted(int fReload)
        {
            // Set language service ID as early as possible, since it may change content type of the buffer,
            // e.g. in a weird scenario when someone does "Open With X Editor" on an Y file. Calling this
            // will change content type to the one language service specifies instead of the default one for
            // the file extension, and will ensure that correct editor factory is used.
            _textLines.SetLanguageServiceID(ref _languageServiceGuid);
            var adapterService = _services.GetService <IVsEditorAdaptersFactoryService>();
            var diskBuffer     = adapterService.GetDocumentBuffer(_textLines);

            Debug.Assert(diskBuffer != null);

            try {
                var editorInstance = diskBuffer.GetService <IEditorViewModel>();
                if (editorInstance == null)
                {
                    var locator         = _services.GetService <IContentTypeServiceLocator>();
                    var instancefactory = locator.GetService <IEditorViewModelFactory>(diskBuffer.ContentType.TypeName);

                    Debug.Assert(instancefactory != null, "No editor factory found for the provided text buffer");
                    editorInstance = instancefactory.CreateEditorViewModel(diskBuffer);
                }

                Debug.Assert(editorInstance != null);
                adapterService.SetDataBuffer(_textLines, editorInstance.ViewBuffer.As <ITextBuffer>());
            } finally {
                cp.Unadvise(cookie);
                cookie     = 0;
                _textLines = null;
                _trackers.Remove(this);
            }
            return(VSConstants.S_OK);
        }
        protected void InitializeLanguageService(IVsTextLines textLines, Guid langSid)
        {
            var userData = textLines as IVsUserData;

            if (userData != null)
            {
                if (langSid != Guid.Empty)
                {
                    var vsCoreSid = new Guid("{8239bec4-ee87-11d0-8c98-00c04fc2ab22}");
                    ErrorHandler.ThrowOnFailure(textLines.GetLanguageServiceID(out var currentSid));
                    // If the language service is set to the default SID, then
                    // set it to our language
                    if (currentSid == vsCoreSid)
                    {
                        ErrorHandler.ThrowOnFailure(textLines.SetLanguageServiceID(ref langSid));
                    }
                    else if (currentSid != langSid)
                    {
                        // Some other language service has it, so return VS_E_INCOMPATIBLEDOCDATA
                        throw new COMException("Incompatible doc data", VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                    }

                    var bufferDetectLang = VSConstants.VsTextBufferUserDataGuid.VsBufferDetectLangSID_guid;
                    ErrorHandler.ThrowOnFailure(userData.SetData(ref bufferDetectLang, false));
                }
            }
        }
            public int OnLoadCompleted(int fReload) {
                _cp.Unadvise(_cookie);

                Guid langSvcGuid = typeof(NodejsLanguageInfo).GUID;
                _textLines.SetLanguageServiceID(ref langSvcGuid);
                
                return VSConstants.S_OK;
            }
            public int OnLoadCompleted(int fReload)
            {
                ThreadHelper.ThrowIfNotOnUIThread();
                _connectionPoint.Unadvise(_cookie);
                _textLines.SetLanguageServiceID(ref _languageServiceId);

                return(VSConstants.S_OK);
            }
            public int OnLoadCompleted(int fReload)
            {
                _connectionPoint.Unadvise(_cookie);

                var languageServiceId = typeof(GaugeLanguageInfo).GUID;

                _textLines.SetLanguageServiceID(ref languageServiceId);

                return(VSConstants.S_OK);
            }
Example #7
0
            public int OnLoadCompleted(int fReload)
            {
                _cp.Unadvise(_cookie);

                Guid langSvcGuid = _editorFactory.GetLanguageInfoType().GUID;

                _textLines.SetLanguageServiceID(ref langSvcGuid);

                return(VSConstants.S_OK);
            }
Example #8
0
        /// <summary>
        /// Here we simply host the visual studio core text editor.
        /// </summary>
        public virtual void 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)
        {
            string ext = Path.GetExtension(moniker).ToLower();

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

            if (takeover && !IsOurKindOfFile(moniker))
            {
                throw new System.Runtime.InteropServices.COMException("", (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.Unwrap());

            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;
        }
Example #9
0
        /// <summary>
        /// Creates a new ConsoleWindow object.
        /// This constructor uses the service provider passed as an argument to create and initialize
        /// the text buffer.
        /// </summary>
        public ConsoleWindow(IServiceProvider provider) :
            base(null)
        {
            if (null == provider)
            {
                throw new ArgumentNullException("provider");
            }
            globalProvider = provider;

            // Create the text buffer.
            textLines = (IVsTextLines)CreateObject(typeof(VsTextBufferClass), typeof(IVsTextLines));
            // Get a reference to the global service provider.
            IOleServiceProvider nativeProvider = (IOleServiceProvider)globalProvider.GetService(typeof(IOleServiceProvider));

            // The text buffer must be sited with the global service provider.
            ((IObjectWithSite)textLines).SetSite(nativeProvider);
            // Set the buffer as read-only. The user should be able to change the content of the
            // buffer only if the engine is started.
            uint flags;

            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
                textLines.GetStateFlags(out flags));
            flags |= (uint)Microsoft.VisualStudio.TextManager.Interop.BUFFERSTATEFLAGS.BSF_USER_READONLY;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
                textLines.SetStateFlags(flags));

            // Set the GUID of the language service that will handle this text buffer
            Guid languageGuid = typeof(FoxProLanguage).GUID;

            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
                textLines.SetLanguageServiceID(ref languageGuid));

            // Initialize the history
            history = new HistoryBuffer();

            // Create the stream on top of the text buffer.
            textStream = new TextBufferStream(textLines);

            // Initialize the engine.
            InitializeEngine();

            // Set the title of the window.
            this.Caption = Resources.ToolWindowTitle;

            // Set the icon of the toolwindow.
            this.BitmapResourceID = 301;
            this.BitmapIndex      = 0;
        }
        public int OnLoadCompleted(int fReload)
        {
            var adapterService = VsAppShell.Current.ExportProvider.GetExport <IVsEditorAdaptersFactoryService>().Value;

            // Set language service ID as early as possible, since it may change content type of the buffer,
            // e.g. in a weird scenario when someone does "Open With X Editor" on an Y file. Calling this
            // will change content type to the one language service specifies instead of the default one for
            // the file extension, and will ensure that correct editor factory is used.
            _textLines.SetLanguageServiceID(ref _languageServiceGuid);
            ITextBuffer diskBuffer = adapterService.GetDocumentBuffer(_textLines);

            Debug.Assert(diskBuffer != null);

            try {
                var editorInstance = ServiceManager.GetService <IEditorInstance>(diskBuffer);
                if (editorInstance == null)
                {
                    var importComposer  = new ContentTypeImportComposer <IEditorFactory>(VsAppShell.Current.CompositionService);
                    var instancefactory = importComposer.GetImport(diskBuffer.ContentType.TypeName);
                    Debug.Assert(instancefactory != null);

                    var documentFactoryImportComposer = new ContentTypeImportComposer <IVsEditorDocumentFactory>(VsAppShell.Current.CompositionService);
                    var documentFactory = documentFactoryImportComposer.GetImport(diskBuffer.ContentType.TypeName);
                    Debug.Assert(documentFactory != null);

                    editorInstance = instancefactory.CreateEditorInstance(diskBuffer, documentFactory);
                }

                Debug.Assert(editorInstance != null);
                adapterService.SetDataBuffer(_textLines, editorInstance.ViewBuffer);
            } finally {
                cp.Unadvise(cookie);
                cookie = 0;

                _textLines = null;
                _hierarchy = null;

                _trackers.Remove(this);
                _trackers = null;
            }

            return(VSConstants.S_OK);
        }
Example #11
0
        private IVsTextLines GetTextBuffer(IntPtr docDataExisting, Guid languageServiceId)
        {
            IVsTextLines textLines = null;

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

                // set the buffer's site
                ((IObjectWithSite)textLines).SetSite(VsServiceProvider);
                textLines.SetLanguageServiceID(ref languageServiceId);
            }
            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
                    IVsTextBufferProvider textBufferProvider = dataObject as IVsTextBufferProvider;

                    if (textBufferProvider != null)
                    {
                        textBufferProvider.GetTextBuffer(out textLines);
                    }
                }
            }

            if (textLines == null)
            {
                // Unknown docData type then, so we have to force VS to close the other editor.
                ErrorHandler.ThrowOnFailure((int)VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            return(textLines);
        }
            private void InitContainedLanguage()
            {
                IVsTextLines         vsTextLines = EnsureBufferCoordinator();
                IVsContainedLanguage vsContainedLanguage;

                languageFactory.GetLanguage(hierarchy, MarkdownCodeProject.FileItemId, _textBufferCoordinator, out vsContainedLanguage);

                if (vsContainedLanguage == null)
                {
                    Logger.Log("Markdown: Couldn't get IVsContainedLanguage for " + ProjectionBuffer.IProjectionBuffer.ContentType);
                    return;
                }

                Guid langService;

                vsContainedLanguage.GetLanguageServiceID(out langService);
                vsTextLines.SetLanguageServiceID(ref langService);

                containedLanguage = vsContainedLanguage;
                IVsContainedLanguageHost legacyContainedLanguageHost = GetLegacyContainedLanguageHost();

                vsContainedLanguage.SetHost(legacyContainedLanguageHost);
                _legacyCommandTarget = new LegacyContainedLanguageCommandTarget();

                IVsTextViewFilter textViewFilter;

                _legacyCommandTarget.Create(owner.Document, vsContainedLanguage, _textBufferCoordinator, ProjectionBuffer, out textViewFilter);
                IWebContainedLanguageHost webContainedLanguageHost = legacyContainedLanguageHost as IWebContainedLanguageHost;

                webContainedLanguageHost.SetContainedCommandTarget(_legacyCommandTarget.TextView, _legacyCommandTarget.ContainedLanguageTarget);
                containedLanguage2 = (webContainedLanguageHost as IContainedLanguageHostVs);
                containedLanguage2.TextViewFilter = textViewFilter;

                ProjectionBuffer.ResetMappings();

                WebEditor.TraceEvent(1005);
            }
            public int OnLoadCompleted(int fReload)
            {
                _cp.Unadvise(_cookie);

                var         adapterService  = _compModel.GetService <IVsEditorAdaptersFactoryService>();
                ITextBuffer diskBuffer      = adapterService.GetDocumentBuffer(_textLines);
                var         contentRegistry = _compModel.GetService <IContentTypeRegistryService>();
                var         factService     = _compModel.GetService <IProjectionBufferFactoryService>();

                IContentType contentType = SniffContentType(diskBuffer) ??
                                           contentRegistry.GetContentType("HTML");

                var projBuffer = new TemplateProjectionBuffer(contentRegistry, factService, diskBuffer, _compModel.GetService <IBufferGraphFactoryService>(), contentType);

                diskBuffer.ChangedHighPriority += projBuffer.DiskBufferChanged;
                diskBuffer.Properties.AddProperty(typeof(TemplateProjectionBuffer), projBuffer);

                Guid langSvcGuid = typeof(DjangoLanguageInfo).GUID;

                _textLines.SetLanguageServiceID(ref langSvcGuid);

                adapterService.SetDataBuffer(_textLines, projBuffer.ProjectionBuffer);

                IVsTextView view;

                ErrorHandler.ThrowOnFailure(_window.GetPrimaryView(out view));

                if (contentType != null && contentType.IsOfType("HTML"))
                {
                    var editAdapter            = _compModel.GetService <IVsEditorAdaptersFactoryService>();
                    var newView                = editAdapter.GetWpfTextView(view);
                    var intellisenseController = HtmlIntellisenseControllerProvider.GetOrCreateController(_compModel, newView);
                    intellisenseController.AttachKeyboardFilter();
                }

                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);
        }
Example #15
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);
        }
        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       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pguidCmdUI         = Guids.PerspexDesignerGeneralPageGuid;
            pgrfCDW            = 0;
            pbstrEditorCaption = null;

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

            IVsTextLines documentBuffer = null;

            if (punkDocDataExisting == IntPtr.Zero)
            {
                // create an invisible editor
                var invisibleEditorManager = (IVsInvisibleEditorManager)_serviceProvider.GetService(typeof(IVsInvisibleEditorManager));
                IVsInvisibleEditor invisibleEditor;
                ErrorHandler.ThrowOnFailure(invisibleEditorManager.RegisterInvisibleEditor(pszMkDocument,
                                                                                           null,
                                                                                           (uint)_EDITORREGFLAGS.RIEF_ENABLECACHING,
                                                                                           null,
                                                                                           out invisibleEditor));

                var docDataPointer   = IntPtr.Zero;
                var guidIVSTextLines = typeof(IVsTextLines).GUID;
                ErrorHandler.ThrowOnFailure(invisibleEditor.GetDocData(1, ref guidIVSTextLines, out docDataPointer));
                documentBuffer = (IVsTextLines)Marshal.GetObjectForIUnknown(docDataPointer);

                //It is important to site the TextBuffer object
                var objWSite = documentBuffer as IObjectWithSite;
                if (objWSite != null)
                {
                    var oleServiceProvider = (IOleServiceProvider)GetService(typeof(IOleServiceProvider));
                    objWSite.SetSite(oleServiceProvider);
                }
            }
            else
            {
                documentBuffer = Marshal.GetObjectForIUnknown(punkDocDataExisting) as IVsTextLines;
                if (documentBuffer == null)
                {
                    return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                }
            }

            if (documentBuffer == null)
            {
                return(VSConstants.S_FALSE);
            }

            // set xml as the language service id
            ErrorHandler.ThrowOnFailure(documentBuffer.SetLanguageServiceID(ref Guids.XmlLanguageServiceGuid));

            var editorPane = GetDocumentView(documentBuffer, pszMkDocument);

            ppunkDocView       = Marshal.GetIUnknownForObject(editorPane);
            ppunkDocData       = Marshal.GetIUnknownForObject(documentBuffer);
            pbstrEditorCaption = "";
            return(VSConstants.S_OK);
        }
Example #17
0
 public int SetLanguageServiceID(ref Guid guidLangService)
 {
     return(_textBuffer.SetLanguageServiceID(ref guidLangService));
 }
        protected void InitializeLanguageService(IVsTextLines textLines, Guid langSid) {
            IVsUserData userData = textLines as IVsUserData;
            if (userData != null) {
                if (langSid != Guid.Empty) {
                    Guid vsCoreSid = Guids.DefaultLanguageService;
                    Guid currentSid;
                    ErrorHandler.ThrowOnFailure(textLines.GetLanguageServiceID(out currentSid));
                    // If the language service is set to the default SID, then
                    // set it to our language
                    if (currentSid == vsCoreSid) {
                        ErrorHandler.ThrowOnFailure(textLines.SetLanguageServiceID(ref langSid));
                    } else if (currentSid != langSid) {
                        // Some other language service has it, so return VS_E_INCOMPATIBLEDOCDATA
                        throw new COMException("Incompatible doc data", VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                    }

                    Guid bufferDetectLang = VSConstants.VsTextBufferUserDataGuid.VsBufferDetectLangSID_guid;
                    ErrorHandler.ThrowOnFailure(userData.SetData(ref bufferDetectLang, false));
                }
            }
        }
        /// <summary>
        /// Creates a new ConsoleWindow object.
        /// This constructor uses the service provider passed as an argument to create and initialize
        /// the text buffer.
        /// </summary>
        public ConsoleWindow(IServiceProvider provider)
            : base(null)
        {
            if (null == provider)
                throw new ArgumentNullException("provider");
            globalProvider = provider;

            // Create the text buffer.
            textLines = (IVsTextLines)CreateObject(typeof(VsTextBufferClass), typeof(IVsTextLines));
            // Get a reference to the global service provider.
            IOleServiceProvider nativeProvider = (IOleServiceProvider)globalProvider.GetService(typeof(IOleServiceProvider));
            // The text buffer must be sited with the global service provider.
            ((IObjectWithSite)textLines).SetSite(nativeProvider);
            // Set the buffer as read-only. The user should be able to change the content of the
            // buffer only if the engine is started.
            uint flags;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
                textLines.GetStateFlags(out flags));
            flags |= (uint)Microsoft.VisualStudio.TextManager.Interop.BUFFERSTATEFLAGS.BSF_USER_READONLY;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
                textLines.SetStateFlags(flags));

            // Set the GUID of the language service that will handle this text buffer
            Guid languageGuid = typeof(PythonLanguage).GUID;
            Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(
                textLines.SetLanguageServiceID(ref languageGuid));

            // Initialize the history
            history = new HistoryBuffer();

            // Create the stream on top of the text buffer.
            textStream = new TextBufferStream(textLines);

            // Initialize the engine.
            InitializeEngine();

            // Set the title of the window.
            this.Caption = Resources.ToolWindowTitle;

            // Set the icon of the toolwindow.
            this.BitmapResourceID = 301;
            this.BitmapIndex = 0;
        }