You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: nsxwidget.m
    path of file: ./repos/emacs-ng/src
    
    the code of the file until where you have to start completion: /* NS Cocoa part implementation of xwidget and webkit widget.

Copyright (C) 2019-2024 Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */

#include <config.h>

#include "lisp.h"
#include "blockinput.h"
#include "dispextern.h"
#include "buffer.h"
#include "frame.h"
#include "nsterm.h"
#include "xwidget.h"

#import <AppKit/AppKit.h>
#import <WebKit/WebKit.h>

/* Thoughts on NS Cocoa xwidget and webkit2:

   Webkit2 process architecture seems to be very hostile for offscreen
   rendering techniques, which is used by GTK xwidget implementation;
   Specifically NSView level view sharing / copying is not working.

   *** So only one view can be associated with a model. ***

   With this decision, implementation is plain and can expect best out
   of webkit2's rationale.  But process and session structures will
   diverge from GTK xwidget.  Though, cosmetically similar usages can
   be presented and will be preferred, if agreeable.

   For other widget types, OSR seems possible, but will not care for a
   while.  */

/* Xwidget webkit.  */

@interface XwWebView : WKWebView
<WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler>
@property struct xwidget *xw;
/* Map url to whether javascript is blocked by
   'Content-Security-Policy' sandbox without allow-scripts.  */
@property(retain) NSMutableDictionary *urlScriptBlocked;
@end
@implementation XwWebView : WKWebView

- (id) initWithFrame:(CGRect)frame
      configuration:(WKWebViewConfiguration *)configuration
            xwidget:(struct xwidget *)xw
{
  /* Script controller to add script message handler and user script.  */
  WKUserContentController *scriptor = [[[WKUserContentController alloc] init]
                                        autorelease];
  configuration.userContentController = scriptor;

  /* Enable inspect element context menu item for debugging.  */
  [configuration.preferences setValue:@YES
                               forKey:@"developerExtrasEnabled"];

#if 0 /* Plugins are not supported by Mac OS X anymore.  */
  Lisp_Object enablePlugins =
    Fintern (build_string ("xwidget-webkit-enable-plugins"), Qnil);

  if (!EQ (Fsymbol_value (enablePlugins), Qnil))
    configuration.preferences.plugInsEnabled = YES;
#endif

  self = [super initWithFrame:frame configuration:configuration];
  if (self)
    {
      self.xw = xw;
      self.urlScriptBlocked = [[[NSMutableDictionary alloc] init]
                                autorelease];
      self.navigationDelegate = self;
      self.UIDelegate = self;
      self.customUserAgent =
        @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6)"
        @" AppleWebKit/603.3.8 (KHTML, like Gecko)"
        @" Version/11.0.1 Safari/603.3.8";
      [scriptor addScriptMessageHandler:self name:@"keyDown"];
      WKUserScript *userScript = [[[WKUserScript alloc]
                                    initWithSource:xwScript
                                     injectionTime:
                                      WKUserScriptInjectionTimeAtDocumentStart
                                    forMainFrameOnly:NO] autorelease];
      [scriptor addUserScript:userScript];
    }
  return self;
}

/* These 4 functions emulate the behavior of webkit_view_load_changed_cb
   in the GTK implementation*/
- (void) webView:(WKWebView *)webView
didFinishNavigation:(WKNavigation *)navigation
{
  if (EQ (Fbuffer_live_p (self.xw->buffer), Qt))
    store_xwidget_event_string (self.xw, "load-changed", "load-finished");
}

- (void) webView:(WKWebView *)webView
didStartProvisionalNavigation:(WKNavigation *)navigation
{
  if (EQ (Fbuffer_live_p (self.xw->buffer), Qt))
    store_xwidget_event_string (self.xw, "load-changed", "load-started");
}

- (void) webView:(WKWebView *)webView
didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation
{
  if (EQ (Fbuffer_live_p (self.xw->buffer), Qt))
    store_xwidget_event_string (self.xw, "load-changed", "load-redirected");
}

/* Start loading WKWebView */
- (void) webView:(WKWebView *)webView
didCommitNavigation:(WKNavigation *)navigation
{
  if (EQ (Fbuffer_live_p (self.xw->buffer), Qt))
    store_xwidget_event_string (self.xw, "load-changed", "load-committed");
}

- (void) webView:(WKWebView *)webView
decidePolicyForNavigationAction:
    
function xwHasFocus() {"
      @"  var ae = document.activeElement;"
      @"  if (ae) {"
      @"    var name = ae.nodeName;"
      @"    return name == 'INPUT' || name == 'TEXTAREA';"
      @"  } else {"
      @"    return false;"
      @"  }"
      @"}"
      @"function xwKeyDown(event) {"
      @"  if (event.ctrlKey && event.key == 'g') {"
      @"    window.webkit.messageHandlers.keyDown.postMessage('C-g');"
      @"  }"
      @"}"
      @"document.addEventListener('keydown', xwKeyDown);"
      ;
}

/* Confirming to WKScriptMessageHandler, listens concerning keyDown in
   webkit. Currently 'C-g'.  */
- (void) userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message
{
  if ([message.body isEqualToString:@"C-g"])
    {
      /* Just give up focus, no relay "C-g" to emacs, another "C-g"
         follows will be handled by emacs.  */
      [self.window makeFirstResponder:self.xw->xv->emacswindow];
    }
}

@end

/* Xwidget webkit commands.  */

bool
nsxwidget_is_web_view (struct xwidget *xw)
{
  return xw->xwWidget != NULL &&
    [xw->xwWidget isKindOfClass:WKWebView.class];
}

Lisp_Object
nsxwidget_webkit_uri (struct xwidget *xw)
{
  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
  return [xwWebView.URL.absoluteString lispString];
}

Lisp_Object
nsxwidget_webkit_title (struct xwidget *xw)
{
  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
  return [xwWebView.title lispString];
}

/* @Note ATS - Need application transport security in 'Info.plist' or
   remote pages will not loaded.  */
void
nsxwidget_webkit_goto_uri (struct xwidget *xw, const char *uri)
{
  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
  NSString *urlString = [NSString stringWithUTF8String:uri];
  NSURL *url = [NSURL URLWithString:urlString];
  NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
  [xwWebView loadRequest:urlRequest];
}

void
nsxwidget_webkit_goto_history (struct xwidget *xw, int rel_pos)
{
  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
  switch (rel_pos) {
  case -1: [xwWebView goBack]; break;
  case 0: [xwWebView reload]; break;
  case 1: [xwWebView goForward]; break;
  }
}

double
nsxwidget_webkit_estimated_load_progress (struct xwidget *xw)
{
  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
  return xwWebView.estimatedProgress;
}

void
nsxwidget_webkit_stop_loading (struct xwidget *xw)
{
  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
  [xwWebView stopLoading];
}

void
nsxwidget_webkit_zoom (struct xwidget *xw, double zoom_change)
{
  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
  xwWebView.magnification += zoom_change;
  /* TODO: setMagnification:centeredAtPoint.  */
}

/* Recursively convert an objc native type JavaScript value to a Lisp
   value.  Mostly copied from GTK xwidget 'webkit_js_to_lisp'.  */
static Lisp_Object
js_to_lisp (id value)
{
  if (value == nil || [value isKindOfClass:NSNull.class])
    return Qnil;
  else if ([value isKindOfClass:NSString.class])
    return [(NSString *) value lispString];
  else if ([value isKindOfClass:NSNumber.class])
    {
      NSNumber *nsnum = (NSNumber *) value;
      char type = nsnum.objCType[0];
      if (type == 'c') /* __NSCFBoolean has type character 'c'.  */
        return nsnum.boolValue? Qt : Qnil;
      else
        {
          if (type == 'i' || type == 'l')
            return make_int (nsnum.longValue);
          else if (type == 'f' || type == 'd')
            return make_float (nsnum.doubleValue);
          /* else fall through.  */
        }
    }
  else if ([value isKindOfClass:NSArray.class])
    {
      NSArray *nsarr = (NSArray *) value;
      EMACS_INT n = nsarr.count;
      Lisp_Object obj;
      struct Lisp_Vector *p = allocate_nil_vector (n);

      for (ptrdiff_t i = 0; i < n; ++i)
        p->contents[i] = js_to_lisp ([nsarr objectAtIndex:i]);
      XSETVECTOR (obj, p);
      return obj;
    }
  else if ([value isKindOfClass:NSDictionary.class])
    {
      NSDictionary *nsdict = (NSDictionary *) value;
      NSArray *keys = nsdict.allKeys;
      ptrdiff_t n = keys.count;
      Lisp_Object obj;
      struct Lisp_Vector *p = allocate_nil_vector (n);

      for (ptrdiff_t i = 0; i < n; ++i)
        {
          NSString *prop_key = (NSString *) [keys objectAtIndex:i];
          id prop_value = [nsdict valueForKey:prop_key];
          p->contents[i] = Fcons ([prop_key lispString],
                                  js_to_lisp (prop_value));
        }
      XSETVECTOR (obj, p);
      return obj;
    }
  NSLog (@"Unhandled type in javascript result");
  return Qnil;
}

void
nsxwidget_webkit_execute_script (struct xwidget *xw, const char *script,
                                 Lisp_Object fun)
{
  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
  if ([xwWebView.urlScriptBlocked[xwWebView.URL] boolValue])
    {
      message ("Javascript is blocked by 'CSP: sandbox'.");
      return;
    }

  NSString *javascriptString = [NSString stringWithUTF8String:script];
  [xwWebView evaluateJavaScript:javascriptString
              completionHandler:^(id result, NSError *error) {
      if (error)
        {
          NSLog (@"evaluateJavaScript error : %@", error.localizedDescription);
          NSLog (@"error script=%@", javascriptString);
        }
      else if (result && FUNCTIONP (fun))
        {
          /* NSLog (@"result=%@, type=%@", result, [result class]); */
          Lisp_Object lisp_value = js_to_lisp (result);
          store_xwidget_js_callback_event (xw, fun, lisp_value);
        }
    }];
}

/* Window containing an xwidget.  */

@implementation XwWindow
- (BOOL) isFlipped { return YES; }
@end