Esempio n. 1
0
        private static void FinishUriSchemeCallback(IntPtr url, IntPtr schemeTask, IntPtr data, long contentLength, Uri uri)
        {
            IntPtr response = Foundation.Call("NSURLResponse", "alloc");

            ObjC.Call(
                response,
                "initWithURL:MIMEType:expectedContentLength:textEncodingName:",
                url,
                NSString.Create(MimeTypes.FindForUri(uri)),
                new IntPtr(contentLength),
                IntPtr.Zero);

            ObjC.Call(schemeTask, "didReceiveResponse:", response);

            IntPtr nsData = Foundation.Call(
                "NSData",
                "dataWithBytesNoCopy:length:freeWhenDone:",
                data,
                new IntPtr(contentLength),
                IntPtr.Zero);

            ObjC.Call(schemeTask, "didReceiveData:", nsData);

            ObjC.Call(schemeTask, "didFinish");
        }
Esempio n. 2
0
        public Task <string?> ExecuteScriptAsync(string script)
        {
            var     taskResult = new TaskCompletionSource <string?>();
            NSBlock?block      = null;

            ScriptEvalCallbackDelegate callback = (IntPtr self, IntPtr result, IntPtr error) =>
            {
                try
                {
                    if (error != IntPtr.Zero)
                    {
                        string?message = NSString.GetString(ObjC.Call(error, "localizedDescription"));
                        taskResult.TrySetException(new ScriptException($"Script execution failed with: \"{message}\""));
                    }
                    else
                    {
                        string?content = NSString.GetString(result);
                        taskResult.TrySetResult(content);
                    }
                }
                catch (Exception ex) { taskResult.TrySetException(ex); }
                finally { block !.Dispose(); }
            };

            block = new NSBlock(callback);
            ObjC.Call(
                Handle,
                "evaluateJavaScript:completionHandler:",
                NSString.Create(script),
                block.Handle);

            return(taskResult.Task);
        }
Esempio n. 3
0
        public CocoaWebview(WindowConfiguration config, IContentProvider contentProvider, WebviewBridge bridge)
        {
            this.config          = config ?? throw new ArgumentNullException(nameof(config));
            this.contentProvider = contentProvider ?? throw new ArgumentNullException(nameof(contentProvider));
            this.bridge          = bridge ?? throw new ArgumentNullException(nameof(bridge));

            Interlocked.Increment(ref count);

            // need to keep the delegates around or they will get garbage collected
            loadDelegate                 = LoadCallback;
            loadFailedDelegate           = LoadFailedCallback;
            observedValueChangedDelegate = ObservedValueChanged;
            scriptDelegate               = ScriptCallback;
            uriSchemeStartDelegate       = UriSchemeStartCallback;
            uriSchemeStopDelegate        = UriSchemeStopCallback;


            IntPtr configuration = WebKit.Call("WKWebViewConfiguration", "new");
            IntPtr manager       = ObjC.Call(configuration, "userContentController");
            IntPtr callbackClass = CreateCallbackClass();

            customHost = CreateSchemeHandler(configuration);

            if (config.EnableScriptInterface)
            {
                ObjC.Call(manager, "addScriptMessageHandler:name:", callbackClass, NSString.Create("external"));
                IntPtr script = WebKit.Call("WKUserScript", "alloc");
                ObjC.Call(
                    script,
                    "initWithSource:injectionTime:forMainFrameOnly:",
                    NSString.Create(Resources.GetInitScript("Mac")),
                    IntPtr.Zero,
                    IntPtr.Zero);
                ObjC.Call(manager, "addUserScript:", script);
            }

            Handle = WebKit.Call("WKWebView", "alloc");
            ObjC.Call(Handle, "initWithFrame:configuration:", CGRect.Zero, configuration);
            ObjC.Call(Handle, "setNavigationDelegate:", callbackClass);

            IntPtr bgColor = NSColor.FromHex(config.BackgroundColor);

            ObjC.Call(Handle, "setBackgroundColor:", bgColor);

            IntPtr boolValue = Foundation.Call("NSNumber", "numberWithBool:", 0);

            ObjC.Call(Handle, "setValue:forKey:", boolValue, NSString.Create("drawsBackground"));

            if (config.UseBrowserTitle)
            {
                ObjC.Call(Handle, "addObserver:forKeyPath:options:context:", callbackClass, NSString.Create("title"), IntPtr.Zero, IntPtr.Zero);
            }

            if (enableDevTools)
            {
                var preferences = ObjC.Call(configuration, "preferences");
                ObjC.Call(preferences, "setValue:forKey:", new IntPtr(1), NSString.Create("developerExtrasEnabled"));
            }
        }
Esempio n. 4
0
        public void SetShortcut(ModifierKey modifier, Key key)
        {
            NSEventModifierFlags nsModifier = KeyMapper.GetModifier(modifier);
            string mappedKey = KeyMapper.GetKey(key);

            ObjC.Call(Handle, "setKeyEquivalentModifierMask:", new UIntPtr((ulong)nsModifier));
            ObjC.Call(Handle, "setKeyEquivalent:", NSString.Create(mappedKey));
        }
Esempio n. 5
0
    public void StringArg()
    {
        NSObject instance = (NSObject) new Class("Subclass1").Call("alloc").Call("init");

        NSString n = (NSString)instance.Call("TakeString", NSString.Create("hmm"));

        Assert.AreEqual("hmmhmm", n.ToString());
    }
Esempio n. 6
0
    public void DerivedArg()
    {
        Subclass1 x = Subclass1.make(13);
        NSString  s = NSString.Create("hey");

        NSString t = x.Call("concat", s, s).To <NSString>();

        Assert.AreEqual("heyhey", t.description());
    }
Esempio n. 7
0
 private CocoaLabelMenuItem(string label, string action)
     : base(AppKit.Call("NSMenuItem", "alloc"))
 {
     ObjC.Call(
         Handle,
         "initWithTitle:action:keyEquivalent:",
         NSString.Create(label),
         ObjC.RegisterName(action),
         NSString.Create(string.Empty));
 }
Esempio n. 8
0
        private static void FinishUriSchemeCallbackWithError(IntPtr schemeTask, int errorCode)
        {
            var error = Foundation.Call(
                "NSError",
                "errorWithDomain:code:userInfo:",
                NSString.Create("com.bildstein.spidereye"),
                new IntPtr(errorCode),
                IntPtr.Zero);

            ObjC.Call(schemeTask, "didFailWithError:", error);
        }
Esempio n. 9
0
 public CocoaMenu(string title)
 {
     if (title != null)
     {
         Handle = AppKit.Call("NSMenu", "alloc");
         ObjC.Call(Handle, "initWithTitle:", NSString.Create(title));
     }
     else
     {
         Handle = AppKit.Call("NSMenu", "new");
     }
 }
Esempio n. 10
0
        public DialogResult Show(IWindow?parent)
        {
            var window = NativeCast.To <CocoaWindow>(parent);

            using var alert = NSDialog.CreateAlert();
            ObjC.Call(alert.Handle, "setShowsHelp:", IntPtr.Zero);
            ObjC.Call(alert.Handle, "setAlertStyle:", new UIntPtr((uint)NSAlertStyle.Informational));
            ObjC.Call(alert.Handle, "setMessageText:", NSString.Create(Title ?? string.Empty));
            ObjC.Call(alert.Handle, "setInformativeText:", NSString.Create(Message ?? string.Empty));
            AddButtons(alert.Handle, Buttons);

            return((DialogResult)alert.Run(window));
        }
Esempio n. 11
0
        private void SetFileFilters(IntPtr dialog, IEnumerable <FileFilter> filters)
        {
            var fileTypes = filters
                            .SelectMany(t => t.Filters.Select(u => u.TrimStart('*', '.')))
                            .Distinct()
                            .Select(t => NSString.Create(t));

            if (fileTypes.Any())
            {
                var data  = fileTypes.ToArray();
                var array = Foundation.Call("NSArray", "arrayWithObjects:count:", data, new IntPtr(data.Length));
                ObjC.Call(dialog, "setAllowedFileTypes:", array);
            }
        }
Esempio n. 12
0
        protected override void BeforeShow(NSDialog dialog)
        {
            if (!string.IsNullOrWhiteSpace(InitialDirectory))
            {
                var url = Foundation.Call("NSURL", "fileURLWithPath:", NSString.Create(InitialDirectory));
                ObjC.Call(dialog.Handle, "setDirectoryURL:", url);
            }

            if (!string.IsNullOrWhiteSpace(FileName))
            {
                ObjC.Call(dialog.Handle, "setNameFieldStringValue:", NSString.Create(FileName));
            }

            SetFileFilters(dialog.Handle, FileFilters);
        }
Esempio n. 13
0
        public DialogResult Show(IWindow parent)
        {
            var window = NativeCast.To <CocoaWindow>(parent);
            var dialog = CreateDialog();

            ObjC.Call(dialog.Handle, "setTitle:", NSString.Create(Title));
            ObjC.Call(dialog.Handle, "setCanCreateDirectories:", true);

            int result       = dialog.Run(window);
            var mappedResult = MapResult(result);

            BeforeReturn(dialog, mappedResult);

            return(mappedResult);
        }
        public CocoaLabelMenuItem(string label)
            : base(AppKit.Call("NSMenuItem", "alloc"))
        {
            // need to keep the delegate around or it will get garbage collected
            menuDelegate = MenuCallback;

            ObjC.Call(
                Handle,
                "initWithTitle:action:keyEquivalent:",
                NSString.Create(label),
                ObjC.RegisterName("menuCallback:"),
                NSString.Create(string.Empty));

            SetCallbackClass();
        }
Esempio n. 15
0
        protected override NSDialog CreateDialog()
        {
            var panel = NSDialog.CreateOpenPanel();

            ObjC.Call(panel.Handle, "setCanChooseFiles:", false);
            ObjC.Call(panel.Handle, "setCanChooseDirectories:", true);
            ObjC.Call(panel.Handle, "setAllowsMultipleSelection:", false);

            if (!string.IsNullOrWhiteSpace(SelectedPath))
            {
                var url = Foundation.Call("NSURL", "fileURLWithPath:", NSString.Create(SelectedPath));
                ObjC.Call(panel.Handle, "setDirectoryURL:", url);
            }

            return(panel);
        }
Esempio n. 16
0
        public void LoadUri(Uri uri)
        {
            if (uri == null)
            {
                throw new ArgumentNullException(nameof(uri));
            }

            if (!uri.IsAbsoluteUri)
            {
                uri = new Uri(customHost, uri);
            }

            IntPtr nsUrl   = Foundation.Call("NSURL", "URLWithString:", NSString.Create(uri.ToString()));
            IntPtr request = Foundation.Call("NSURLRequest", "requestWithURL:", nsUrl);

            ObjC.Call(Handle, "loadRequest:", request);
        }
Esempio n. 17
0
        public DialogResult Show(IWindow parent)
        {
            var window = parent as CocoaWindow;

            if (parent != null && window == null)
            {
                throw new ArgumentException("Invalid window type.", nameof(parent));
            }

            using (var alert = NSDialog.CreateAlert())
            {
                ObjC.Call(alert.Handle, "setShowsHelp:", IntPtr.Zero);
                ObjC.Call(alert.Handle, "setMessageText:", NSString.Create(Title ?? string.Empty));
                ObjC.Call(alert.Handle, "setInformativeText:", NSString.Create(Message ?? string.Empty));
                AddButtons(alert.Handle, Buttons);

                return((DialogResult)alert.Run(window));
            }
        }
Esempio n. 18
0
        public void NavigateToFile(string url)
        {
            if (url == null)
            {
                throw new ArgumentNullException(nameof(url));
            }

            if (customHost != null)
            {
                url = UriTools.Combine(customHost, url).ToString();
            }
            else
            {
                url = UriTools.Combine(config.ExternalHost, url).ToString();
            }

            IntPtr nsUrl   = Foundation.Call("NSURL", "URLWithString:", NSString.Create(url));
            IntPtr request = Foundation.Call("NSURLRequest", "requestWithURL:", nsUrl);

            ObjC.Call(Handle, "loadRequest:", request);
        }
Esempio n. 19
0
        public CocoaWebview(WebviewBridge bridge)
        {
            this.bridge = bridge ?? throw new ArgumentNullException(nameof(bridge));

            IntPtr configuration = WebKit.Call("WKWebViewConfiguration", "new");
            IntPtr manager       = ObjC.Call(configuration, "userContentController");

            callbackClass = CallbackClassDefinition.CreateInstance(this);
            schemeHandler = SchemeHandlerDefinition.CreateInstance(this);

            const string scheme = "spidereye";

            customHost = new Uri(UriTools.GetRandomResourceUrl(scheme));
            ObjC.Call(configuration, "setURLSchemeHandler:forURLScheme:", schemeHandler.Handle, NSString.Create(scheme));

            ObjC.Call(manager, "addScriptMessageHandler:name:", callbackClass.Handle, NSString.Create("external"));
            IntPtr script = WebKit.Call("WKUserScript", "alloc");

            ObjC.Call(
                script,
                "initWithSource:injectionTime:forMainFrameOnly:",
                NSString.Create(Resources.GetInitScript("Mac")),
                IntPtr.Zero,
                IntPtr.Zero);
            ObjC.Call(manager, "addUserScript:", script);

            Handle = WebKit.Call("WKWebView", "alloc");
            ObjC.Call(Handle, "initWithFrame:configuration:", CGRect.Zero, configuration);
            ObjC.Call(Handle, "setNavigationDelegate:", callbackClass.Handle);

            IntPtr boolValue = Foundation.Call("NSNumber", "numberWithBool:", false);

            ObjC.Call(Handle, "setValue:forKey:", boolValue, NSString.Create("drawsBackground"));
            ObjC.Call(Handle, "addObserver:forKeyPath:options:context:", callbackClass.Handle, NSString.Create("title"), IntPtr.Zero, IntPtr.Zero);

            preferences = ObjC.Call(configuration, "preferences");
        }
Esempio n. 20
0
        public DialogResult Show(IWindow parent)
        {
            var window = parent as CocoaWindow;

            if (parent != null && window == null)
            {
                throw new ArgumentException("Invalid window type.", nameof(parent));
            }

            var dialog = CreateDialog();

            if (!string.IsNullOrWhiteSpace(InitialDirectory))
            {
                var url = Foundation.Call("NSURL", "fileURLWithPath:", NSString.Create(InitialDirectory));
                ObjC.Call(dialog.Handle, "setDirectoryURL:", url);
            }

            if (!string.IsNullOrWhiteSpace(FileName))
            {
                ObjC.Call(dialog.Handle, "setNameFieldStringValue:", NSString.Create(FileName));
            }

            ObjC.Call(dialog.Handle, "setTitle:", NSString.Create(Title));
            ObjC.Call(dialog.Handle, "setCanCreateDirectories:", true);
            SetFileFilters(dialog.Handle, FileFilters);

            int result = dialog.Run(window);

            var selection = ObjC.Call(dialog.Handle, "URL");

            FileName = NSString.GetString(ObjC.Call(selection, "path"));

            BeforeReturn(dialog);

            return(MapResult(result));
        }
Esempio n. 21
0
        private string CreateSchemeHandler(IntPtr configuration)
        {
            string host = null;

            if (string.IsNullOrWhiteSpace(config.ExternalHost))
            {
                const string scheme = "spidereye";
                host = UriTools.GetRandomResourceUrl(scheme);

                IntPtr handlerClass = ObjC.AllocateClassPair(ObjC.GetClass("NSObject"), "SchemeHandler" + count, IntPtr.Zero);
                ObjC.AddProtocol(handlerClass, ObjC.GetProtocol("WKURLSchemeHandler"));

                ObjC.AddMethod(
                    handlerClass,
                    ObjC.RegisterName("webView:startURLSchemeTask:"),
                    uriSchemeStartDelegate,
                    "v@:@@");

                ObjC.AddMethod(
                    handlerClass,
                    ObjC.RegisterName("webView:stopURLSchemeTask:"),
                    uriSchemeStopDelegate,
                    "v@:@@");

                ObjC.RegisterClassPair(handlerClass);

                IntPtr handler = ObjC.Call(handlerClass, "new");
                ObjC.Call(configuration, "setURLSchemeHandler:forURLScheme:", handler, NSString.Create(scheme));
            }

            return(host);
        }
Esempio n. 22
0
        private static void AddButton(IntPtr alert, string title, DialogResult result)
        {
            IntPtr button = ObjC.Call(alert, "addButtonWithTitle:", NSString.Create(title));

            ObjC.Call(button, "setTag:", new IntPtr((int)result));
        }
 protected override void SetShortcut(NSEventModifierFlags modifier, string key)
 {
     ObjC.Call(Handle, "setKeyEquivalentModifierMask:", new UIntPtr((ulong)modifier));
     ObjC.Call(Handle, "setKeyEquivalent:", NSString.Create(key));
 }
Esempio n. 24
0
 public NSString concat(NSString lhs, NSString rhs)
 {
     return(NSString.Create(lhs.ToString() + rhs.ToString()));
 }