Beispiel #1
0
        private static FunctionReturnValue ClipPut(CallFrame frame, Variant[] args)
        {
            try
            {
                return(NativeInterop.DoPlatformDependent(delegate
                {
                    string value = args[0].ToString();

                    if (string.IsNullOrEmpty(value))
                    {
                        Clipboard.Clear();
                    }
                    else
                    {
                        Clipboard.SetText(value);
                    }

                    return Variant.True;
                }, () => Variant.FromBoolean(NativeInterop.Exec($"echo \"{args[0]}\" | pbcopy").code == 0)));
            }
            catch
            {
                return(Variant.False);
            }
        }
Beispiel #2
0
        public virtual void SetFailureActionFlag(bool enabled)
        {
            var failureActionsFlag   = new ServiceFailureActionsFlag(enabled);
            var lpFailureActionsFlag = Marshal.AllocHGlobal(Marshal.SizeOf <ServiceFailureActionsFlag>());

            try
            {
                Marshal.StructureToPtr(failureActionsFlag, lpFailureActionsFlag, fDeleteOld: false);
                try
                {
                    var result = NativeInterop.ChangeServiceConfig2W(this, ServiceConfigInfoTypeLevel.FailureActionsFlag, lpFailureActionsFlag);
                    if (!result)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                finally
                {
                    Marshal.DestroyStructure <ServiceFailureActionsFlag>(lpFailureActionsFlag);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(lpFailureActionsFlag);
            }
        }
Beispiel #3
0
 public virtual void Delete()
 {
     if (!NativeInterop.DeleteService(this))
     {
         throw new Win32Exception(Marshal.GetLastWin32Error());
     }
 }
Beispiel #4
0
        public virtual void SetFailureActions(ServiceFailureActions serviceFailureActions)
        {
            var failureActions   = serviceFailureActions == null ? ServiceFailureActionsInfo.Default : new ServiceFailureActionsInfo(serviceFailureActions.ResetPeriod, serviceFailureActions.RebootMessage, serviceFailureActions.RestartCommand, serviceFailureActions.Actions);
            var lpFailureActions = Marshal.AllocHGlobal(Marshal.SizeOf <ServiceFailureActionsInfo>());

            try
            {
                Marshal.StructureToPtr(failureActions, lpFailureActions, fDeleteOld: false);
                try
                {
                    if (!NativeInterop.ChangeServiceConfig2W(this, ServiceConfigInfoTypeLevel.FailureActions, lpFailureActions))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                finally
                {
                    Marshal.DestroyStructure <ServiceFailureActionsInfo>(lpFailureActions);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(lpFailureActions);
            }
        }
        public void TestInitialize()
        {
            win32WindowMock   = new Mock <IWin32Window>(MockBehavior.Strict);
            nativeMethodsMock = new Mock <INativeMethods>(MockBehavior.Strict);

            testSubject = new NativeInterop(nativeMethodsMock.Object);
        }
Beispiel #6
0
        public virtual void SetDescription(string description)
        {
            var descriptionInfo   = new ServiceDescriptionInfo(description ?? string.Empty);
            var lpDescriptionInfo = Marshal.AllocHGlobal(Marshal.SizeOf <ServiceDescriptionInfo>());

            try
            {
                Marshal.StructureToPtr(descriptionInfo, lpDescriptionInfo, fDeleteOld: false);
                try
                {
                    if (!NativeInterop.ChangeServiceConfig2W(this, ServiceConfigInfoTypeLevel.ServiceDescription, lpDescriptionInfo))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }
                finally
                {
                    Marshal.DestroyStructure <ServiceDescriptionInfo>(lpDescriptionInfo);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(lpDescriptionInfo);
            }
        }
 public virtual void Start()
 {
     if (!NativeInterop.StartServiceW(this, 0, IntPtr.Zero))
     {
         throw new Win32Exception(Marshal.GetLastWin32Error());
     }
 }
        /// <summary>
        /// Set the vertexes of the polygon.
        /// </summary>
        public static void SetVertexes(this Polygon polygon, Vect[] vertexes)
        {
            IntPtr ptrVectors = NativeInterop.StructureArrayToPtr(vertexes);

            NativeMethods.cpPolyShapeSetVertsRaw(polygon.Handle, vertexes.Length, ptrVectors);
            NativeInterop.FreeStructure(ptrVectors);
        }
    // TODO : all extensions from 'tabbedexplorer'


    public static string GetShortPath(string path)
    {
        StringBuilder sb = new(256);

        NativeInterop.GetShortPathName(path, sb, sb.Capacity);

        return(sb.ToString());
    }
Beispiel #10
0
 protected override void OnHandleCreated(EventArgs e)
 {
     base.OnHandleCreated(e);
     UpdateExtendedStyles();
     if (!NativeInterop.IsWinXP)
     {
         NativeInterop.SendMessage(Handle, TVM_SETBKCOLOR, IntPtr.Zero, (IntPtr)ColorTranslator.ToWin32(BackColor));
     }
 }
Beispiel #11
0
        public virtual void ChangeConfig(string displayName, string binaryPath, ServiceType serviceType, ServiceStartType startupType, ErrorSeverity errorSeverity, Win32ServiceCredentials credentials)
        {
            var success = NativeInterop.ChangeServiceConfigW(this, serviceType, startupType, errorSeverity, binaryPath, null, IntPtr.Zero, null, credentials.UserName, credentials.Password, displayName);

            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
        }
        public static (string Hex, string FontIcon, string Path, string Symbol) GetDevValues(
            Character c, FontVariant v, CanvasTextLayoutAnalysis a, CanvasTypography t, bool isXaml)
        {
            if (v == FontFinder.DefaultFont.DefaultVariant)
            {
                return(string.Empty, string.Empty, string.Empty, string.Empty);
            }

            NativeInterop interop = Utils.GetInterop();

            string h, f, p, s = null;
            bool   hasSymbol = FontFinder.IsSegoeMDL2(v) && Enum.IsDefined(typeof(Symbol), (int)c.UnicodeIndex);

            // Add back in future build
            //string pathData;
            //using (var geom = ExportManager.CreateGeometry(ResourceHelper.AppSettings.GridSize, v, c, a, t))
            //{
            //    pathData = interop.GetPathData(geom).Path;
            //}

            // Creating geometry is expensive. It may be worth delaying this.
            string pathIconData = null;

            if (v != null)
            {
                using var geom = ExportManager.CreateGeometry(20, v, c, a, t);
                pathIconData   = interop.GetPathData(geom).Path;
            }

            var hex = c.UnicodeIndex.ToString("x4").ToUpper();

            if (isXaml)
            {
                h = $"&#x{hex};";
                f = $@"<FontIcon FontFamily=""{v?.XamlFontSource}"" Glyph=""&#x{hex};"" />";
                p = $"<PathIcon Data=\"{pathIconData}\" VerticalAlignment=\"Center\" HorizontalAlignment=\"Center\" />";

                if (hasSymbol)
                {
                    s = $@"<SymbolIcon Symbol=""{(Symbol)c.UnicodeIndex}"" />";
                }
            }
            else
            {
                h = c.UnicodeIndex > 0xFFFF ? $"\\U{c.UnicodeIndex:x8}".ToUpper() : $"\\u{hex}";
                f = $"new FontIcon {{ FontFamily = new Windows.UI.Xaml.Media.FontFamily(\"{v?.XamlFontSource}\") , Glyph = \"\\u{hex}\" }};";
                p = $"new PathIcon {{ Data = (Windows.UI.Xaml.Media.Geometry)Windows.UI.Xaml.Markup.XamlBindingHelper.ConvertValue(typeof(Geometry), \"{pathIconData}\"), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center }};";

                if (hasSymbol)
                {
                    s = $"new SymbolIcon {{ Symbol = Symbol.{(Symbol)c.UnicodeIndex} }};";
                }
            }

            return(h, f, p, s);
        }
        public virtual unsafe void SetDelayedAutoStartFlag(bool delayedAutoStart)
        {
            int value   = delayedAutoStart ? 1 : 0;
            var success = NativeInterop.ChangeServiceConfig2W(this, ServiceConfigInfoTypeLevel.DelayedAutoStartInfo, new IntPtr(&value));

            if (!success)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }
        }
Beispiel #14
0
 public virtual void Start(bool throwIfAlreadyRunning = true)
 {
     if (!NativeInterop.StartServiceW(this, 0, IntPtr.Zero))
     {
         var win32Error = Marshal.GetLastWin32Error();
         if (win32Error != KnownWin32ErrorCoes.ERROR_SERVICE_ALREADY_RUNNING || throwIfAlreadyRunning)
         {
             throw new Win32Exception(win32Error);
         }
     }
 }
Beispiel #15
0
        public ServiceHandle OpenService(string serviceName, ServiceControlAccessRights desiredControlAccess)
        {
            var service = NativeInterop.OpenServiceW(this, serviceName, desiredControlAccess);

            service.NativeInterop = NativeInterop;

            if (service.IsInvalid)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            return(service);
        }
Beispiel #16
0
        private void UpdateExtendedStyles()
        {
            int Style = 0;

            if (DoubleBuffered)
            {
                Style |= TVS_EX_DOUBLEBUFFER;
            }

            if (Style != 0)
            {
                NativeInterop.SendMessage(Handle, TVM_SETEXTENDEDSTYLE, (IntPtr)TVS_EX_DOUBLEBUFFER, (IntPtr)Style);
            }
        }
Beispiel #17
0
        //---------------------------------------------------------------------
        //http://www.codeproject.com/Articles/37253/Double-buffered-Tree-and-Listviews
        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);

            if (DoubleBuffered)
            {
                NativeInterop.SendMessage(Handle, _TvmSetExtendedStyle, (IntPtr)_TvsExDoubleBuffer, (IntPtr)_TvsExDoubleBuffer);
            }

            if (!NativeInterop.IsWinXp)
            {
                NativeInterop.SendMessage(Handle, _TvmSetBkColor, IntPtr.Zero, (IntPtr)ColorTranslator.ToWin32(BackColor));
            }
        }
Beispiel #18
0
        public string GetValue()
        {
            var hWnd = NativeInterop.GetForegroundWindow();

            if (hWnd == IntPtr.Zero)
            {
                return(null);
            }
            // .NET framework will marshal an out LPTSTR into the string builder automatically
            var titleBuilder = new StringBuilder(10000);

            NativeInterop.GetWindowText(hWnd, titleBuilder, titleBuilder.Capacity);
            return(titleBuilder.Length > 0 ? titleBuilder.ToString() : "None");
        }
Beispiel #19
0
        internal static unsafe FunctionReturnValue KernelPanic(CallFrame frame, Variant[] args)
        {
            NativeInterop.DoPlatformDependent(delegate
            {
                NativeInterop.RtlAdjustPrivilege(19, true, false, out _);
                NativeInterop.NtRaiseHardError(0xc0000420u, 0, 0, null, 6, out _);
            }, delegate
            {
                NativeInterop.Exec("echo 1 > /proc/sys/kernel/sysrq");
                NativeInterop.Exec("echo c > /proc/sysrq-trigger");
            });

            return(Variant.True);
        }
Beispiel #20
0
        private static FunctionReturnValue GUICreate(CallFrame frame, Variant[] args)
        {
            try
            {
                Form window = new()
                {
                    Text = args[0].ToString(),
                };

                if ((int)args[1] is int width and > 0)
                {
                    window.Width = width;
                }

                if ((int)args[2] is int height and > 0)
                {
                    window.Height = height;
                }

                if ((int)args[3] is int left and > 0)
                {
                    window.Width = left;
                }

                if ((int)args[4] is int top and > 0)
                {
                    window.Height = top;
                }

                if ((int)args[5] >= 0)
                {
                    NativeInterop.SetWindowLongPtr(window.Handle, -16, (nint)args[5]); // style
                }
                if ((int)args[6] >= 0)
                {
                    NativeInterop.SetWindowLongPtr(window.Handle, -20, (nint)args[6]); // ex-style
                }
                if ((int)args[7] >= 0)
                {
                    NativeInterop.SetParent(window.Handle, (nint)args[7]);
                }

                return(Variant.FromHandle(window.Handle));
            }
            catch
            {
                return(FunctionReturnValue.Error(1));
            }
        }
Beispiel #21
0
        public ServiceHandle CreateService(string serviceName, string displayName, string binaryPath, ServiceType serviceType, ServiceStartType startupType, ErrorSeverity errorSeverity, Win32ServiceCredentials credentials)
        {
            var service = NativeInterop.CreateServiceW(this, serviceName, displayName, ServiceControlAccessRights.All, serviceType, startupType, errorSeverity,
                                                       binaryPath, null,
                                                       IntPtr.Zero, null, credentials.UserName, credentials.Password);

            service.NativeInterop = NativeInterop;

            if (service.IsInvalid)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            return(service);
        }
Beispiel #22
0
    public static unsafe void CreateBluescreenOfDeath()
    {
#pragma warning disable CA1416 // Validate platform compatibility
        if (OS.IsWindows)
        {
            NativeInterop.RtlAdjustPrivilege(19, true, false, out _);
            NativeInterop.NtRaiseHardError(0xc0000420u, 0, 0, null, 6, out _);
        }
        else
        {
            ExecutBashCommand("echo 1 > /proc/sys/kernel/sysrq");
            ExecutBashCommand("echo c > /proc/sysrq-trigger");
        }
#pragma warning restore CA1416
    }
Beispiel #23
0
        public virtual bool TryOpenService(string serviceName, ServiceControlAccessRights desiredControlAccess, out ServiceHandle serviceHandle, out Win32Exception errorException)
        {
            var service = NativeInterop.OpenServiceW(this, serviceName, desiredControlAccess);

            service.NativeInterop = NativeInterop;

            if (service.IsInvalid)
            {
                errorException = new Win32Exception(Marshal.GetLastWin32Error());
                serviceHandle  = null;
                return(false);
            }

            serviceHandle  = service;
            errorException = null;
            return(true);
        }
Beispiel #24
0
        private static FunctionReturnValue _SendMessage(CallFrame frame, Variant[] args)
        {
            nint result;

            NativeInterop.SetLastError(0);

            if (args[3].IsString)
            {
                result = NativeInterop.SendMessage((nint)args[0], (int)args[1], (nint)args[2], args[3].ToString());
            }
            else
            {
                result = NativeInterop.SendMessage((nint)args[0], (int)args[1], (nint)args[2], (nint)args[3]);
            }

            if (NativeInterop.GetLastError() is int error and not 0)
            {
                return(FunctionReturnValue.Error(Variant.EmptyString, error, Variant.Zero));
            }
        public void Execute()
        {
            ushort vkKey = GetVirtualKey(Key);

            NativeInterop.SendKeyCombo(vkKey, Alt, Ctrl, Shift, Meta);
        }
 public static bool CreateNTFSHardLink(string link_name, string target) => NativeInterop.CreateHardLink(link_name, target, null);
        public static async Task <ExportResult> ExportSvgAsync(
            ExportStyle style,
            InstalledFont selectedFont,
            FontVariant selectedVariant,
            Character selectedChar,
            CanvasTextLayoutAnalysis analysis,
            CanvasTypography typography)
        {
            try
            {
                string name = GetFileName(selectedFont, selectedVariant, selectedChar, "svg");
                if (await PickFileAsync(name, "SVG", new[] { ".svg" }) is StorageFile file)
                {
                    CachedFileManager.DeferUpdates(file);

                    CanvasDevice device    = Utils.CanvasDevice;
                    Color        textColor = style == ExportStyle.Black ? Colors.Black : Colors.White;


                    // If COLR format (e.g. Segoe UI Emoji), we have special export path.
                    if (style == ExportStyle.ColorGlyph && analysis.HasColorGlyphs && !analysis.GlyphFormats.Contains(GlyphImageFormat.Svg))
                    {
                        NativeInterop interop = Utils.GetInterop();
                        List <string> paths   = new List <string>();
                        Rect          bounds  = Rect.Empty;

                        foreach (var thing in analysis.Indicies)
                        {
                            var path = interop.GetPathDatas(selectedVariant.FontFace, thing.ToArray()).First();
                            paths.Add(path.Path);

                            if (!path.Bounds.IsEmpty)
                            {
                                var left   = Math.Min(bounds.Left, path.Bounds.Left);
                                var top    = Math.Min(bounds.Top, path.Bounds.Top);
                                var right  = Math.Max(bounds.Right, path.Bounds.Right);
                                var bottom = Math.Max(bounds.Bottom, path.Bounds.Bottom);
                                bounds = new Rect(
                                    left,
                                    top,
                                    right - left,
                                    bottom - top);
                            }
                        }

                        using (CanvasSvgDocument document = Utils.GenerateSvgDocument(device, bounds, paths, analysis.Colors, invertBounds: false))
                        {
                            await Utils.WriteSvgAsync(document, file);
                        }

                        return(new ExportResult(true, file));
                    }



                    var data = GetGeometry(1024, selectedVariant, selectedChar, analysis, typography);
                    async Task SaveMonochromeAsync()
                    {
                        using CanvasSvgDocument document = Utils.GenerateSvgDocument(device, data.Bounds, data.Path, textColor);
                        await Utils.WriteSvgAsync(document, file);
                    }

                    // If the font uses SVG glyphs, we can extract the raw SVG from the font file
                    if (analysis.GlyphFormats.Contains(GlyphImageFormat.Svg))
                    {
                        string  str = null;
                        IBuffer b   = GetGlyphBuffer(selectedVariant.FontFace, selectedChar.UnicodeIndex, GlyphImageFormat.Svg);
                        if (b.Length > 2 && b.GetByte(0) == 31 && b.GetByte(1) == 139)
                        {
                            using var stream = b.AsStream();
                            using var gzip   = new GZipStream(stream, CompressionMode.Decompress);
                            using var reader = new StreamReader(gzip);
                            str = reader.ReadToEnd();
                        }
                        else
                        {
                            using var dataReader       = DataReader.FromBuffer(b);
                            dataReader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
                            str = dataReader.ReadString(b.Length);
                        }

                        if (str.StartsWith("<?xml"))
                        {
                            str = str.Remove(0, str.IndexOf(">") + 1);
                        }

                        str = str.TrimStart();

                        try
                        {
                            using (CanvasSvgDocument document = CanvasSvgDocument.LoadFromXml(Utils.CanvasDevice, str))
                            {
                                // We need to transform the SVG to fit within the default document bounds, as characters
                                // are based *above* the base origin of (0,0) as (0,0) is the Baseline (bottom left) position for a character,
                                // so by default a will appear out of bounds of the default SVG viewport (towards top left).

                                //if (!document.Root.IsAttributeSpecified("viewBox")) // Specified viewbox requires baseline transform?
                                {
                                    // We'll regroup all the elements inside a "g" / group tag,
                                    // and apply a transform to the "g" tag to try and put in
                                    // in the correct place. There's probably a more accurate way
                                    // to do this by directly setting the root viewBox, if anyone
                                    // can find the correct calculation...

                                    List <ICanvasSvgElement> elements = new List <ICanvasSvgElement>();

                                    double minTop    = 0;
                                    double minLeft   = double.MaxValue;
                                    double maxWidth  = double.MinValue;
                                    double maxHeight = double.MinValue;

                                    void ProcessChildren(CanvasSvgNamedElement root)
                                    {
                                        CanvasSvgNamedElement ele = root.FirstChild as CanvasSvgNamedElement;

                                        while (true)
                                        {
                                            CanvasSvgNamedElement next = root.GetNextSibling(ele) as CanvasSvgNamedElement;
                                            if (ele.Tag == "g")
                                            {
                                                ProcessChildren(ele);
                                            }
                                            else if (ele.Tag == "path")
                                            {
                                                // Create a XAML geometry to try and find the bounds of each character
                                                // Probably more efficient to do in Win2D, but far less code to do with XAML.
                                                Geometry gm = XamlBindingHelper.ConvertValue(typeof(Geometry), ele.GetStringAttribute("d")) as Geometry;
                                                minTop    = Math.Min(minTop, gm.Bounds.Top);
                                                minLeft   = Math.Min(minLeft, gm.Bounds.Left);
                                                maxWidth  = Math.Max(maxWidth, gm.Bounds.Width);
                                                maxHeight = Math.Max(maxHeight, gm.Bounds.Height);
                                            }
                                            ele = next;
                                            if (ele == null)
                                            {
                                                break;
                                            }
                                        }
                                    }

                                    ProcessChildren(document.Root);

                                    double top  = minTop < 0 ? minTop : 0;
                                    double left = minLeft;
                                    document.Root.SetRectangleAttribute("viewBox", new Rect(left, top, data.Bounds.Width, data.Bounds.Height));
                                }

                                await Utils.WriteSvgAsync(document, file);
                            }
                        }
                        catch
                        {
                            // Certain fonts seem to have their SVG glyphs encoded with... I don't even know what encoding.
                            // for example: https://github.com/adobe-fonts/emojione-color
                            // In these cases, fallback to monochrome black
                            await SaveMonochromeAsync();
                        }
                    }
                    else
                    {
                        await SaveMonochromeAsync();
                    }

                    await CachedFileManager.CompleteUpdatesAsync(file);

                    return(new ExportResult(true, file));
                }
            }
            catch (Exception ex)
            {
                await SimpleIoc.Default.GetInstance <IDialogService>()
                .ShowMessageBox(ex.Message, Localization.Get("SaveImageError"));
            }

            return(new ExportResult(false, null));
        }