/// <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> /// 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); }
/// <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); }
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); }
/// <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>(); }
private void TestSetGet() { int hr; object o; hr = m_iows.GetSite(typeof(IAMGraphBuilderCallback).GUID, out o); Debug.Assert(hr < 0, "Should fail until we assign a value"); foo1 f = new foo1(); hr = m_iows.SetSite(f); DsError.ThrowExceptionForHR(hr); hr = m_iows.GetSite(typeof(IAMGraphBuilderCallback).GUID, out o); DsError.ThrowExceptionForHR(hr); Debug.Assert(o == f); }
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; }
/// <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); }
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); }
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); }
///-------------------------------------------------------------------------------------------- /// <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); }
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); }
/// <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 { ThreadHelper.ThrowIfNotOnUIThread(); 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 = 0; string extension = String.Empty; try { ErrorHandler.ThrowOnFailure(generator.DefaultExtension(out extension)); } catch (Exception e) { if (System.Diagnostics.Debugger.IsAttached) { Debug.WriteLine("generator.DefaultExtension failed: " + e.Message); } } // IVsTextStream stream; string inputFileContents = this.GetBufferContents(moniker, out stream); // // HACK To support T4 Template // //bool utf8 = false; if (String.Compare(Path.GetExtension(fileNode.FileName), ".tt", true) == 0) { // Per default, for a T4 template, convert to UTF8 // utf8 = true; ? to be done ?? // The Output Extension may be modified by the Template. Check it Regex t4ParsingRegex = new Regex("output.*\\sextension\\s*=\\s*\"(?<pvalue>.*?)(?<=[^\\\\](\\\\\\\\)*)\"", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.ExplicitCapture); MatchCollection matchs = t4ParsingRegex.Matches(inputFileContents); if (matchs.Count > 0) { Match match = matchs[0]; Group group = match.Groups["pvalue"]; extension = group.Value; } // Any Encoding in the Template ? t4ParsingRegex = new Regex("output.*\\sencoding\\s*=\\s*\"(?<pvalue>.*?)(?<=[^\\\\](\\\\\\\\)*)\"", RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline | RegexOptions.ExplicitCapture); matchs = t4ParsingRegex.Matches(inputFileContents); if (matchs.Count > 0) { Match match = matchs[0]; Group group = match.Groups["pvalue"]; //utf8 = false; } } //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); } } try { ErrorHandler.ThrowOnFailure(generator.Generate(moniker, inputFileContents, customToolNamespace, output, out outPutSize, this)); } catch (Exception e) { if (System.Diagnostics.Debugger.IsAttached) { Debug.WriteLine("generator.Generate failed: " + e.Message); } } if (outPutSize > 0) { byte[] data = new byte[outPutSize]; if (output[0] != IntPtr.Zero) { Marshal.Copy(output[0], data, 0, (int)outPutSize); Marshal.FreeCoTaskMem(output[0]); } // HACK T4 Support /* * utf8 = false; * if (utf8) * { * System.Text.StringBuilder sb = new System.Text.StringBuilder(); * sb.Append(System.Text.Encoding.ASCII.GetString(data, 0, (int)outPutSize)); * // * System.Text.Encoding enc = new System.Text.UTF8Encoding(true); * byte[] preamble = enc.GetPreamble(); * byte[] encData = enc.GetBytes(sb.ToString()); * // * outPutSize = (uint)encData.Length + (uint)preamble.Length; * data = new byte[outPutSize]; * Array.Copy(preamble, data, preamble.Length); * Array.Copy(encData, 0, data, preamble.Length, encData.Length); * } */ //Todo - Create a file and add it to the Project string fileToAdd = this.UpdateGeneratedCodeFile(fileNode, data, (int)outPutSize, dependentNodeName); } } } finally { this.runningGenerator = false; } }
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; pguidCmdUI = new Guid("D0481CA6-C9E2-4852-A60D-A7C0AE6AFB99"); 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) { Guid iid = typeof(IVsTextLines).GUID; Guid CLSID_VsTextBuffer = typeof(VsTextBufferClass).GUID; localRegistry.CreateInstance(CLSID_VsTextBuffer, null, ref iid, 1 /*CLSCTX_INPROC_SERVER*/, out IntPtr 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) { IOleServiceProvider oleServiceProvider = (IOleServiceProvider)GetService(typeof(IOleServiceProvider)); 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 || IsInit == false) { return(VSConstants.VS_E_INCOMPATIBLEDOCDATA); } } string filename = System.IO.Path.GetFileName(pszMkDocument); if (string.IsNullOrEmpty(filename) == false) { if (filename.Equals(FileName) && ExcuteToCheckXmlRule(pszMkDocument)) { ManifestEditorPane NewEditor = new ManifestEditorPane(editorPackage, pszMkDocument, textBuffer); IsInit = true; ppunkDocView = Marshal.GetIUnknownForObject(NewEditor); ppunkDocData = Marshal.GetIUnknownForObject(textBuffer); pbstrEditorCaption = ""; return(VSConstants.S_OK); } else { Guid clsidCodeWindow = typeof(VsCodeWindowClass).GUID; Guid iidCodeWindow = typeof(IVsCodeWindow).GUID; IVsCodeWindow pCodeWindow = (IVsCodeWindow)editorPackage.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)textBuffer); // Now tell the caller about all this new stuff // that has been created. ppunkDocView = Marshal.GetIUnknownForObject(pCodeWindow); ppunkDocData = Marshal.GetIUnknownForObject(textBuffer); // 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 = " [MyPackage]"; return(VSConstants.S_OK); } } } return(VSConstants.S_FALSE); }
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); }
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); }
/// <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); }
IVsTextLines GetTextBuffer(System.IntPtr punkDocDataExisting) { 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(null); } } return(textBuffer); }
/// <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, 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); }
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--; } }
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; } }
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); }
/// <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); }
/// <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; } }
private void CreateVsCodeWindow() { int hr = VSConstants.S_OK; Guid clsidVsCodeWindow = typeof(VsCodeWindowClass).GUID; Guid iidVsCodeWindow = typeof(IVsCodeWindow).GUID; Guid clsidVsTextBuffer = typeof(VsTextBufferClass).GUID; Guid iidVsTextLines = typeof(IVsTextLines).GUID; // create/site a VsTextBuffer object _vsTextBuffer = (IVsTextBuffer)NuoDbVSPackagePackage.Instance.CreateInstance(ref clsidVsTextBuffer, ref iidVsTextLines, typeof(IVsTextBuffer)); IObjectWithSite ows = (IObjectWithSite)_vsTextBuffer; ows.SetSite(_editor); //string strSQL = "select * from sometable"; //hr = _vsTextBuffer.InitializeContent(strSQL, strSQL.Length); switch (NuoDbVSPackagePackage.Instance.GetMajorVStudioVersion()) { case 10: hr = _vsTextBuffer.SetLanguageServiceID(ref GuidList.guidSQLLangSvc_VS2010); break; case 11: hr = _vsTextBuffer.SetLanguageServiceID(ref GuidList.guidSQLLangSvc_VS2012); break; } // create/initialize/site a VsCodeWindow object _vsCodeWindow = (IVsCodeWindow)NuoDbVSPackagePackage.Instance.CreateInstance(ref clsidVsCodeWindow, ref iidVsCodeWindow, typeof(IVsCodeWindow)); INITVIEW[] initView = new INITVIEW[1]; initView[0].fSelectionMargin = 0; initView[0].fWidgetMargin = 0; initView[0].fVirtualSpace = 0; initView[0].fDragDropMove = 1; initView[0].fVirtualSpace = 0; IVsCodeWindowEx vsCodeWindowEx = (IVsCodeWindowEx)_vsCodeWindow; hr = vsCodeWindowEx.Initialize((uint)_codewindowbehaviorflags.CWB_DISABLEDROPDOWNBAR | (uint)_codewindowbehaviorflags.CWB_DISABLESPLITTER, 0, null, null, (uint)TextViewInitFlags.VIF_SET_WIDGET_MARGIN | (uint)TextViewInitFlags.VIF_SET_SELECTION_MARGIN | (uint)TextViewInitFlags.VIF_SET_VIRTUAL_SPACE | (uint)TextViewInitFlags.VIF_SET_DRAGDROPMOVE | (uint)TextViewInitFlags2.VIF_SUPPRESS_STATUS_BAR_UPDATE | (uint)TextViewInitFlags2.VIF_SUPPRESSBORDER | (uint)TextViewInitFlags2.VIF_SUPPRESSTRACKCHANGES | (uint)TextViewInitFlags2.VIF_SUPPRESSTRACKGOBACK, initView); hr = _vsCodeWindow.SetBuffer((IVsTextLines)_vsTextBuffer); IVsWindowPane vsWindowPane = (IVsWindowPane)_vsCodeWindow; hr = vsWindowPane.SetSite(_editor); hr = vsWindowPane.CreatePaneWindow(this.Handle, 0, 0, this.Parent.Size.Width, this.Parent.Size.Height, out _hWndCodeWindow); IVsTextView vsTextView; hr = _vsCodeWindow.GetPrimaryView(out vsTextView); // sink IVsTextViewEvents, so we can determine when a VsCodeWindow object actually has the focus. IConnectionPointContainer connptCntr = (IConnectionPointContainer)vsTextView; Guid riid = typeof(IVsTextViewEvents).GUID; IConnectionPoint cp; connptCntr.FindConnectionPoint(ref riid, out cp); cp.Advise(_editor, out cookie); // sink IVsTextLinesEvents, so we can determine when a VsCodeWindow text has been changed. connptCntr = (IConnectionPointContainer)_vsTextBuffer; riid = typeof(IVsTextLinesEvents).GUID; connptCntr.FindConnectionPoint(ref riid, out cp); cp.Advise(_editor, out cookie); }