/// <summary>
 /// Initializes a new instance of the <see cref="ComObject"/> class from a IUnknown object.
 /// </summary>
 /// <param name="iunknowObject">Reference to a IUnknown object</param>
 public ComObject(object iunknownObject)
 {
     NativePointer = Marshal.GetIUnknownForObject(iunknownObject);
 }
        public static SoundInfo[] GetCurrentSoundInfo()
        {
            SoundInfo[] soundSourceInfos = new SoundInfo[0];

            try
            { // TODO: properly handle when headphones are used, etc.
                MMDeviceEnumerator DevEnum = new MMDeviceEnumerator();
                MMDevice           device  = DevEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);

                List <SoundInfo> soundSourceInfoList = new List <SoundInfo>();
                SoundInfo        soundInfo           = null;

                // Note the AudioSession manager did not have a method to enumerate all sessions in windows Vista; this will only work on Win7 and newer.
                for (int i = 0; i < device.AudioSessionManager.Sessions.Count; i++)
                {
                    AudioSessionControl session = device.AudioSessionManager.Sessions[i];

                    soundInfo = new SoundInfo();

//                    if (session.State == AudioSessionState.AudioSessionStateActive)
                    {
                        soundInfo.Pid = (int)session.ProcessID;

                        soundInfo.IconPath                  = session.IconPath;
                        soundInfo.DisplayName               = session.DisplayName;
                        soundInfo.SessionIdentifier         = session.SessionIdentifier;
                        soundInfo.SessionInstanceIdentifier = session.SessionInstanceIdentifier;
                        soundInfo.IsSystemSoundsSession     = session.IsSystemSoundsSession;
                        //soundSourceInfo.State = session.State;

                        try
                        {
                            int pid = (int)session.ProcessID;
                            if (pid != 0)
                            {
                                string procName;
                                if (false == ProcNameDict.TryGetValue(pid, out procName))
                                {
                                    try
                                    {
                                        Process p = Process.GetProcessById(pid); //TO_DO: should remove processname and windowtitle from this class (but make sure that windowtitle gets updated at appropriate interval)
                                        ProcNameDict[pid]        = p.ProcessName;
                                        ProcWindowTitleDict[pid] = p.MainWindowTitle;
                                        try
                                        {
                                            if (p.Modules.Count > 0)
                                            {
                                                ProcFullPathDict[pid] = p.Modules[0].FileName;
                                            }
                                            else
                                            {
                                                ProcFullPathDict[pid] = "";
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            // WMI code from stackoverflow
                                            string query = "SELECT ExecutablePath, ProcessID FROM Win32_Process";
                                            System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(query);

                                            foreach (ManagementObject item in searcher.Get())
                                            {
                                                object id   = item["ProcessID"];
                                                object path = item["ExecutablePath"];

                                                if (path != null && id.ToString() == p.Id.ToString())
                                                {
                                                    ProcFullPathDict[pid] = path.ToString();
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        System.Diagnostics.Debug.WriteLine(ex);
                                        ProcNameDict[pid]        = "";
                                        ProcWindowTitleDict[pid] = "";
                                        ProcFullPathDict[pid]    = "";
                                    }
                                }
                                soundInfo.ProcessName = ProcNameDict[pid];

                                soundInfo.WindowTitle = ProcWindowTitleDict[pid];
                                if (soundInfo.WindowTitle == "")
                                {
                                    try
                                    {
                                        Process proc = Process.GetProcessById(pid);
                                        soundInfo.WindowTitle = proc.MainWindowTitle;
                                        if (soundInfo.WindowTitle == "")
                                        {
                                            soundInfo.WindowTitle = proc.ProcessName;
                                        }
                                    }
                                    catch { }
                                }
                                soundInfo.ProcessFullPath = ProcFullPathDict[pid];
                                if ((soundInfo.ProcessFullPath == "") && (soundInfo.IsSystemSoundsSession == false))
                                {
                                    int x = 0;
                                    x++;
                                }
                            }
                            else
                            {
                                soundInfo.ProcessName     = "";
                                soundInfo.WindowTitle     = "System Sounds";
                                soundInfo.ProcessFullPath = "";
                            }
                        }
                        catch (Exception ex)
                        {
                            string msg = ex.Message;
                        }

                        AudioMeterInformation mi  = session.AudioMeterInformation;
                        SimpleAudioVolume     vol = session.SimpleAudioVolume;

                        soundInfo.Muted       = vol.Mute;
                        soundInfo.MixerVolume = session.SimpleAudioVolume.MasterVolume;
                        //session.SimpleAudioVolume.MasterVolume = soundSourceInfo.ChannelVolume;
                        soundInfo.EmittedVolume = session.AudioMeterInformation.MasterPeakValue;
                        soundSourceInfoList.Add(soundInfo);
                    }
                }

                // Free up the memory
                IntPtr pointer = Marshal.GetIUnknownForObject(device);
                Marshal.Release(pointer);

                soundSourceInfos = soundSourceInfoList.ToArray();

                Array.Sort(soundSourceInfos, delegate(SoundInfo info1, SoundInfo info2)
                {
                    return(info1.CompareTo(info2));
                });
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex);
            }

            return(soundSourceInfos);
        }
 public void GetIUnknownForObject_NullObject_ThrowsArgumentNullException()
 {
     AssertExtensions.Throws <ArgumentNullException>("o", () => Marshal.GetIUnknownForObject(null));
 }
 /// <summary>Provides the document view to the document window.</summary>
 /// <param name="ppUnkDocView">[out] Pointer to the <see langword="IUnknown" /> interface of the document view. Used as an argument to <see cref="M:Microsoft.VisualStudio.Shell.Interop.IVsUIShell.CreateDocumentWindow(System.UInt32,System.String,Microsoft.VisualStudio.Shell.Interop.IVsUIHierarchy,System.UInt32,System.IntPtr,System.IntPtr,System.Guid@,System.String,System.Guid@,Microsoft.VisualStudio.OLE.Interop.IServiceProvider,System.String,System.String,System.Int32[],Microsoft.VisualStudio.Shell.Interop.IVsWindowFrame@)" />.</param>
 /// <returns>If the method succeeds, it returns <see cref="F:Microsoft.VisualStudio.VSConstants.S_OK" />. If it fails, it returns an error code.</returns>
 int IVsDeferredDocView.get_DocView(out IntPtr ppUnkDocView)
 {
     ppUnkDocView = Marshal.GetIUnknownForObject(this);
     return(VSConstants.S_OK);
 }
Exemple #5
0
        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)
        {
            Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering {0} CreateEditorInstace()", this.ToString()));

            // Initialize to null
            ppunkDocView       = IntPtr.Zero;
            ppunkDocData       = IntPtr.Zero;
            pguidCmdUI         = Constants.EtoPreviewEditorFactory_guid;
            pgrfCDW            = 0;
            pbstrEditorCaption = null;


            if (!BuilderInfo.Supports(pszMkDocument))
            {
                return(VSConstants.VS_E_UNSUPPORTEDFORMAT);
            }

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

            object prjItemObject;
            var    projectItemId = VSConstants.VSITEMID_ROOT;

            pvHier.GetProperty(projectItemId, (int)__VSHPROPID.VSHPROPID_ExtObject, out prjItemObject);
            var proj = prjItemObject as EnvDTE.Project;

            // Get or open text buffer
            var textBuffer = GetTextBuffer(punkDocDataExisting, pszMkDocument, ToVsProject(proj));

            if (textBuffer == null)
            {
                return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
            }

            if (punkDocDataExisting != IntPtr.Zero)
            {
                ppunkDocData = punkDocDataExisting;
                Marshal.AddRef(ppunkDocData);
            }
            else
            {
                ppunkDocData = Marshal.GetIUnknownForObject(textBuffer);
            }


            var outputFile = GetAssemblyPath(proj);
            var references = GetReferences(proj).ToList();
            //var outputDir = Path.GetDirectoryName(outputFile);

            // Create the Document (editor)
            var editor = new EtoPreviewPane(editorPackage, pszMkDocument, textBuffer, outputFile, references);

            ppunkDocView = Marshal.GetIUnknownForObject(editor);
            //pbstrEditorCaption = " [Preview]";
            return(VSConstants.S_OK);
        }
        public static bool IsAssignableFrom(this Type type, ref object value)
        {
            if (type.IsByRef)
            {
                type = type.GetElementType();
            }

            if (type.IsNullable())
            {
                // ReSharper disable once AssignNullToNotNullAttribute
                return((value == null) || (Nullable.GetUnderlyingType(type).IsAssignableFrom(ref value)));
            }

            if (value == null)
            {
                // ReSharper disable once PossibleNullReferenceException
                return(!type.IsValueType);
            }

            var valueType = value.GetType();

            if (valueType == type)
            {
                return(true);
            }

            // ReSharper disable once PossibleNullReferenceException
            if (!type.IsValueType)
            {
                if (type.IsAssignableFrom(valueType))
                {
                    return(true);
                }

                if (type.IsInterface && type.IsImport && valueType.IsCOMObject)
                {
                    var result   = false;
                    var pUnknown = Marshal.GetIUnknownForObject(value);

                    var iid = type.GUID;
                    if (iid != Guid.Empty)
                    {
                        IntPtr pInterface;
                        if (RawCOMHelpers.HResult.Succeeded(Marshal.QueryInterface(pUnknown, ref iid, out pInterface)))
                        {
                            Marshal.Release(pInterface);
                            result = true;
                        }
                    }

                    Marshal.Release(pUnknown);
                    return(result);
                }

                return(false);
            }

            if (!valueType.IsValueType)
            {
                return(false);
            }

            if (type.IsEnum)
            {
                return(Enum.GetUnderlyingType(type).IsAssignableFrom(ref value) && (value.DynamicCast <int>() == 0));
            }

            if (valueType.IsEnum)
            {
                return(false);
            }

            bool typeIsIntegral;

            if (type.IsNumeric(out typeIsIntegral))
            {
                if (typeIsIntegral)
                {
                    if (!valueType.IsIntegral())
                    {
                        return(false);
                    }
                }
                else if (!valueType.IsNumeric())
                {
                    return(false);
                }

                value = Convert.ChangeType(value, type);
                return(true);
            }

            return(false);
        }
Exemple #7
0
 internal void SetIUnknown(object value)
 {
     _valueType = (ushort)VarEnum.VT_UNKNOWN;
     _ptr       = Marshal.GetIUnknownForObject(value);
 }
        /// <summary>
        /// Uses the IMAPIPROP.SetProps to set the content ID
        /// </summary>
        /// <param name="attachment"></param>
        /// <param name="contentId"></param>
        public static void SetContentID(IAttachment attachment, string contentId)
        {
            // Pointer to IUnknown Interface
            IntPtr IUnknown = IntPtr.Zero;
            // Pointer to IMAPIProp Interface
            IntPtr IMAPIProp = IntPtr.Zero;
            // A pointer that points to the SPropValue structure
            IntPtr ptrPropValue = IntPtr.Zero;
            // Structure that will hold the Property Value
            SPropValue propValue;

            // if we have no MAPIObject everything is senseless...
            if (attachment == null)
            {
                return;
            }

            try {
                // We can pass NULL here as parameter, so we do it.
                MAPIInitialize(IntPtr.Zero);

                // retrive the IUnknon Interface from our MAPIObject comming from Outlook.
                IUnknown = Marshal.GetIUnknownForObject(attachment.MAPIOBJECT);
                IMAPIProp mapiProp = (IMAPIProp)Marshal.GetTypedObjectForIUnknown(IUnknown, typeof(IMAPIProp));

                // Create structure
                propValue         = new SPropValue();
                propValue.propTag = (uint)PropTags.PR_ATTACH_CONTENT_ID;
                //propValue.propTag = 0x3712001E;
                // Create Ansi string
                propValue.Value = Marshal.StringToHGlobalUni(contentId);

                // Create unmanaged memory for structure
                ptrPropValue = Marshal.AllocHGlobal(Marshal.SizeOf(propValue));
                // Copy structure to unmanged memory
                Marshal.StructureToPtr(propValue, ptrPropValue, false);
                mapiProp.SetProps(1, ptrPropValue, IntPtr.Zero);

                propValue.propTag = (uint)PropTags.PR_ATTACH_CONTENT_LOCATION;
                // Copy structure to unmanged memory
                Marshal.StructureToPtr(propValue, ptrPropValue, false);
                mapiProp.SetProps(1, ptrPropValue, IntPtr.Zero);


                // Free string
                Marshal.FreeHGlobal(propValue.Value);
                mapiProp.SaveChanges(KEEP_OPEN_READWRITE);
            } catch (Exception ex) {
                LOG.Error(ex);
            } finally {
                // Free used Memory structures
                if (ptrPropValue != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(ptrPropValue);
                }
                // cleanup all references to COM Objects
                if (IMAPIProp != IntPtr.Zero)
                {
                    Marshal.Release(IMAPIProp);
                }
                //if (IMessage != IntPtr.Zero) Marshal.Release(IMessage);
                if (IUnknown != IntPtr.Zero)
                {
                    Marshal.Release(IUnknown);
                }
            }
        }
        /// <summary>
        /// Use MAPI32.DLL "HrSetOneProp" from managed code
        /// </summary>
        /// <param name="attachment"></param>
        /// <param name="proptag"></param>
        /// <param name="propertyValue"></param>
        /// <returns></returns>
        public static bool SetMAPIProperty(IAttachment attachment, PropTags proptag, string propertyValue)
        {
            // Pointer to IUnknown Interface
            IntPtr IUnknown = IntPtr.Zero;
            // Pointer to IMAPIProp Interface
            IntPtr IMAPIProp = IntPtr.Zero;
            // Structure that will hold the Property Value
            SPropValue propValue;
            // A pointer that points to the SPropValue structure
            IntPtr ptrPropValue = IntPtr.Zero;
            object mapiObject   = attachment.MAPIOBJECT;

            // if we have no MAPIObject everything is senseless...
            if (mapiObject == null)
            {
                return(false);
            }

            try {
                // We can pass NULL here as parameter, so we do it.
                MAPIInitialize(IntPtr.Zero);

                // retrive the IUnknon Interface from our MAPIObject comming from Outlook.
                IUnknown = Marshal.GetIUnknownForObject(mapiObject);

                // create a Guid that we pass to retreive the IMAPIProp Interface.
                Guid guidIMAPIProp = new Guid(IID_IMAPIProp);

                // try to retrieve the IMAPIProp interface from IMessage Interface, everything else is sensless.
                if (Marshal.QueryInterface(IUnknown, ref guidIMAPIProp, out IMAPIProp) != 0)
                {
                    return(false);
                }

                // double check, if we wave no pointer, exit...
                if (IMAPIProp == IntPtr.Zero)
                {
                    return(false);
                }

                // Create structure
                propValue         = new SPropValue();
                propValue.propTag = (uint)proptag;
                // Create Ansi string
                propValue.Value = Marshal.StringToHGlobalUni(propertyValue);

                // Create unmanaged memory for structure
                ptrPropValue = Marshal.AllocHGlobal(Marshal.SizeOf(propValue));
                // Copy structure to unmanged memory
                Marshal.StructureToPtr(propValue, ptrPropValue, false);

                // Set the property
                HrSetOneProp(IMAPIProp, ptrPropValue);

                // Free string
                Marshal.FreeHGlobal(propValue.Value);
                IMAPIProp mapiProp = (IMAPIProp)Marshal.GetTypedObjectForIUnknown(IUnknown, typeof(IMAPIProp));
                return(mapiProp.SaveChanges(4) == 0);
            } catch (System.Exception ex) {
                LOG.Error(ex);
                return(false);
            } finally {
                // Free used Memory structures
                if (ptrPropValue != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(ptrPropValue);
                }
                // cleanup all references to COM Objects
                if (IMAPIProp != IntPtr.Zero)
                {
                    Marshal.Release(IMAPIProp);
                }
                //if (IMessage != IntPtr.Zero) Marshal.Release(IMessage);
                if (IUnknown != IntPtr.Zero)
                {
                    Marshal.Release(IUnknown);
                }
                MAPIUninitialize();
            }
        }
        /// <summary>
        ///    <para>Waits for the next event that matches the specified query to arrive, and
        ///       then returns it.</para>
        /// </summary>
        /// <returns>
        /// <para>A <see cref='System.Management.ManagementBaseObject'/> representing the
        ///    newly arrived event.</para>
        /// </returns>
        /// <remarks>
        ///    <para>If the event watcher object contains options with
        ///       a specified timeout, the API will wait for the next event only for the specified
        ///       amount of time; otherwise, the API will be blocked until the next event occurs.</para>
        /// </remarks>
        public ManagementBaseObject WaitForNextEvent()
        {
            ManagementBaseObject obj = null;

            Initialize();

            lock (this)
            {
                SecurityHandler securityHandler = Scope.GetSecurityHandler();

                int status = (int)ManagementStatus.NoError;

                try
                {
                    if (null == enumWbem)   //don't have an enumerator yet - get it
                    {
                        //Execute the query
                        status = scope.GetSecuredIWbemServicesHandler(Scope.GetIWbemServices()).ExecNotificationQuery_(
                            query.QueryLanguage,
                            query.QueryString,
                            options.Flags,
                            options.GetContext(),
                            ref enumWbem);
                    }

                    if (status >= 0)
                    {
                        if ((cachedCount - cacheIndex) == 0) //cache is empty - need to get more objects
                        {
                            //Because Interop doesn't support custom marshalling for arrays, we have to use
                            //the "DoNotMarshal" objects in the interop and then convert to the "FreeThreaded"
                            //counterparts afterwards.
                            IWbemClassObject_DoNotMarshal[] tempArray = new IWbemClassObject_DoNotMarshal[options.BlockSize];

                            int timeout = (ManagementOptions.InfiniteTimeout == options.Timeout)
                                ? (int)tag_WBEM_TIMEOUT_TYPE.WBEM_INFINITE :
                                          (int)options.Timeout.TotalMilliseconds;

                            status     = scope.GetSecuredIEnumWbemClassObjectHandler(enumWbem).Next_(timeout, (uint)options.BlockSize, tempArray, ref cachedCount);
                            cacheIndex = 0;

                            if (status >= 0)
                            {
                                //Convert results and put them in cache. Note that we may have timed out
                                //in which case we might not have all the objects. If no object can be returned
                                //we throw a timeout exception.
                                if (cachedCount == 0)
                                {
                                    ManagementException.ThrowWithExtendedInfo(ManagementStatus.Timedout);
                                }

                                for (int i = 0; i < cachedCount; i++)
                                {
                                    cachedObjects[i] = new IWbemClassObjectFreeThreaded(Marshal.GetIUnknownForObject(tempArray[i]));
                                }
                            }
                        }

                        if (status >= 0)
                        {
                            obj = new ManagementBaseObject(cachedObjects[cacheIndex]);
                            cacheIndex++;
                        }
                    }
                }
                finally
                {
                    securityHandler.Reset();
                }

                if (status < 0)
                {
                    if ((status & 0xfffff000) == 0x80041000)
                    {
                        ManagementException.ThrowWithExtendedInfo((ManagementStatus)status);
                    }
                    else
                    {
                        Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f());
                    }
                }
            }

            return(obj);
        }
Exemple #11
0
        private static void ValidateMarshalAPIs(bool validateUseRegistered)
        {
            string scenario = validateUseRegistered ? "use registered wrapper" : "fall back to runtime";

            Console.WriteLine($"Running {nameof(ValidateMarshalAPIs)}: {scenario}...");

            GlobalComWrappers registeredWrapper = GlobalComWrappers.Instance;

            registeredWrapper.ReturnInvalid = !validateUseRegistered;

            Console.WriteLine($" -- Validate Marshal.GetIUnknownForObject...");

            var    testObj     = new Test();
            IntPtr comWrapper1 = Marshal.GetIUnknownForObject(testObj);

            Assert.AreNotEqual(IntPtr.Zero, comWrapper1);
            Assert.AreEqual(testObj, registeredWrapper.LastComputeVtablesObject, "Registered ComWrappers instance should have been called");

            IntPtr comWrapper2 = Marshal.GetIUnknownForObject(testObj);

            Assert.AreEqual(comWrapper1, comWrapper2);

            Marshal.Release(comWrapper1);
            Marshal.Release(comWrapper2);

            Console.WriteLine($" -- Validate Marshal.GetIDispatchForObject...");

            Assert.Throws <InvalidCastException>(() => Marshal.GetIDispatchForObject(testObj));

            if (validateUseRegistered)
            {
                var    dispatchObj     = new TestEx(IID_IDISPATCH);
                IntPtr dispatchWrapper = Marshal.GetIDispatchForObject(dispatchObj);
                Assert.AreNotEqual(IntPtr.Zero, dispatchWrapper);
                Assert.AreEqual(dispatchObj, registeredWrapper.LastComputeVtablesObject, "Registered ComWrappers instance should have been called");

                Console.WriteLine($" -- Validate Marshal.GetIDispatchForObject != Marshal.GetIUnknownForObject...");
                IntPtr unknownWrapper = Marshal.GetIUnknownForObject(dispatchObj);
                Assert.AreNotEqual(IntPtr.Zero, unknownWrapper);
                Assert.AreNotEqual(unknownWrapper, dispatchWrapper);
            }

            Console.WriteLine($" -- Validate Marshal.GetObjectForIUnknown...");

            IntPtr trackerObjRaw = MockReferenceTrackerRuntime.CreateTrackerObject();
            object objWrapper1   = Marshal.GetObjectForIUnknown(trackerObjRaw);

            Assert.AreEqual(validateUseRegistered, objWrapper1 is FakeWrapper, $"GetObjectForIUnknown should{(validateUseRegistered ? string.Empty : "not")} have returned {nameof(FakeWrapper)} instance");
            object objWrapper2 = Marshal.GetObjectForIUnknown(trackerObjRaw);

            Assert.AreEqual(objWrapper1, objWrapper2);

            Console.WriteLine($" -- Validate Marshal.GetUniqueObjectForIUnknown...");

            object objWrapper3 = Marshal.GetUniqueObjectForIUnknown(trackerObjRaw);

            Assert.AreEqual(validateUseRegistered, objWrapper3 is FakeWrapper, $"GetObjectForIUnknown should{(validateUseRegistered ? string.Empty : "not")} have returned {nameof(FakeWrapper)} instance");

            Assert.AreNotEqual(objWrapper1, objWrapper3);

            Marshal.Release(trackerObjRaw);
        }
Exemple #12
0
        private static bool DeepEquals(IAccessible ia1, IAccessible ia2)
        {
            if (ia1.Equals(ia2))
            {
                return(true);
            }
            if (Marshal.GetIUnknownForObject(ia1) == Marshal.GetIUnknownForObject(ia2))
            {
                return(true);
            }
            try
            {
                if (ia1.accChildCount != ia2.accChildCount)
                {
                    return(false);
                }
                SystemAccessibleObject sa1 = new SystemAccessibleObject(ia1, 0);
                SystemAccessibleObject sa2 = new SystemAccessibleObject(ia2, 0);
                if (sa1.Window.HWnd != sa2.Window.HWnd)
                {
                    return(false);
                }
                if (sa1.Location != sa2.Location)
                {
                    return(false);
                }
                if (sa1.DefaultAction != sa2.DefaultAction)
                {
                    return(false);
                }
                if (sa1.Description != sa2.Description)
                {
                    return(false);
                }
                if (sa1.KeyboardShortcut != sa2.KeyboardShortcut)
                {
                    return(false);
                }
                if (sa1.Name != sa2.Name)
                {
                    return(false);
                }
                if (!sa1.Role.Equals(sa2.Role))
                {
                    return(false);
                }
                if (sa1.State != sa2.State)
                {
                    return(false);
                }
                if (sa1.Value != sa2.Value)
                {
                    return(false);
                }
                if (sa1.Visible != sa2.Visible)
                {
                    return(false);
                }
                if (ia1.accParent == null && ia2.accParent == null)
                {
                    return(true);
                }
                if (ia1.accParent == null || ia2.accParent == null)
                {
                    return(false);
                }
            }
            catch (COMException)
            {
                return(false);
            }
            bool de = DeepEquals((IAccessible)ia1.accParent, (IAccessible)ia2.accParent);

            return(de);
        }
Exemple #13
0
        private async Task <IVsWindowFrame> CreateDocWindowForSolutionAsync()
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            IVsWindowFrame windowFrame = null;
            var            solution    = await this.GetServiceAsync <IVsSolution>();

            var uiShell = await this.GetServiceAsync <SVsUIShell, IVsUIShell>();

            var windowFlags =
                (uint)_VSRDTFLAGS.RDT_DontAddToMRU |
                (uint)_VSRDTFLAGS.RDT_DontSaveAs;

            // when VSSolutionManager is already initialized, then use the existing APIs to check pre-conditions.
            if (!await SolutionManager.Value.IsSolutionAvailableAsync())
            {
                throw new InvalidOperationException(Resources.SolutionIsNotSaved);
            }

            var projects = (await SolutionManager.Value.GetNuGetProjectsAsync()).ToArray();

            if (projects.Length == 0)
            {
                MessageHelper.ShowWarningMessage(Resources.NoSupportedProjectsInSolution, Resources.ErrorDialogBoxTitle);
                return(null);
            }

            // pass empty array of NuGetProject
            var uiController = UIFactory.Value.Create(projects);

            var solutionName = (string)_dte.Solution.Properties.Item("Name").Value;

            var model = new PackageManagerModel(
                uiController,
                isSolution: true,
                editorFactoryGuid: GuidList.guidNuGetEditorType)
            {
                SolutionName = solutionName
            };

            var vsWindowSearchHostfactory = await GetServiceAsync(typeof(SVsWindowSearchHostFactory)) as IVsWindowSearchHostFactory;

            var vsShell = await GetServiceAsync(typeof(SVsShell)) as IVsShell4;

            var control        = new PackageManagerControl(model, Settings.Value, vsWindowSearchHostfactory, vsShell, OutputConsoleLogger.Value);
            var windowPane     = new PackageManagerWindowPane(control);
            var guidEditorType = GuidList.guidNuGetEditorType;
            var guidCommandUI  = Guid.Empty;
            var caption        = Resx.Label_SolutionNuGetWindowCaption;
            var documentName   = _dte.Solution.FullName;

            var ppunkDocView = IntPtr.Zero;
            var ppunkDocData = IntPtr.Zero;
            var hr           = 0;

            try
            {
                ppunkDocView = Marshal.GetIUnknownForObject(windowPane);
                ppunkDocData = Marshal.GetIUnknownForObject(model);
                hr           = uiShell.CreateDocumentWindow(
                    windowFlags,
                    documentName,
                    (IVsUIHierarchy)solution,
                    (uint)VSConstants.VSITEMID.Root,
                    ppunkDocView,
                    ppunkDocData,
                    ref guidEditorType,
                    null,
                    ref guidCommandUI,
                    null,
                    caption,
                    string.Empty,
                    null,
                    out windowFrame);

                if (windowFrame != null)
                {
                    WindowFrameHelper.AddF1HelpKeyword(windowFrame, keywordValue: F1KeywordValuePmUI);
                }
            }
            finally
            {
                if (ppunkDocView != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocData);
                }

                if (ppunkDocData != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocView);
                }
            }

            ErrorHandler.ThrowOnFailure(hr);
            return(windowFrame);
        }
        public PropertyPagePanel(bool OkCloseButtons, IBaseFilter filter)
        {
            _filter = filter;

            base.BackColor = SystemColors.Control;

            _tabs           = new TabControl();
            _tabs.Dock      = DockStyle.Fill;
            this.Dock       = DockStyle.Fill;
            _tabs.Multiline = false;
            Controls.Add(_tabs);

            _buttonsPanel      = new Panel();
            _buttonsPanel.Dock = DockStyle.Bottom;

            _interfacesButton           = new Button();
            _interfacesButton.Text      = "Scan Interfaces";
            _interfacesButton.Width     = 100;
            _interfacesButton.Dock      = DockStyle.Left;
            _interfacesButton.BackColor = SystemColors.Control;
            _interfacesButton.Click    += new EventHandler(_interfacesButton_Click);
            _buttonsPanel.Controls.Add(_interfacesButton);

            _applyButton           = new Button();
            _applyButton.Text      = "Apply";
            _applyButton.Dock      = DockStyle.Left;
            _applyButton.BackColor = SystemColors.Control;
            _applyButton.Enabled   = false;
            _applyButton.Click    += new EventHandler(_applyButton_Click);
            _buttonsPanel.Controls.Add(_applyButton);

            if (OkCloseButtons)
            {
                _closeButton           = new Button();
                _closeButton.Text      = "Close";
                _closeButton.Dock      = DockStyle.Left;
                _closeButton.BackColor = SystemColors.Control;
                _buttonsPanel.Controls.Add(_closeButton);

                _okButton           = new Button();
                _okButton.Text      = "Ok";
                _okButton.Dock      = DockStyle.Left;
                _okButton.BackColor = SystemColors.Control;
                _okButton.Click    += new EventHandler(_applyButton_Click);
                _buttonsPanel.Controls.Add(_okButton);
            }

            _buttonsPanel.Height = 23;
            Controls.Add(_buttonsPanel);
            int hr = 0;

            ISpecifyPropertyPages pProp = filter as ISpecifyPropertyPages;

            if (pProp != null)
            {
                // Get the propertypages from the property bag
                DsCAUUID caGUID;
                hr = pProp.GetPages(out caGUID);
                if (hr != 0 || caGUID.cElems == 0)
                {
                    // could not get property sheets or got 0 property sheets
                    return;
                }

                // convert caGUID to a managed array of Guids
                Guid[] propertyPages = caGUID.ToGuidArray();

                for (int i = 0; i < propertyPages.Length; i++)
                {
                    try
                    {
                        Type   type = Type.GetTypeFromCLSID(propertyPages[i]);
                        object o    = Activator.CreateInstance(type);

                        IPropertyPage pp = o as IPropertyPage;
                        PROPPAGEINFO  pi = new PROPPAGEINFO();
                        pp.GetPageInfo(ref pi);

                        // get the page size, adjusting for button panel and padding
                        _pageSize.Width  = Math.Max(_pageSize.Width, pi.size.Width + 10);
                        _pageSize.Height = Math.Max(_pageSize.Height, pi.size.Height + 33);

                        // we want to inc the refcount so the property page won't vanish on us
                        _iunk.Add(Marshal.GetIUnknownForObject(o));

                        object[] obs = { filter };
                        pp.SetObjects(1, obs);
                        pp.SetPageSite(this);
                        Rectangle rect = new Rectangle(0, 0, pi.size.Width, pi.size.Height);

                        TabPage tp = new TabPage(Marshal.PtrToStringAuto(pi.szTitle));
                        _tabs.Controls.Add(tp);
                        _pages.Add(pp);
                        pp.Activate(tp.Handle, ref rect, false);

                        // some PropertyPages aren't visible by default
                        IntPtr childwindow = GetWindow(tp.Handle, 5);
                        if (childwindow != IntPtr.Zero)
                        {
                            ShowWindow(childwindow, 5);
                        }
                    }
                    catch
                    {
                        // some property pages don't abide by the rules of COM
                    }
                }
            }
        }
Exemple #15
0
 public static IntPtr GetIUnknownForObject(object obj)
 {
     return(obj == null ? IntPtr.Zero : Marshal.GetIUnknownForObject(obj));
 }
 IntPtr nsIFactory.CreateInstance(nsISupports aOuter, ref Guid iid)
 {
     return(Marshal.GetIUnknownForObject(new PromptService()));
 }
Exemple #17
0
        /// <summary>
        /// Rename document in the running document table from oldName to newName.
        /// </summary>
        /// <param name="provider">The service provider.</param>
        /// <param name="oldName">Full path to the old name of the document.</param>
        /// <param name="newName">Full path to the new name of the document.</param>
        /// <param name="newItemId">The new item id of the document</param>
        public static void RenameDocument(IServiceProvider site, string oldName, string newName, uint newItemId)
        {
            Utilities.ArgumentNotNull("site", site);

            if (String.IsNullOrEmpty(oldName))
            {
                throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "oldName");
            }

            if (String.IsNullOrEmpty(newName))
            {
                throw new ArgumentException(SR.GetString(SR.ParameterCannotBeNullOrEmpty, CultureInfo.CurrentUICulture), "newName");
            }

            IVsRunningDocumentTable pRDT = site.GetService(typeof(SVsRunningDocumentTable)) as IVsRunningDocumentTable;
            IVsUIShellOpenDocument  doc  = site.GetService(typeof(SVsUIShellOpenDocument)) as IVsUIShellOpenDocument;

            if (pRDT == null || doc == null)
            {
                return;
            }

            IVsHierarchy pIVsHierarchy;
            uint         itemId;
            IntPtr       docData;
            uint         uiVsDocCookie;

            ErrorHandler.ThrowOnFailure(pRDT.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, oldName, out pIVsHierarchy, out itemId, out docData, out uiVsDocCookie));

            if (docData != IntPtr.Zero)
            {
                try
                {
                    IntPtr pUnk = Marshal.GetIUnknownForObject(pIVsHierarchy);
                    Guid   iid  = typeof(IVsHierarchy).GUID;
                    IntPtr pHier;
                    Marshal.QueryInterface(pUnk, ref iid, out pHier);
                    try
                    {
                        ErrorHandler.ThrowOnFailure(pRDT.RenameDocument(oldName, newName, pHier, newItemId));
                    }
                    catch (Exception)
                    {
                        int i = 0;
                    }
                    finally
                    {
                        if (pHier != IntPtr.Zero)
                        {
                            Marshal.Release(pHier);
                        }
                        if (pUnk != IntPtr.Zero)
                        {
                            Marshal.Release(pUnk);
                        }
                    }
                }
                finally
                {
                    Marshal.Release(docData);
                }
            }
        }
Exemple #18
0
 internal Direct3DSurface9(ComInterface.IDirect3DSurface9 obj)
 {
     this.comObject = obj;
     this.native    = Marshal.GetIUnknownForObject(this.comObject);
 }
        internal static IntPtr GetJSContextForDomWindow(nsIDOMWindow window)
        {
            IntPtr            context     = IntPtr.Zero;
            nsIDOMEventTarget eventTarget = window.GetWindowRootAttribute();

            try
            {
                context = eventTarget.GetJSContextForEventHandlers();
                if (context == IntPtr.Zero)
                {
                    IntPtr pUnk = Marshal.GetIUnknownForObject(window);
                    Marshal.Release(pUnk);


                    if (!_windowContexts.TryGetValue(pUnk, out context))
                    {
                        context = IntPtr.Zero;

                        IntPtr cx;
                        IntPtr iterp = IntPtr.Zero;
                        IntPtr rt    = Runtime;
                        while ((cx = SpiderMonkey.JS_ContextIterator(rt, ref iterp)) != IntPtr.Zero)
                        {
                            IntPtr pGlobal = SpiderMonkey.DefaultObjectForContextOrNull(cx);
                            if (pGlobal != IntPtr.Zero)
                            {
                                using (var auto = new AutoJSContext(cx))
                                {
                                    using (ComPtr <nsISupports> global = auto.GetGlobalNsObject())
                                    {
                                        if (global != null)
                                        {
                                            var domWindow = Xpcom.QueryInterface <nsIDOMWindow>(global.Instance);
                                            if (domWindow != null)
                                            {
                                                try
                                                {
                                                    IntPtr pUnkTest = Marshal.GetIUnknownForObject(domWindow.GetWindowAttribute());
                                                    Marshal.Release(pUnkTest);

                                                    if (pUnk == pUnkTest)
                                                    {
                                                        _windowContexts.Add(pUnk, cx);
                                                        context = cx;
                                                        break;
                                                    }
                                                }
                                                finally
                                                {
                                                    Xpcom.FreeComObject(ref domWindow);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            finally
            {
                if (eventTarget != null)
                {
                    Xpcom.FreeComObject(ref eventTarget);
                }
            }
            return(context);
        }
Exemple #20
0
        public PROPVARIANT(object obj)
        {
            vt = VT_UNKNOWN;

            pUnknown = Marshal.GetIUnknownForObject(obj);
        }
Exemple #21
0
        public static object QueryInterface(object obj, Guid iid)
        {
            AssertCorrectThread();

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

            // get an nsISupports (aka IUnknown) pointer from the object
            IntPtr pUnk = Marshal.GetIUnknownForObject(obj);

            if (pUnk == IntPtr.Zero)
            {
                return(null);
            }

            // query interface
            IntPtr ppv;

            Marshal.QueryInterface(pUnk, ref iid, out ppv);

            // if QueryInterface didn't work, try using nsIInterfaceRequestor instead
            if (ppv == IntPtr.Zero)
            {
                // QueryInterface the object for nsIInterfaceRequestor
                Guid   interfaceRequestorIID = typeof(nsIInterfaceRequestor).GUID;
                IntPtr pInterfaceRequestor;
                Marshal.QueryInterface(pUnk, ref interfaceRequestorIID, out pInterfaceRequestor);

                // if we got a pointer to nsIInterfaceRequestor
                if (pInterfaceRequestor != IntPtr.Zero)
                {
                    // convert it to a managed interface
                    QI_nsIInterfaceRequestor req = (QI_nsIInterfaceRequestor)Xpcom.GetObjectForIUnknown(pInterfaceRequestor);

                    if (req != null)
                    {
                        try
                        {
                            req.GetInterface(ref iid, out ppv);
                            // clean up
                            Marshal.ReleaseComObject(req);
                        }
                        catch (NullReferenceException ex)
                        {
                            Debug.WriteLine("NullRefException from native code.\n" + ex.ToString());
                        }
                    }
                    Marshal.Release(pInterfaceRequestor);
                }
            }

            object result = (ppv != IntPtr.Zero) ? Xpcom.GetObjectForIUnknown(ppv) : null;

            Marshal.Release(pUnk);
            if (ppv != IntPtr.Zero)
            {
                Marshal.Release(ppv);
            }

            return(result);
        }
        public int CreateEditorInstance(
            uint grfCreateDoc,
            string pszMkDocument,
            string pszPhysicalView,
            IVsHierarchy vsHierarchy,
            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;
            pbstrEditorCaption = string.Empty;
            pguidCmdUI         = Guid.Empty;
            pgrfCDW            = 0;

            var physicalView = pszPhysicalView == null
                ? "Code"
                : pszPhysicalView;

            IVsTextBuffer textBuffer = null;

            // Is this document already open? If so, let's see if it's a IVsTextBuffer we should re-use. This allows us
            // to properly handle multiple windows open for the same document.
            if (punkDocDataExisting != IntPtr.Zero)
            {
                object docDataExisting = Marshal.GetObjectForIUnknown(punkDocDataExisting);

                textBuffer = docDataExisting as IVsTextBuffer;

                if (textBuffer == null)
                {
                    // We are incompatible with the existing doc data
                    return(VSConstants.VS_E_INCOMPATIBLEDOCDATA);
                }
            }

            // Do we need to create a text buffer?
            if (textBuffer == null)
            {
                var contentType = _contentTypeRegistryService.GetContentType(ContentTypeName);
                textBuffer = _editorAdaptersFactoryService.CreateVsTextBufferAdapter(_oleServiceProvider, contentType);

                if (_encoding)
                {
                    var userData = textBuffer as IVsUserData;
                    if (userData != null)
                    {
                        // The editor shims require that the boxed value when setting the PromptOnLoad flag is a uint
                        int hresult = userData.SetData(
                            VSConstants.VsTextBufferUserDataGuid.VsBufferEncodingPromptOnLoad_guid,
                            (uint)__PROMPTONLOADFLAGS.codepagePrompt);

                        if (ErrorHandler.Failed(hresult))
                        {
                            return(hresult);
                        }
                    }
                }
            }

            // If the text buffer is marked as read-only, ensure that the padlock icon is displayed
            // next the new window's title and that [Read Only] is appended to title.
            READONLYSTATUS readOnlyStatus = READONLYSTATUS.ROSTATUS_NotReadOnly;
            uint           textBufferFlags;

            if (ErrorHandler.Succeeded(textBuffer.GetStateFlags(out textBufferFlags)) &&
                0 != (textBufferFlags & ((uint)BUFFERSTATEFLAGS.BSF_FILESYS_READONLY | (uint)BUFFERSTATEFLAGS.BSF_USER_READONLY)))
            {
                readOnlyStatus = READONLYSTATUS.ROSTATUS_ReadOnly;
            }

            switch (physicalView)
            {
            case "Form":

                // We must create the WinForms designer here
                const string LoaderName      = "Microsoft.VisualStudio.Design.Serialization.CodeDom.VSCodeDomDesignerLoader";
                var          designerService = (IVSMDDesignerService)ServiceProvider.GetService(typeof(SVSMDDesignerService));
                var          designerLoader  = (IVSMDDesignerLoader)designerService.CreateDesignerLoader(LoaderName);

                try
                {
                    designerLoader.Initialize(_oleServiceProvider, vsHierarchy, (int)itemid, (IVsTextLines)textBuffer);
                    pbstrEditorCaption = designerLoader.GetEditorCaption((int)readOnlyStatus);

                    var designer = designerService.CreateDesigner(_oleServiceProvider, designerLoader);
                    ppunkDocView = Marshal.GetIUnknownForObject(designer.View);
                    pguidCmdUI   = designer.CommandGuid;
                }
                catch
                {
                    designerLoader.Dispose();
                    throw;
                }

                break;

            case "Code":

                var codeWindow = _editorAdaptersFactoryService.CreateVsCodeWindowAdapter(_oleServiceProvider);
                codeWindow.SetBuffer((IVsTextLines)textBuffer);

                codeWindow.GetEditorCaption(readOnlyStatus, out pbstrEditorCaption);

                ppunkDocView = Marshal.GetIUnknownForObject(codeWindow);
                pguidCmdUI   = VSConstants.GUID_TextEditorFactory;

                break;

            default:

                return(VSConstants.E_INVALIDARG);
            }

            ppunkDocData = Marshal.GetIUnknownForObject(textBuffer);

            return(VSConstants.S_OK);
        }
Exemple #23
0
            private void WmGetObject(ref Message m)
            {
                if (m.LParam == (IntPtr)NativeMethods.UiaRootObjectId)
                {
                    AccessibleObject uiaProvider = GetChildAccessibleObject(_childWindowType);

                    // If the requested object identifier is UiaRootObjectId,
                    // we should return an UI Automation provider using the UiaReturnRawElementProvider function.
                    InternalAccessibleObject internalAccessibleObject = new InternalAccessibleObject(uiaProvider);
                    m.Result = UiaCore.UiaReturnRawElementProvider(
                        new HandleRef(this, Handle),
                        m.WParam,
                        m.LParam,
                        internalAccessibleObject);

                    return;
                }

                // See "How to Handle WM_GETOBJECT" in MSDN
                //
                if (unchecked ((int)(long)m.LParam) == OBJID.CLIENT)
                {
                    // Get the IAccessible GUID
                    //
                    Guid IID_IAccessible = new Guid(NativeMethods.uuid_IAccessible);

                    // Get an Lresult for the accessibility Object for this control
                    //
                    IntPtr punkAcc;
                    try
                    {
                        AccessibleObject            wfAccessibleObject = null;
                        UiaCore.IAccessibleInternal iacc = null;

                        if (_accessibilityObject is null)
                        {
                            wfAccessibleObject   = GetChildAccessibleObject(_childWindowType);
                            _accessibilityObject = new InternalAccessibleObject(wfAccessibleObject);
                        }

                        iacc = (UiaCore.IAccessibleInternal)_accessibilityObject;

                        // Obtain the Lresult
                        //
                        punkAcc = Marshal.GetIUnknownForObject(iacc);

                        try
                        {
                            m.Result = Oleacc.LresultFromObject(ref IID_IAccessible, m.WParam, new HandleRef(this, punkAcc));
                        }
                        finally
                        {
                            Marshal.Release(punkAcc);
                        }
                    }
                    catch (Exception e)
                    {
                        throw new InvalidOperationException(SR.RichControlLresult, e);
                    }
                }
                else
                {  // m.lparam != OBJID_CLIENT, so do default message processing
                    DefWndProc(ref m);
                }
            }
Exemple #24
0
        public void CreateWindowSizeDependentResources()
        {
            WaitForGpu();

            for (int n = 0; n < FrameCount; n++)
            {
                DirectXHelper.ReleaseCom(_renderTargets[n]);
                _renderTargets[n] = null;
                _fenceValues[n]   = _fenceValues[_currentFrame];
            }

            UpdateRenderTargetSize();

            DXGI_MODE_ROTATION displayRotation = ComputeDisplayRotation();

            bool swapDimensions =
                displayRotation == DXGI_MODE_ROTATION.DXGI_MODE_ROTATION_ROTATE90 ||
                displayRotation == DXGI_MODE_ROTATION.DXGI_MODE_ROTATION_ROTATE270;

            _d3dRenderTargetSize.Width  = swapDimensions ? _outputSize.Height : _outputSize.Width;
            _d3dRenderTargetSize.Height = swapDimensions ? _outputSize.Width : _outputSize.Height;

            uint backBufferWidth  = (uint)Math.Round(_d3dRenderTargetSize.Width, MidpointRounding.AwayFromZero);
            uint backBufferHeight = (uint)Math.Round(_d3dRenderTargetSize.Height, MidpointRounding.AwayFromZero);

            if (_swapChain != null)
            {
                HRESULT hr = _swapChain.Ptr->ResizeBuffers(FrameCount, backBufferWidth, backBufferHeight, _backBufferFormat,
                                                           0);

                if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET)
                {
                    _deviceRemoved = true;

                    return;
                }
                else
                {
                    DirectXHelper.ThrowIfFailed(hr);
                }
            }
            else
            {
                DXGI_SCALING scaling = DisplayMetrics.SupportHighResolutions
                    ? DXGI_SCALING.DXGI_SCALING_NONE
                    : DXGI_SCALING.DXGI_SCALING_STRETCH;

                DXGI_SWAP_CHAIN_DESC1 swapChainDesc;

                swapChainDesc.Width              = backBufferWidth;
                swapChainDesc.Height             = backBufferHeight;
                swapChainDesc.Format             = _backBufferFormat;
                swapChainDesc.Stereo             = 0;
                swapChainDesc.SampleDesc.Count   = 1;
                swapChainDesc.SampleDesc.Quality = 0;
                swapChainDesc.BufferUsage        = DXGI.DXGI_USAGE_RENDER_TARGET_OUTPUT;
                swapChainDesc.BufferCount        = FrameCount;
                swapChainDesc.SwapEffect         = DXGI_SWAP_EFFECT.DXGI_SWAP_EFFECT_FLIP_DISCARD;
                swapChainDesc.Flags              = 0;
                swapChainDesc.Scaling            = scaling;
                swapChainDesc.AlphaMode          = DXGI_ALPHA_MODE.DXGI_ALPHA_MODE_IGNORE;

                {
                    using ComPtr <IDXGISwapChain1> swapChain = null;
                    IntPtr pWindow = Marshal.GetIUnknownForObject(_window);
                    DirectXHelper.ThrowIfFailed(
                        _dxgiFactory.Ptr->CreateSwapChainForCoreWindow(
                            _commandQueue,
                            (IUnknown *)pWindow,
                            &swapChainDesc,
                            null,
                            swapChain.GetAddressOf()));

                    IDXGISwapChain3 *swapChain3;
                    Guid             iid = DXGI.IID_IDXGISwapChain3;
                    DirectXHelper.ThrowIfFailed(swapChain.Ptr->QueryInterface(&iid, (void **)&swapChain3));
                    _swapChain = swapChain3;
                }
            }

            switch (displayRotation)
            {
            case DXGI_MODE_ROTATION.DXGI_MODE_ROTATION_IDENTITY:
                _orientationTransform3D = ScreenRotation.Rotation0;
                break;

            case DXGI_MODE_ROTATION.DXGI_MODE_ROTATION_ROTATE90:
                _orientationTransform3D = ScreenRotation.Rotation270;
                break;

            case DXGI_MODE_ROTATION.DXGI_MODE_ROTATION_ROTATE180:
                _orientationTransform3D = ScreenRotation.Rotation180;
                break;

            case DXGI_MODE_ROTATION.DXGI_MODE_ROTATION_ROTATE270:
                _orientationTransform3D = ScreenRotation.Rotation90;
                break;
            }

            DirectXHelper.ThrowIfFailed(_swapChain.Ptr->SetRotation(displayRotation));

            {
                _currentFrame = (int)_swapChain.Ptr->GetCurrentBackBufferIndex();
                D3D12_CPU_DESCRIPTOR_HANDLE rtvDescriptor = _rtvHeap.Ptr->GetCPUDescriptorHandleForHeapStart();

                fixed(void *pBuffer = & _renderTargets)
                {
                    var p = (ID3D12Resource **)pBuffer;

                    Guid iid = D3D12.IID_ID3D12Resource;

                    for (var n = 0; n < FrameCount; n++)
                    {
                        DirectXHelper.ThrowIfFailed(_swapChain.Ptr->GetBuffer((uint)n, &iid, (void **)&p[n]));
                        _d3dDevice.Ptr->CreateRenderTargetView(
                            _renderTargets[n],
                            null,
                            rtvDescriptor);

                        rtvDescriptor.Offset((int)_rtvDescriptorSize);

                        DirectXHelper.NameObject(_renderTargets[n], $"{nameof(_renderTargets)}[{n}]"); // _renderTargets[n]
                    }
                }
            }

            {
                D3D12_HEAP_PROPERTIES depthHeapProperties = CD3DX12_HEAP_PROPERTIES.Create(D3D12_HEAP_TYPE.D3D12_HEAP_TYPE_DEFAULT);

                D3D12_RESOURCE_DESC depthResourceDesc =
                    CD3DX12_RESOURCE_DESC.Tex2D(_depthBufferFormat, backBufferWidth, backBufferHeight, 1, 1);

                depthResourceDesc.Flags |= D3D12_RESOURCE_FLAGS.D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;

                D3D12_CLEAR_VALUE depthOptimizedClearValue = CD3DX12_CLEAR_VALUE.Create(_depthBufferFormat, 1, 0);

                fixed(ID3D12Resource **p = _depthStencil)
                {
                    Guid iid = D3D12.IID_ID3D12Resource;

                    DirectXHelper.ThrowIfFailed(_d3dDevice.Ptr->CreateCommittedResource(
                                                    &depthHeapProperties,
                                                    D3D12_HEAP_FLAGS.D3D12_HEAP_FLAG_NONE,
                                                    &depthResourceDesc,
                                                    D3D12_RESOURCE_STATES.D3D12_RESOURCE_STATE_DEPTH_WRITE,
                                                    &depthOptimizedClearValue,
                                                    &iid,
                                                    (void **)p
                                                    ));

                    DirectXHelper.NameObject(_depthStencil, nameof(_depthStencil));

                    D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc = default;

                    dsvDesc.Format        = _depthBufferFormat;
                    dsvDesc.ViewDimension = D3D12_DSV_DIMENSION.D3D12_DSV_DIMENSION_TEXTURE2D;
                    dsvDesc.Flags         = D3D12_DSV_FLAGS.D3D12_DSV_FLAG_NONE;
                    D3D12_CPU_DESCRIPTOR_HANDLE handle = _dsvHeap.Ptr->GetCPUDescriptorHandleForHeapStart();

                    _d3dDevice.Ptr->CreateDepthStencilView(_depthStencil.Ptr, &dsvDesc, handle);
                }
            }

            // 0.0f, 0.0f, m_d3dRenderTargetSize.Width, m_d3dRenderTargetSize.Height, 0.0f, 1.0f
            _screenViewport = new D3D12_VIEWPORT
            {
                TopLeftX = 0,
                TopLeftY = 0,
                Width    = (float)_d3dRenderTargetSize.Width,
                Height   = (float)_d3dRenderTargetSize.Height,
                MinDepth = 0,
                MaxDepth = 1
            };
        }
        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);
        }
Exemple #26
0
        private async Task <IVsWindowFrame> CreateDocWindowAsync(
            Project project,
            string documentName,
            IVsHierarchy hier,
            uint itemId)
        {
            uint windowFlags =
                (uint)_VSRDTFLAGS.RDT_DontAddToMRU |
                (uint)_VSRDTFLAGS.RDT_DontSaveAs;

            var solutionManager = ServiceLocator.GetInstance <ISolutionManager>();

            if (!solutionManager.IsSolutionAvailable)
            {
                throw new InvalidOperationException(Strings.SolutionIsNotSaved);
            }

            var nugetProject = solutionManager.GetNuGetProject(EnvDTEProjectUtility.GetCustomUniqueName(project));

            // If we failed to generate a cache entry in the solution manager something went wrong.
            if (nugetProject == null)
            {
                throw new InvalidOperationException(
                          string.Format(Resources.ProjectHasAnInvalidNuGetConfiguration, project.Name));
            }

            // load packages.config. This makes sure that an exception will get thrown if there
            // are problems with packages.config, such as duplicate packages. When an exception
            // is thrown, an error dialog will pop up and this doc window will not be created.
            var installedPackages = await nugetProject.GetInstalledPackagesAsync(CancellationToken.None);

            var uiContextFactory = ServiceLocator.GetInstance <INuGetUIContextFactory>();
            var uiContext        = uiContextFactory.Create(this, new[] { nugetProject });

            var uiFactory    = ServiceLocator.GetInstance <INuGetUIFactory>();
            var uiController = uiFactory.Create(uiContext, _uiProjectContext);

            var model = new PackageManagerModel(uiController, uiContext, isSolution: false, editorFactoryGuid: GuidList.guidNuGetEditorType);
            var vsWindowSearchHostfactory = ServiceLocator.GetGlobalService <SVsWindowSearchHostFactory, IVsWindowSearchHostFactory>();
            var vsShell        = ServiceLocator.GetGlobalService <SVsShell, IVsShell4>();
            var control        = new PackageManagerControl(model, Settings, vsWindowSearchHostfactory, vsShell, _outputConsoleLogger);
            var windowPane     = new PackageManagerWindowPane(control);
            var guidEditorType = GuidList.guidNuGetEditorType;
            var guidCommandUI  = Guid.Empty;
            var caption        = String.Format(
                CultureInfo.CurrentCulture,
                Resx.Label_NuGetWindowCaption,
                project.Name);

            IVsWindowFrame windowFrame;
            IVsUIShell     uiShell = (IVsUIShell)GetService(typeof(SVsUIShell));

            IntPtr ppunkDocView = IntPtr.Zero;
            IntPtr ppunkDocData = IntPtr.Zero;
            int    hr           = 0;

            try
            {
                ppunkDocView = Marshal.GetIUnknownForObject(windowPane);
                ppunkDocData = Marshal.GetIUnknownForObject(model);
                hr           = uiShell.CreateDocumentWindow(
                    windowFlags,
                    documentName,
                    (IVsUIHierarchy)hier,
                    itemId,
                    ppunkDocView,
                    ppunkDocData,
                    ref guidEditorType,
                    null,
                    ref guidCommandUI,
                    null,
                    caption,
                    string.Empty,
                    null,
                    out windowFrame);
            }
            finally
            {
                if (ppunkDocView != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocData);
                }

                if (ppunkDocData != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocView);
                }
            }

            ErrorHandler.ThrowOnFailure(hr);
            return(windowFrame);
        }
 public void GetIUnknownForObject_Unix_ThrowsPlatformNotSupportedException()
 {
     Assert.Throws <PlatformNotSupportedException>(() => Marshal.GetIUnknownForObject(null));
 }
Exemple #28
0
        private async Task <IVsWindowFrame> CreateDocWindowForSolutionAsync()
        {
            IVsWindowFrame windowFrame = null;
            IVsSolution    solution    = ServiceLocator.GetInstance <IVsSolution>();
            IVsUIShell     uiShell     = (IVsUIShell)GetService(typeof(SVsUIShell));
            uint           windowFlags =
                (uint)_VSRDTFLAGS.RDT_DontAddToMRU |
                (uint)_VSRDTFLAGS.RDT_DontSaveAs;

            var solutionManager = ServiceLocator.GetInstance <ISolutionManager>();

            if (!solutionManager.IsSolutionAvailable)
            {
                throw new InvalidOperationException(Strings.SolutionIsNotSaved);
            }

            var projects = solutionManager.GetNuGetProjects();

            if (!projects.Any())
            {
                // NOTE: The menu 'Manage NuGet Packages For Solution' will be disabled in this case.
                // But, it is possible, that, before NuGetPackage is loaded in VS, the menu is enabled and used.
                // For once, this message will be shown. Once the package is loaded, the menu will get disabled as appropriate
                MessageHelper.ShowWarningMessage(Resources.NoSupportedProjectsInSolution, Resources.ErrorDialogBoxTitle);
                return(null);
            }

            // load packages.config. This makes sure that an exception will get thrown if there
            // are problems with packages.config, such as duplicate packages. When an exception
            // is thrown, an error dialog will pop up and this doc window will not be created.
            foreach (var project in projects)
            {
                await project.GetInstalledPackagesAsync(CancellationToken.None);
            }

            var uiContextFactory = ServiceLocator.GetInstance <INuGetUIContextFactory>();
            var uiContext        = uiContextFactory.Create(this, projects);

            var uiFactory    = ServiceLocator.GetInstance <INuGetUIFactory>();
            var uiController = uiFactory.Create(uiContext, _uiProjectContext);

            var solutionName = (string)_dte.Solution.Properties.Item("Name").Value;
            var model        = new PackageManagerModel(uiController, uiContext, isSolution: true, editorFactoryGuid: GuidList.guidNuGetEditorType);

            model.SolutionName = solutionName;
            var vsWindowSearchHostfactory = ServiceLocator.GetGlobalService <SVsWindowSearchHostFactory, IVsWindowSearchHostFactory>();
            var vsShell        = ServiceLocator.GetGlobalService <SVsShell, IVsShell4>();
            var control        = new PackageManagerControl(model, Settings, vsWindowSearchHostfactory, vsShell, _outputConsoleLogger);
            var windowPane     = new PackageManagerWindowPane(control);
            var guidEditorType = GuidList.guidNuGetEditorType;
            var guidCommandUI  = Guid.Empty;
            var caption        = Resx.Label_SolutionNuGetWindowCaption;
            var documentName   = _dte.Solution.FullName;

            IntPtr ppunkDocView = IntPtr.Zero;
            IntPtr ppunkDocData = IntPtr.Zero;
            int    hr           = 0;

            try
            {
                ppunkDocView = Marshal.GetIUnknownForObject(windowPane);
                ppunkDocData = Marshal.GetIUnknownForObject(model);
                hr           = uiShell.CreateDocumentWindow(
                    windowFlags,
                    documentName,
                    (IVsUIHierarchy)solution,
                    (uint)VSConstants.VSITEMID.Root,
                    ppunkDocView,
                    ppunkDocData,
                    ref guidEditorType,
                    null,
                    ref guidCommandUI,
                    null,
                    caption,
                    string.Empty,
                    null,
                    out windowFrame);
            }
            finally
            {
                if (ppunkDocView != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocData);
                }

                if (ppunkDocData != IntPtr.Zero)
                {
                    Marshal.Release(ppunkDocView);
                }
            }

            ErrorHandler.ThrowOnFailure(hr);
            return(windowFrame);
        }
            private static HRESULT GetData(IntPtr thisPtr, FORMATETC *format, STGMEDIUM_Raw *pMedium)
            {
                var instance = ComInterfaceDispatch.GetInstance <IDataObject>((ComInterfaceDispatch *)thisPtr);

                try
                {
                    instance.GetData(ref *format, out var medium);
                    pMedium->pUnkForRelease = medium.pUnkForRelease == null ? IntPtr.Zero : Marshal.GetIUnknownForObject(medium.pUnkForRelease);
                    pMedium->tymed          = medium.tymed;
                    pMedium->unionmember    = medium.unionmember;
                    return(HRESULT.S_OK);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex);
                    return((HRESULT)ex.HResult);
                }
            }
Exemple #30
0
        public PropVariant(object value, PropertyType?type = null)
        {
            if (value == null)
            {
                _vt = PropertyType.VT_NULL;
                return;
            }

            if (Marshal.IsComObject(value))
            {
                _ptr = Marshal.GetIUnknownForObject(value);
                _vt  = PropertyType.VT_UNKNOWN;
                return;
            }

            if (value is PropVariant pv)
            {
                value = pv.Value;
            }

            if (value is char[] chars)
            {
                value = new string(chars);
            }

            if (value is char[][])
            {
                var charray = value as char[][];
                var strings = new string[charray.GetLength(0)];
                for (var i = 0; i < charray.Length; i++)
                {
                    strings[i] = new string(charray[i]);
                }
                value = strings;
            }

            if (value is Array array)
            {
                ConstructArray(array, type);
                return;
            }

            if (!(value is string) && value is IEnumerable enumerable)
            {
                ConstructEnumerable(enumerable, type);
                return;
            }

            var tc = Type.GetTypeCode(value.GetType());

            switch (tc)
            {
            case TypeCode.Boolean:
                _boolean = (bool)value ? (short)(-1) : (short)0;
                break;

            case TypeCode.Byte:
                _byte = (byte)value;
                break;

            case TypeCode.Char:
                chars = new[] { (char)value };
                _ptr  = MarshalString(new string(chars), FromType(typeof(string), type));
                break;

            case TypeCode.DateTime:
                var ft = ToPositiveFileTime((DateTime)value);
                if (ft == 0)
                {
                    break;     // stay empty
                }
                InitPropVariantFromFileTime(ref ft, this);
                break;

            case TypeCode.Empty:
            case TypeCode.DBNull:
                break;

            case TypeCode.Decimal:
                _decimal = (decimal)value;
                break;

            case TypeCode.Double:
                _double = (double)value;
                break;

            case TypeCode.Int16:
                _int16 = (short)value;
                break;

            case TypeCode.Int32:
                _int32 = (int)value;
                break;

            case TypeCode.Int64:
                _int64 = (long)value;
                break;

            case TypeCode.SByte:
                _sbyte = (sbyte)value;
                break;

            case TypeCode.Single:
                _single = (float)value;
                break;

            case TypeCode.String:
                _ptr = MarshalString((string)value, FromType(typeof(string), type));
                break;

            case TypeCode.UInt16:
                _uint16 = (ushort)value;
                break;

            case TypeCode.UInt32:
                _uint32 = (uint)value;
                break;

            case TypeCode.UInt64:
                _uint64 = (ulong)value;
                break;

            //case TypeCode.Object:
            default:
                if (value is Guid guid)
                {
                    _ptr = Marshal.AllocCoTaskMem(16);
                    Marshal.Copy(guid.ToByteArray(), 0, _ptr, 16);
                    break;
                }

                if (value is System.Runtime.InteropServices.ComTypes.FILETIME filetime)
                {
                    _filetime = filetime;
                    break;
                }
                throw new ArgumentException("Value of type '" + value.GetType().FullName + "' is not supported.", nameof(value));
            }

            _vt = FromType(value.GetType(), type);
        }