unofficial mirror of emacs-devel@gnu.org 
 help / color / mirror / code / Atom feed
* [PATCH v4] Enable xwidgets on macOS
@ 2019-07-18 19:23 Sungbin Jo
  2019-07-19  4:16 ` [PATCH v5] " Sungbin Jo
  0 siblings, 1 reply; 49+ messages in thread
From: Sungbin Jo @ 2019-07-18 19:23 UTC (permalink / raw)
  To: emacs-devel; +Cc: schwab, alan, eggert, monnier, Sungbin Jo

---
 configure.ac                     |  34 +-
 lisp/xwidget.el                  | 326 +++++++++++++----
 nextstep/templates/Info.plist.in |  12 +-
 src/Makefile.in                  |   1 +
 src/emacs.c                      |   2 +-
 src/nsterm.m                     |  22 +-
 src/nsxwidget.h                  |  80 ++++
 src/nsxwidget.m                  | 611 +++++++++++++++++++++++++++++++
 src/xwidget.c                    | 258 ++++++++++++-
 src/xwidget.h                    |  50 ++-
 10 files changed, 1292 insertions(+), 104 deletions(-)
 create mode 100644 src/nsxwidget.h
 create mode 100644 src/nsxwidget.m

diff --git a/configure.ac b/configure.ac
index c093d8650d..9685b65862 100644
--- a/configure.ac
+++ b/configure.ac
@@ -484,7 +484,7 @@ AC_DEFUN
  [with_file_notification=$with_features])
 
 OPTION_DEFAULT_OFF([xwidgets],
-  [enable use of some gtk widgets in Emacs buffers (requires gtk3)])
+  [enable use of xwidgets in Emacs buffers (requires gtk3 or macOS Cocoa)])
 
 ## For the times when you want to build Emacs but don't have
 ## a suitable makeinfo, and can live without the manuals.
@@ -2808,20 +2808,34 @@ AC_DEFUN
 
 
 dnl Enable xwidgets if GTK3 and WebKitGTK+ are available.
+dnl Enable xwidgets if macOS Cocoa and WebKit framework are available.
 HAVE_XWIDGETS=no
 XWIDGETS_OBJ=
 if test "$with_xwidgets" != "no"; then
-  test "$USE_GTK_TOOLKIT" = "GTK3" && test "$window_system" != "none" ||
-    AC_MSG_ERROR([xwidgets requested but gtk3 not used.])
+  if test "$USE_GTK_TOOLKIT" = "GTK3" && test "$window_system" != "none"; then
+    WEBKIT_REQUIRED=2.12
+    WEBKIT_MODULES="webkit2gtk-4.0 >= $WEBKIT_REQUIRED"
+    EMACS_CHECK_MODULES([WEBKIT], [$WEBKIT_MODULES])
+    HAVE_XWIDGETS=$HAVE_WEBKIT
+    XWIDGETS_OBJ="xwidget.o"
+  elif test "${NS_IMPL_COCOA}" = "yes"; then
+    dnl FIXME: Check framework WebKit2
+    dnl WEBKIT_REQUIRED=M.m.p
+    WEBKIT_LIBS="-Wl,-framework -Wl,WebKit"
+    WEBKIT_CFLAGS="-I/System/Library/Frameworks/WebKit.framework/Headers"
+    HAVE_WEBKIT="yes"
+    HAVE_XWIDGETS=$HAVE_WEBKIT
+    XWIDGETS_OBJ="xwidget.o"
+    NS_OBJC_OBJ="$NS_OBJC_OBJ nsxwidget.o"
+    dnl Update NS_OBJC_OBJ with added nsxwidget.o
+    AC_SUBST(NS_OBJC_OBJ)
+  else
+    AC_MSG_ERROR([xwidgets requested, it requires GTK3 as X window toolkit or macOS Cocoa as window system.])
+  fi
 
-  WEBKIT_REQUIRED=2.12
-  WEBKIT_MODULES="webkit2gtk-4.0 >= $WEBKIT_REQUIRED"
-  EMACS_CHECK_MODULES([WEBKIT], [$WEBKIT_MODULES])
-  HAVE_XWIDGETS=$HAVE_WEBKIT
   test $HAVE_XWIDGETS = yes ||
-    AC_MSG_ERROR([xwidgets requested but WebKitGTK+ not found.])
+    AC_MSG_ERROR([xwidgets requested but WebKitGTK+ or WebKit framework not found.])
 
-  XWIDGETS_OBJ=xwidget.o
   AC_DEFINE([HAVE_XWIDGETS], 1, [Define to 1 if you have xwidgets support.])
 fi
 AC_SUBST(XWIDGETS_OBJ)
@@ -5697,7 +5711,7 @@ AC_DEFUN
   Does Emacs directly use zlib?                           ${HAVE_ZLIB}
   Does Emacs have dynamic modules support?                ${HAVE_MODULES}
   Does Emacs use toolkit scroll bars?                     ${USE_TOOLKIT_SCROLL_BARS}
-  Does Emacs support Xwidgets (requires gtk3)?            ${HAVE_XWIDGETS}
+  Does Emacs support Xwidgets?                            ${HAVE_XWIDGETS}
   Does Emacs have threading support in lisp?              ${threads_enabled}
   Does Emacs support the portable dumper?                 ${with_pdumper}
   Does Emacs support legacy unexec dumping?               ${with_unexec}
diff --git a/lisp/xwidget.el b/lisp/xwidget.el
index 662a854ac3..9b146b0202 100644
--- a/lisp/xwidget.el
+++ b/lisp/xwidget.el
@@ -39,9 +39,10 @@
 (declare-function xwidget-buffer "xwidget.c" (xwidget))
 (declare-function xwidget-size-request "xwidget.c" (xwidget))
 (declare-function xwidget-resize "xwidget.c" (xwidget new-width new-height))
-(declare-function xwidget-webkit-execute-script "xwidget.c"
-                  (xwidget script &optional callback))
+(declare-function xwidget-webkit-uri "xwidget.c" (xwidget))
+(declare-function xwidget-webkit-title "xwidget.c" (xwidget))
 (declare-function xwidget-webkit-goto-uri "xwidget.c" (xwidget uri))
+(declare-function xwidget-webkit-goto-history "xwidget.c" (xwidget rel-pos))
 (declare-function xwidget-webkit-zoom "xwidget.c" (xwidget factor))
 (declare-function xwidget-plist "xwidget.c" (xwidget))
 (declare-function set-xwidget-plist "xwidget.c" (xwidget plist))
@@ -51,6 +52,10 @@
 (declare-function get-buffer-xwidgets "xwidget.c" (buffer))
 (declare-function xwidget-query-on-exit-flag "xwidget.c" (xwidget))
 
+(defgroup xwidget nil
+  "Displaying native widgets in Emacs buffers."
+  :group 'widgets)
+
 (defun xwidget-insert (pos type title width height &optional args)
   "Insert an xwidget at position POS.
 Supply the xwidget's TYPE, TITLE, WIDTH, and HEIGHT.
@@ -78,6 +83,8 @@ xwidget-at
 ;;; webkit support
 (require 'browse-url)
 (require 'image-mode);;for some image-mode alike functionality
+(require 'seq)
+(require 'url-handlers)
 
 ;;;###autoload
 (defun xwidget-webkit-browse-url (url &optional new-session)
@@ -96,6 +103,24 @@ xwidget-webkit-browse-url
         (xwidget-webkit-new-session url)
       (xwidget-webkit-goto-url url))))
 
+(defun xwidget-webkit-split-below ()
+  "Clone current URL into a new widget place in new window below.
+Get the URL of current session, then browse to the URL
+in `split-window-below' with a new xwidget webkit session."
+  (interactive)
+  (let ((url (xwidget-webkit-current-url)))
+    (with-selected-window (split-window-below)
+      (xwidget-webkit-new-session url))))
+
+(defun xwidget-webkit-split-right ()
+  "Clone current URL into a new widget place in new window right.
+Get the URL of current session, then browse to the URL
+in `split-window-right' with a new xwidget webkit session."
+  (interactive)
+  (let ((url (xwidget-webkit-current-url)))
+    (with-selected-window (split-window-right)
+      (xwidget-webkit-new-session url))))
+
 ;;todo.
 ;; - check that the webkit support is compiled in
 (defvar xwidget-webkit-mode-map
@@ -103,34 +128,42 @@ xwidget-webkit-mode-map
     (define-key map "g" 'xwidget-webkit-browse-url)
     (define-key map "a" 'xwidget-webkit-adjust-size-dispatch)
     (define-key map "b" 'xwidget-webkit-back)
+    (define-key map "f" 'xwidget-webkit-forward)
     (define-key map "r" 'xwidget-webkit-reload)
     (define-key map "t" (lambda () (interactive) (message "o"))) ;FIXME: ?!?
     (define-key map "\C-m" 'xwidget-webkit-insert-string)
-    (define-key map "w" 'xwidget-webkit-current-url)
+    (define-key map "w" 'xwidget-webkit-current-url-message-kill)
     (define-key map "+" 'xwidget-webkit-zoom-in)
     (define-key map "-" 'xwidget-webkit-zoom-out)
 
     ;;similar to image mode bindings
     (define-key map (kbd "SPC")                 'xwidget-webkit-scroll-up)
+    (define-key map (kbd "S-SPC")               'xwidget-webkit-scroll-down)
     (define-key map (kbd "DEL")                 'xwidget-webkit-scroll-down)
 
-    (define-key map [remap scroll-up]           'xwidget-webkit-scroll-up)
+    (define-key map [remap scroll-up]           'xwidget-webkit-scroll-up-line)
     (define-key map [remap scroll-up-command]   'xwidget-webkit-scroll-up)
 
-    (define-key map [remap scroll-down]         'xwidget-webkit-scroll-down)
+    (define-key map [remap scroll-down]         'xwidget-webkit-scroll-down-line)
     (define-key map [remap scroll-down-command] 'xwidget-webkit-scroll-down)
 
     (define-key map [remap forward-char]        'xwidget-webkit-scroll-forward)
     (define-key map [remap backward-char]       'xwidget-webkit-scroll-backward)
     (define-key map [remap right-char]          'xwidget-webkit-scroll-forward)
     (define-key map [remap left-char]           'xwidget-webkit-scroll-backward)
-    (define-key map [remap previous-line]       'xwidget-webkit-scroll-down)
-    (define-key map [remap next-line]           'xwidget-webkit-scroll-up)
+    (define-key map [remap previous-line]       'xwidget-webkit-scroll-down-line)
+    (define-key map [remap next-line]           'xwidget-webkit-scroll-up-line)
 
     ;; (define-key map [remap move-beginning-of-line] 'image-bol)
     ;; (define-key map [remap move-end-of-line]       'image-eol)
     (define-key map [remap beginning-of-buffer] 'xwidget-webkit-scroll-top)
     (define-key map [remap end-of-buffer]       'xwidget-webkit-scroll-bottom)
+
+    ;; For macOS xwidget webkit, we don't support multiple views for a
+    ;; model, instead, create a new session and model behind the scene.
+    (when (memq window-system '(mac ns))
+      (define-key map [remap split-window-below] 'xwidget-webkit-split-below)
+      (define-key map [remap split-window-right] 'xwidget-webkit-split-right))
     map)
   "Keymap for `xwidget-webkit-mode'.")
 
@@ -144,33 +177,69 @@ xwidget-webkit-zoom-out
   (interactive)
   (xwidget-webkit-zoom (xwidget-webkit-current-session) -0.1))
 
-(defun xwidget-webkit-scroll-up ()
-  "Scroll webkit up."
-  (interactive)
+(defun xwidget-webkit-scroll-up (&optional n)
+  "Scroll webkit up by N pixels or window height pixels.
+Stop if the bottom edge of the page is reached.
+If N is omitted or nil, scroll up by window height pixels."
+  (interactive "P")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(0, 50);"))
-
-(defun xwidget-webkit-scroll-down ()
-  "Scroll webkit down."
-  (interactive)
+   (format "window.scrollBy(0, %d);"
+           (or n (xwidget-window-inside-pixel-height (selected-window))))))
+
+(defun xwidget-webkit-scroll-down (&optional n)
+  "Scroll webkit down by N pixels or window height pixels.
+Stop if the top edge of the page is reached.
+If N is omitted or nil, scroll down by window height pixels."
+  (interactive "P")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(0, -50);"))
-
-(defun xwidget-webkit-scroll-forward ()
-  "Scroll webkit forwards."
-  (interactive)
+   (format "window.scrollBy(0, -%d);"
+           (or n (xwidget-window-inside-pixel-height (selected-window))))))
+
+(defcustom xwidget-webkit-scroll-line-height 50
+  "Default line height in pixels to scroll xwidget webkit."
+  :type 'integer)
+
+(defcustom xwidget-webkit-scroll-char-width 10
+  "Default char height in pixels to scroll xwidget webkit."
+  :type 'integer)
+
+(defun xwidget-webkit-scroll-up-line (&optional n)
+  "Scroll webkit up by N lines.
+The height of line is `xwidget-webkit-scroll-line-height' pixels.
+Stop if the bottom edge of the page is reached.
+If N is omitted or nil, scroll up by one line."
+  (interactive "p")
+  (xwidget-webkit-scroll-up (* n xwidget-webkit-scroll-line-height)))
+
+(defun xwidget-webkit-scroll-down-line (&optional n)
+  "Scroll webkit down by N lines.
+The height of line is `xwidget-webkit-scroll-line-height' pixels.
+Stop if the top edge of the page is reached.
+If N is omitted or nil, scroll down by one line."
+  (interactive "p")
+  (xwidget-webkit-scroll-down (* n xwidget-webkit-scroll-line-height)))
+
+(defun xwidget-webkit-scroll-forward (&optional n)
+  "Scroll webkit forwards by N chars.
+The width of char is `xwidget-webkit-scroll-char-width' pixels.
+If N is ommited or nil, scroll forwards by one char."
+  (interactive "p")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(50, 0);"))
-
-(defun xwidget-webkit-scroll-backward ()
-  "Scroll webkit backwards."
-  (interactive)
+   (format "window.scrollBy(%d, 0);"
+           (* n xwidget-webkit-scroll-char-width))))
+
+(defun xwidget-webkit-scroll-backward (&optional n)
+  "Scroll webkit backwards by N chars.
+The width of char is `xwidget-webkit-scroll-char-width' pixels.
+If N is ommited or nil, scroll backwards by one char."
+  (interactive "p")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(-50, 0);"))
+   (format "window.scrollBy(-%d, 0);"
+           (* n xwidget-webkit-scroll-char-width))))
 
 (defun xwidget-webkit-scroll-top ()
   "Scroll webkit to the very top."
@@ -184,7 +253,7 @@ xwidget-webkit-scroll-bottom
   (interactive)
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollTo(pageXOffset, window.document.body.clientHeight);"))
+   "window.scrollTo(pageXOffset, window.document.body.scrollHeight);"))
 
 ;; The xwidget event needs to go into a higher level handler
 ;; since the xwidget can generate an event even if it's offscreen.
@@ -208,7 +277,6 @@ xwidget-event-handler
        ;;TODO stopped working for some reason
        )
     ;;(funcall  xwidget-callback xwidget xwidget-event-type)
-    (message "xw callback %s" xwidget)
     (funcall  'xwidget-webkit-callback xwidget xwidget-event-type)))
 
 (defun xwidget-webkit-callback (xwidget xwidget-event-type)
@@ -219,43 +287,141 @@ xwidget-webkit-callback
        "error: callback called for xwidget with dead buffer")
     (with-current-buffer (xwidget-buffer xwidget)
       (cond ((eq xwidget-event-type 'load-changed)
-             (xwidget-webkit-execute-script
-              xwidget "document.title"
-              (lambda (title)
-                (xwidget-log "webkit finished loading: '%s'" title)
-                ;;TODO - check the native/internal scroll
-                ;;(xwidget-adjust-size-to-content xwidget)
-                (xwidget-webkit-adjust-size-to-window xwidget)
-                (rename-buffer (format "*xwidget webkit: %s *" title))))
-             (pop-to-buffer (current-buffer)))
+             ;; We do not change selected window for the finish of loading a page.
+             ;; And do not adjust webkit size to window here, the selected window
+             ;; can be the mini-buffer window unwantedly.
+             (let ((title (xwidget-webkit-title xwidget)))
+               (xwidget-log "webkit finished loading: %s" title)
+               (rename-buffer (format "*xwidget webkit: %s *" title) t)))
             ((eq xwidget-event-type 'decide-policy)
              (let ((strarg  (nth 3 last-input-event)))
                (if (string-match ".*#\\(.*\\)" strarg)
                    (xwidget-webkit-show-id-or-named-element
                     xwidget
                     (match-string 1 strarg)))))
+            ;; TODO: Response handling other than download.
+            ((eq xwidget-event-type 'download-callback)
+             (let ((url  (nth 3 last-input-event))
+                   (mime-type (nth 4 last-input-event))
+                   (file-name (nth 5 last-input-event)))
+               (xwidget-webkit-save-as-file url mime-type file-name)))
             ((eq xwidget-event-type 'javascript-callback)
              (let ((proc (nth 3 last-input-event))
                    (arg  (nth 4 last-input-event)))
-               (funcall proc arg)))
+               ;; Some javascript return vector as result
+               (funcall proc (if (vectorp arg) (seq-into arg 'list) arg))))
             (t (xwidget-log "unhandled event:%s" xwidget-event-type))))))
 
 (defvar bookmark-make-record-function)
+(defvar isearch-search-fun-function)
+(when (memq window-system '(mac ns))
+  (defcustom xwidget-webkit-enable-plugins nil
+    "Enable plugins for xwidget webkit.
+If non-nil, plugins are enabled.  Otherwise, disabled."
+    :type 'boolean))
+
 (define-derived-mode xwidget-webkit-mode
     special-mode "xwidget-webkit" "Xwidget webkit view mode."
     (setq buffer-read-only t)
+    (setq cursor-type nil)
     (setq-local bookmark-make-record-function
                 #'xwidget-webkit-bookmark-make-record)
+    (setq-local isearch-search-fun-function
+                #'xwidget-webkit-search-fun-function)
+    (setq-local isearch-lazy-highlight nil)
     ;; Keep track of [vh]scroll when switching buffers
     (image-mode-setup-winprops))
 
+;;; Download, save as file.
+
+(defcustom xwidget-webkit-download-dir "~/Downloads/"
+  "Directory where download file saved."
+  :type 'string)
+
+(defun xwidget-webkit-save-as-file (url mime-type &optional file-name)
+  "For XWIDGET webkit, save URL resource of MIME-TYPE as FILE-NAME."
+  (let ((save-name (read-file-name
+                    (format "Save '%s' file as: " mime-type)
+                    xwidget-webkit-download-dir
+                    (expand-file-name
+                     file-name
+                     xwidget-webkit-download-dir))))
+    (if (file-directory-p save-name)
+        (setq save-name
+              (expand-file-name (file-name-nondirectory file-name) save-name)))
+    (setq xwidget-webkit-download-dir (file-name-directory save-name))
+    (url-copy-file url save-name t)))
+
+;;; Bookmarks integration
+
+(defcustom xwidget-webkit-bookmark-jump-new-session nil
+  "Control bookmark jump to use new session or not.
+If non-nil, it will use a new session.  Otherwise, it will use
+`xwidget-webkit-last-session'.  When you set this variable to
+nil, consider further customization with
+`xwidget-webkit-last-session-buffer'."
+  :type 'boolean)
+
 (defun xwidget-webkit-bookmark-make-record ()
   "Integrate Emacs bookmarks with the webkit xwidget."
   (nconc (bookmark-make-record-default t t)
-         `((page     . ,(xwidget-webkit-current-url))
-           (handler  . (lambda (bmk) (browse-url
-                                 (bookmark-prop-get bmk 'page)))))))
-
+         `((page . ,(xwidget-webkit-current-url))
+           (handler  . (lambda (bmk)
+                         (xwidget-webkit-browse-url
+                          (bookmark-prop-get bmk 'page)
+                          xwidget-webkit-bookmark-jump-new-session))))))
+
+;;; Search text in page
+
+;; Initialize last search text length variable when isearch starts
+(defvar xwidget-webkit-isearch-last-length 0)
+(add-hook 'isearch-mode-hook
+          (lambda ()
+            (setq xwidget-webkit-isearch-last-length 0)))
+
+;; This is minimal. Regex and incremental search will be nice
+(defvar xwidget-webkit-search-js "
+var xwSearchForward = %s;
+var xwSearchRepeat = %s;
+var xwSearchString = '%s';
+if (window.getSelection() && !window.getSelection().isCollapsed) {
+  if (xwSearchRepeat) {
+    if (xwSearchForward)
+      window.getSelection().collapseToEnd();
+    else
+      window.getSelection().collapseToStart();
+  } else {
+    if (xwSearchForward)
+      window.getSelection().collapseToStart();
+    else {
+      var sel = window.getSelection();
+      window.getSelection().collapse(sel.focusNode, sel.focusOffset + 1);
+    }
+  }
+}
+window.find(xwSearchString, false, !xwSearchForward, true, false, true);
+")
+
+(defun xwidget-webkit-search-fun-function ()
+  "Return the function which perform the search in xwidget webkit."
+  (lambda (string &optional _bound _noerror _count)
+    (let* ((current-length (length string))
+           (search-forward (if isearch-forward "true" "false"))
+           (search-repeat
+            (if (eq current-length xwidget-webkit-isearch-last-length)
+                "true"
+              "false")))
+      (setq xwidget-webkit-isearch-last-length current-length)
+      (xwidget-webkit-execute-script
+       (xwidget-webkit-current-session)
+       (format xwidget-webkit-search-js
+               search-forward
+               search-repeat
+               (regexp-quote string)))
+      ;; Unconditionally avoid 'Failing I-search ...'
+      (goto-char (if isearch-forward (point-min) (point-max))))))
+
+;;; xwidget webkit session
 
 (defvar xwidget-webkit-last-session-buffer nil)
 
@@ -303,7 +469,7 @@ xwidget-webkit-activeelement-js"
 
 "
 
-  "javascript that finds the active element."
+  "Javascript that finds the active element."
   ;; Yes it's ugly, because:
   ;; - there is apparently no way to find the active frame other than recursion
   ;; - the js "for each" construct misbehaved on the "frames" collection
@@ -313,25 +479,29 @@ xwidget-webkit-activeelement-js"
   )
 
 (defun xwidget-webkit-insert-string ()
-  "Prompt for a string and insert it in the active field in the
-current webkit widget."
+  "Insert string into the active field in the current webkit widget."
   ;; Read out the string in the field first and provide for edit.
   (interactive)
+  ;; As the prompt needs to change based on the asynchronous execution results,
+  ;; the function must handle the string itself.
   (let ((xww (xwidget-webkit-current-session)))
+
     (xwidget-webkit-execute-script
      xww
      (concat xwidget-webkit-activeelement-js "
 (function () {
   var res = findactiveelement(document);
-  return [res.value, res.type];
+  if (res)
+    return [res.value, res.type];
 })();")
      (lambda (field)
+       "Prompt a string for the FIELD and insert in the active input."
        (let ((str (pcase field
-                    (`[,val "text"]
+                    (`(,val "text")
                      (read-string "Text: " val))
-                    (`[,val "password"]
+                    (`(,val "password")
                      (read-passwd "Password: " nil val))
-                    (`[,val "textarea"]
+                    (`(,val "textarea")
                      (xwidget-webkit-begin-edit-textarea xww val)))))
          (xwidget-webkit-execute-script
           xww
@@ -444,11 +614,23 @@ xwidget-webkit-adjust-size-dispatch
   (ignore-errors
     (recenter-top-bottom)))
 
+;; Utility functions, wanted in `window.el'
+
+(defun xwidget-window-inside-pixel-width (window)
+  "Return Emacs WINDOW body width in pixel."
+  (let ((edges (window-inside-pixel-edges window)))
+    (- (nth 2 edges) (nth 0 edges))))
+
+(defun xwidget-window-inside-pixel-height (window)
+  "Return Emacs WINDOW body height in pixel."
+  (let ((edges (window-inside-pixel-edges window)))
+    (- (nth 3 edges) (nth 1 edges))))
+
 (defun xwidget-webkit-adjust-size-to-window (xwidget &optional window)
   "Adjust the size of the webkit XWIDGET to fit the WINDOW."
   (xwidget-resize xwidget
-                  (window-pixel-width window)
-                  (window-pixel-height window)))
+                  (xwidget-window-inside-pixel-width window)
+                  (xwidget-window-inside-pixel-height window)))
 
 (defun xwidget-webkit-adjust-size (w h)
   "Manually set webkit size to width W, height H."
@@ -487,10 +669,13 @@ xwidget-webkit-new-session
                                               (get-buffer-create bufname)))
     ;; The xwidget id is stored in a text property, so we need to have
     ;; at least character in this buffer.
-    (insert " ")
-    (setq xw (xwidget-insert 1 'webkit bufname
-                             (window-pixel-width)
-                             (window-pixel-height)))
+    ;; Insert invisible url, good default for next `g' to browse url.
+    (let ((start (point)))
+      (insert url)
+      (put-text-property start (+ start (length url)) 'invisible t)
+      (setq xw (xwidget-insert start 'webkit bufname
+                               (xwidget-window-inside-pixel-width (selected-window))
+                               (xwidget-window-inside-pixel-height (selected-window)))))
     (xwidget-put xw 'callback 'xwidget-webkit-callback)
     (xwidget-webkit-mode)
     (xwidget-webkit-goto-uri (xwidget-webkit-last-session) url)))
@@ -506,23 +691,27 @@ xwidget-webkit-goto-url
 (defun xwidget-webkit-back ()
   "Go back in history."
   (interactive)
-  (xwidget-webkit-execute-script (xwidget-webkit-current-session)
-                                 "history.go(-1);"))
+  (xwidget-webkit-goto-history (xwidget-webkit-current-session) -1))
+
+(defun xwidget-webkit-forward ()
+  "Go forward in history."
+  (interactive)
+  (xwidget-webkit-goto-history (xwidget-webkit-current-session) 1))
 
 (defun xwidget-webkit-reload ()
-  "Reload current url."
+  "Reload current URL."
   (interactive)
-  (xwidget-webkit-execute-script (xwidget-webkit-current-session)
-                                 "history.go(0);"))
+  (xwidget-webkit-goto-history (xwidget-webkit-current-session) 0))
 
 (defun xwidget-webkit-current-url ()
-  "Get the webkit url and place it on the kill-ring."
+  "Get the current xwidget webkit URL."
   (interactive)
-  (xwidget-webkit-execute-script
-   (xwidget-webkit-current-session)
-   "document.URL" (lambda (rv)
-                    (let ((url (kill-new (or rv ""))))
-                      (message "url: %s" url)))))
+  (xwidget-webkit-uri (xwidget-webkit-current-session)))
+
+(defun xwidget-webkit-current-url-message-kill ()
+  "Display the current xwidget webkit URL and place it on the `kill-ring'."
+  (interactive)
+  (message "URL: %s" (kill-new (or (xwidget-webkit-current-url) ""))))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 (defun xwidget-webkit-get-selection (proc)
@@ -533,10 +722,9 @@ xwidget-webkit-get-selection
    proc))
 
 (defun xwidget-webkit-copy-selection-as-kill ()
-  "Get the webkit selection and put it on the kill-ring."
+  "Get the webkit selection and put it on the `kill-ring'."
   (interactive)
-  (xwidget-webkit-get-selection (lambda (selection) (kill-new selection))))
-
+  (xwidget-webkit-get-selection #'kill-new))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;; Xwidget plist management (similar to the process plist functions)
diff --git a/nextstep/templates/Info.plist.in b/nextstep/templates/Info.plist.in
index c1e50a8409..76efe95673 100644
--- a/nextstep/templates/Info.plist.in
+++ b/nextstep/templates/Info.plist.in
@@ -675,7 +675,15 @@ along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
 	</array>
 	<key>NSAppleScriptEnabled</key>
 	<string>YES</string>
-        <key>NSAppleEventsUsageDescription</key>
-        <string>Emacs requires permission to send AppleEvents to other applications.</string>
+	<key>NSAppleEventsUsageDescription</key>
+	<string>Emacs requires permission to send AppleEvents to other applications.</string>
+	<!-- For xwidget webkit to browse remote url,
+	     but this set no restriction at all.  Consult apple's documentation
+	     for detail information about `NSApplicationDefinedMask'. -->
+	<key>NSAppTransportSecurity</key>
+	<dict>
+		<key>NSAllowsArbitraryLoads</key>
+		<true/>
+	</dict>
 </dict>
 </plist>
diff --git a/src/Makefile.in b/src/Makefile.in
index fd05a45df5..0af650244d 100644
--- a/src/Makefile.in
+++ b/src/Makefile.in
@@ -434,6 +434,7 @@ SOME_MACHINE_OBJECTS =
   xterm.o xfns.o xmenu.o xselect.o xrdb.o xsmfns.o fringe.o image.o \
   fontset.o dbusbind.o cygw32.o \
   nsterm.o nsfns.o nsmenu.o nsselect.o nsimage.o nsfont.o macfont.o \
+  nsxwidget.o \
   w32.o w32console.o w32cygwinx.o w32fns.o w32heap.o w32inevt.o w32notify.o \
   w32menu.o w32proc.o w32reg.o w32select.o w32term.o w32xfns.o \
   w16select.o widget.o xfont.o ftfont.o xftfont.o ftxfont.o gtkutil.o \
diff --git a/src/emacs.c b/src/emacs.c
index ad661a081b..7c6871f1e7 100644
--- a/src/emacs.c
+++ b/src/emacs.c
@@ -1902,7 +1902,6 @@ main (int argc, char **argv)
       syms_of_xfns ();
       syms_of_xmenu ();
       syms_of_fontset ();
-      syms_of_xwidget ();
       syms_of_xsettings ();
 #ifdef HAVE_X_SM
       syms_of_xsmfns ();
@@ -1979,6 +1978,7 @@ main (int argc, char **argv)
 #endif /* HAVE_W32NOTIFY */
 #endif /* WINDOWSNT */
 
+      syms_of_xwidget ();
       syms_of_threads ();
       syms_of_profiler ();
       syms_of_pdumper ();
diff --git a/src/nsterm.m b/src/nsterm.m
index 02331826d9..9479c40006 100644
--- a/src/nsterm.m
+++ b/src/nsterm.m
@@ -49,6 +49,7 @@ Updated by Christian Limpach (chris@nice.ch)
 #include "nsterm.h"
 #include "systime.h"
 #include "character.h"
+#include "xwidget.h"
 #include "fontset.h"
 #include "composite.h"
 #include "ccl.h"
@@ -2411,7 +2412,7 @@ so some key presses (TAB) are swallowed by the system.  */
 }
 
 static int
-ns_note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
+ns_note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y, BOOL dragging)
 /*   ------------------------------------------------------------------------
      Called by EmacsView on mouseMovement events.  Passes on
      to emacs mainstream code if we moved off of a rect of interest
@@ -2420,17 +2421,24 @@ so some key presses (TAB) are swallowed by the system.  */
 {
   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
   NSRect *r;
+  BOOL force_update = NO;
 
   // NSTRACE ("note_mouse_movement");
 
   dpyinfo->last_mouse_motion_frame = frame;
   r = &dpyinfo->last_mouse_glyph;
 
+  /* If the last rect is too large (ex, xwidget webkit), update at
+     every move, or resizing by dragging modeline or vertical split is
+     very hard to make its way.  */
+  if (dragging && (r->size.width > 32 || r->size.height > 32))
+    force_update = YES;
+
   /* Note, this doesn't get called for enter/leave, since we don't have a
      position.  Those are taken care of in the corresponding NSView methods.  */
 
-  /* Has movement gone beyond last rect we were tracking?  */
-  if (x < r->origin.x || x >= r->origin.x + r->size.width
+  /* Has movement gone beyond last rect we were tracking? */
+  if (force_update || x < r->origin.x || x >= r->origin.x + r->size.width
       || y < r->origin.y || y >= r->origin.y + r->size.height)
     {
       ns_update_begin (frame);
@@ -4182,6 +4190,10 @@ overwriting cursor (usually when cursor on a tab).  */
         }
       break;
 
+    case XWIDGET_GLYPH:
+      x_draw_xwidget_glyph_string (s);
+      break;
+
     case STRETCH_GLYPH:
       ns_dumpglyphs_stretch (s);
       break;
@@ -6835,6 +6847,7 @@ - (void)mouseMoved: (NSEvent *)e
   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
   Lisp_Object frame;
   NSPoint pt;
+  BOOL dragging;
 
   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
 
@@ -6877,7 +6890,8 @@ - (void)mouseMoved: (NSEvent *)e
       last_mouse_window = window;
     }
 
-  if (!ns_note_mouse_movement (emacsframe, pt.x, pt.y))
+  dragging = (e.type == NSEventTypeLeftMouseDragged);
+  if (!ns_note_mouse_movement (emacsframe, pt.x, pt.y, dragging))
     help_echo_string = previous_help_echo_string;
 
   XSETFRAME (frame, emacsframe);
diff --git a/src/nsxwidget.h b/src/nsxwidget.h
new file mode 100644
index 0000000000..6af5fe5a4d
--- /dev/null
+++ b/src/nsxwidget.h
@@ -0,0 +1,80 @@
+/* Header for NS Cocoa part of xwidget and webkit widget.
+
+Copyright (C) 2011-2017 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 <http://www.gnu.org/licenses/>.  */
+
+#ifndef NSXWIDGET_H_INCLUDED
+#define NSXWIDGET_H_INCLUDED
+
+/* This file can be included from non-objc files through 'xwidget.h'.  */
+#ifdef __OBJC__
+#import <AppKit/NSView.h>
+#endif
+
+#include "dispextern.h"
+#include "lisp.h"
+#include "xwidget.h"
+
+/* Functions for xwidget webkit.  */
+
+bool nsxwidget_is_web_view (struct xwidget *xw);
+Lisp_Object nsxwidget_webkit_uri (struct xwidget *xw);
+Lisp_Object nsxwidget_webkit_title (struct xwidget *xw);
+void nsxwidget_webkit_goto_uri (struct xwidget *xw, const char *uri);
+void nsxwidget_webkit_goto_history (struct xwidget *xw, int rel_pos);
+void nsxwidget_webkit_zoom (struct xwidget *xw, double zoom_change);
+void nsxwidget_webkit_execute_script (struct xwidget *xw, const char *script,
+                                      Lisp_Object fun);
+
+/* Functions for xwidget model.  */
+
+#ifdef __OBJC__
+@interface XwWindow : NSView
+@property struct xwidget *xw;
+@end
+#endif
+
+void nsxwidget_init (struct xwidget *xw);
+void nsxwidget_kill (struct xwidget *xw);
+void nsxwidget_resize (struct xwidget *xw);
+Lisp_Object nsxwidget_get_size (struct xwidget *xw);
+
+/* Functions for xwidget view.  */
+
+#ifdef __OBJC__
+@interface XvWindow : NSView
+@property struct xwidget *xw;
+@property struct xwidget_view *xv;
+@end
+#endif
+
+void nsxwidget_init_view (struct xwidget_view *xv,
+                          struct xwidget *xww,
+                          struct glyph_string *s,
+                          int x, int y);
+void nsxwidget_delete_view (struct xwidget_view *xv);
+
+void nsxwidget_show_view (struct xwidget_view *xv);
+void nsxwidget_hide_view (struct xwidget_view *xv);
+void nsxwidget_resize_view (struct xwidget_view *xv,
+                            int widget, int height);
+
+void nsxwidget_move_view (struct xwidget_view *xv, int x, int y);
+void nsxwidget_move_widget_in_view (struct xwidget_view *xv, int x, int y);
+void nsxwidget_set_needsdisplay (struct xwidget_view *xv);
+
+#endif /* NSXWIDGET_H_INCLUDED */
diff --git a/src/nsxwidget.m b/src/nsxwidget.m
new file mode 100644
index 0000000000..8d8a92d09c
--- /dev/null
+++ b/src/nsxwidget.m
@@ -0,0 +1,611 @@
+/* NS Cocoa part implementation of xwidget and webkit widget.
+
+Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2017 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 <http://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 xwiget implementation;
+   Specifically NSView level view sharing / copying is not working.
+
+   *** So only one view can be associcated 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 xwiget.  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];
+  configuration.userContentController = scriptor;
+
+  /* Enable inspect element context menu item for debugging.  */
+  [configuration.preferences setValue:@YES
+                               forKey:@"developerExtrasEnabled"];
+
+  Lisp_Object enablePlugins =
+    Fintern (build_string ("xwidget-webkit-enable-plugins"), Qnil);
+  if (!EQ (Fsymbol_value (enablePlugins), Qnil))
+    configuration.preferences.plugInsEnabled = YES;
+
+  self = [super initWithFrame:frame configuration:configuration];
+  if (self)
+    {
+      self.xw = xw;
+      self.urlScriptBlocked = [[NSMutableDictionary alloc] init];
+      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"];
+      [scriptor addUserScript:[[WKUserScript alloc]
+                                initWithSource:xwScript
+                                 injectionTime:
+                                  WKUserScriptInjectionTimeAtDocumentStart
+                                forMainFrameOnly:NO]];
+    }
+  return self;
+}
+
+#if 0
+/* Non ARC - just to check lifecycle.  */
+- (void)dealloc
+{
+  NSLog (@"XwWebView dealloc");
+  [super dealloc];
+}
+#endif
+
+- (void)webView:(WKWebView *)webView
+didFinishNavigation:(WKNavigation *)navigation
+{
+  if (EQ (Fbuffer_live_p (self.xw->buffer), Qt))
+    store_xwidget_event_string (self.xw, "load-changed", "");
+}
+
+- (void)webView:(WKWebView *)webView
+decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
+decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
+{
+  switch (navigationAction.navigationType) {
+  case WKNavigationTypeLinkActivated:
+    decisionHandler (WKNavigationActionPolicyAllow);
+    break;
+  default:
+    // decisionHandler (WKNavigationActionPolicyCancel);
+    decisionHandler (WKNavigationActionPolicyAllow);
+    break;
+  }
+}
+
+- (void)webView:(WKWebView *)webView
+decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
+decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
+{
+  if (!navigationResponse.canShowMIMEType)
+    {
+      NSString *url = navigationResponse.response.URL.absoluteString;
+      NSString *mimetype = navigationResponse.response.MIMEType;
+      NSString *filename = navigationResponse.response.suggestedFilename;
+      decisionHandler (WKNavigationResponsePolicyCancel);
+      store_xwidget_download_callback_event (self.xw,
+                                             url.UTF8String,
+                                             mimetype.UTF8String,
+                                             filename.UTF8String);
+      return;
+    }
+  decisionHandler (WKNavigationResponsePolicyAllow);
+
+  self.urlScriptBlocked[navigationResponse.response.URL] =
+    [NSNumber numberWithBool:NO];
+  if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]])
+    {
+      NSDictionary *headers =
+        ((NSHTTPURLResponse *) navigationResponse.response).allHeaderFields;
+      NSString *value = headers[@"Content-Security-Policy"];
+      if (value)
+        {
+          /* TODO: Sloppy parsing of 'Content-Security-Policy' value.  */
+          NSRange sandbox = [value rangeOfString:@"sandbox"];
+          if (sandbox.location != NSNotFound
+              && (sandbox.location == 0
+                  || [value characterAtIndex:(sandbox.location - 1)] == ' '
+                  || [value characterAtIndex:(sandbox.location - 1)] == ';'))
+            {
+              NSRange allowScripts = [value rangeOfString:@"allow-scripts"];
+              if (allowScripts.location == NSNotFound
+                  || allowScripts.location < sandbox.location)
+                self.urlScriptBlocked[navigationResponse.response.URL] =
+                  [NSNumber numberWithBool:YES];
+            }
+        }
+    }
+}
+
+/* No additional new webview or emacs window will be created
+   for <a ... target="_blank">.  */
+- (WKWebView *)webView:(WKWebView *)webView
+createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
+   forNavigationAction:(WKNavigationAction *)navigationAction
+        windowFeatures:(WKWindowFeatures *)windowFeatures
+{
+  if (!navigationAction.targetFrame.isMainFrame)
+    [webView loadRequest:navigationAction.request];
+  return nil;
+}
+
+/* Open panel for file upload.  */
+- (void)webView:(WKWebView *)webView
+runOpenPanelWithParameters:(WKOpenPanelParameters *)parameters
+initiatedByFrame:(WKFrameInfo *)frame
+completionHandler:(void (^)(NSArray<NSURL *> *URLs))completionHandler
+{
+  NSOpenPanel *openPanel = [NSOpenPanel openPanel];
+  openPanel.canChooseFiles = YES;
+  openPanel.canChooseDirectories = NO;
+  openPanel.allowsMultipleSelection = parameters.allowsMultipleSelection;
+  if ([openPanel runModal] == NSModalResponseOK)
+    completionHandler (openPanel.URLs);
+  else
+    completionHandler (nil);
+}
+
+/* By forwarding mouse events to emacs view (frame)
+   - Mouse click in webview selects the window contains the webview.
+   - Correct mouse hand/arrow/I-beam is displayed (TODO: not perfect yet).
+*/
+
+- (void)mouseDown:(NSEvent *)event
+{
+  [self.xw->xv->emacswindow mouseDown:event];
+  [super mouseDown:event];
+}
+
+- (void)mouseUp:(NSEvent *)event
+{
+  [self.xw->xv->emacswindow mouseUp:event];
+  [super mouseUp:event];
+}
+
+/* Basically we want keyboard events handled by emacs unless an input
+   element has focus.  Especially, while incremental search, we set
+   emacs as first responder to avoid focus held in an input element
+   with matching text.  */
+
+- (void)keyDown:(NSEvent *)event
+{
+  Lisp_Object var = Fintern (build_string ("isearch-mode"), Qnil);
+  Lisp_Object val = buffer_local_value (var, Fcurrent_buffer ());
+  if (!EQ (val, Qunbound) && !EQ (val, Qnil))
+    {
+      [self.window makeFirstResponder:self.xw->xv->emacswindow];
+      [self.xw->xv->emacswindow keyDown:event];
+      return;
+    }
+
+  /* Emacs handles keyboard events when javascript is blocked.  */
+  if ([self.urlScriptBlocked[self.URL] boolValue])
+    {
+      [self.xw->xv->emacswindow keyDown:event];
+      return;
+    }
+
+  [self evaluateJavaScript:@"xwHasFocus()"
+         completionHandler:^(id result, NSError *error) {
+      if (error)
+        {
+          NSLog (@"xwHasFocus: %@", error);
+          [self.xw->xv->emacswindow keyDown:event];
+        }
+      else if (result)
+        {
+          NSNumber *hasFocus = result; /* __NSCFBoolean */
+          if (!hasFocus.boolValue)
+            [self.xw->xv->emacswindow keyDown:event];
+          else
+            [super keyDown:event];
+        }
+    }];
+}
+
+- (void)interpretKeyEvents:(NSArray<NSEvent *> *)eventArray
+{
+  /* We should do nothing and do not forward (default implementation
+     if we not override here) to let emacs collect key events and ask
+     interpretKeyEvents to its superclass.  */
+}
+
+static NSString *xwScript;
++ (void)initialize
+{
+  /* Find out if an input element has focus.
+     Message to script message handler when 'C-g' key down.  */
+  if (!xwScript)
+    xwScript =
+      @"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.  */
+
+static Lisp_Object build_string_with_nsstr (NSString *nsstr);
+
+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 build_string_with_nsstr (xwWebView.URL.absoluteString);
+}
+
+Lisp_Object
+nsxwidget_webkit_title (struct xwidget *xw)
+{
+  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
+  return build_string_with_nsstr (xwWebView.title);
+}
+
+/* @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;
+  }
+}
+
+void
+nsxwidget_webkit_zoom (struct xwidget *xw, double zoom_change)
+{
+  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
+  xwWebView.magnification += zoom_change;
+  /* TODO: setMagnification:centeredAtPoint.  */
+}
+
+/* Build lisp string */
+static Lisp_Object
+build_string_with_nsstr (NSString *nsstr)
+{
+  const char *utfstr = [nsstr UTF8String];
+  NSUInteger bytes = [nsstr lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
+  return make_string (utfstr, bytes);
+}
+
+/* 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 build_string_with_nsstr ((NSString *) value);
+  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_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_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 (build_string_with_nsstr (prop_key),
+                                  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
+
+/* Xwidget model, macOS Cocoa part.  */
+
+void
+nsxwidget_init(struct xwidget *xw)
+{
+  block_input ();
+  NSRect rect = NSMakeRect (0, 0, xw->width, xw->height);
+  xw->xwWidget = [[XwWebView alloc]
+                   initWithFrame:rect
+                   configuration:[[WKWebViewConfiguration alloc] init]
+                         xwidget:xw];
+  xw->xwWindow = [[XwWindow alloc]
+                   initWithFrame:rect];
+  [xw->xwWindow addSubview:xw->xwWidget];
+  xw->xv = NULL; /* for 1 to 1 relationship of webkit2.  */
+  unblock_input ();
+}
+
+void
+nsxwidget_kill (struct xwidget *xw)
+{
+  if (xw)
+    {
+      WKUserContentController *scriptor =
+        ((XwWebView *) xw->xwWidget).configuration.userContentController;
+      [scriptor removeAllUserScripts];
+      [scriptor removeScriptMessageHandlerForName:@"keyDown"];
+      [scriptor release];
+      if (xw->xv)
+        xw->xv->model = Qnil; /* Make sure related view stale.  */
+
+      /* This stops playing audio when a xwidget-webkit buffer is
+         killed.  I could not find other solution.  */
+      nsxwidget_webkit_goto_uri (xw, "about:blank");
+
+      [((XwWebView *) xw->xwWidget).urlScriptBlocked release];
+      [xw->xwWidget removeFromSuperviewWithoutNeedingDisplay];
+      [xw->xwWidget release];
+      [xw->xwWindow removeFromSuperviewWithoutNeedingDisplay];
+      [xw->xwWindow release];
+      xw->xwWidget = nil;
+    }
+}
+
+void
+nsxwidget_resize (struct xwidget *xw)
+{
+  if (xw->xwWidget)
+    {
+      [xw->xwWindow setFrameSize:NSMakeSize(xw->width, xw->height)];
+      [xw->xwWidget setFrameSize:NSMakeSize(xw->width, xw->height)];
+    }
+}
+
+Lisp_Object
+nsxwidget_get_size (struct xwidget *xw)
+{
+  return list2i (xw->xwWidget.frame.size.width,
+                 xw->xwWidget.frame.size.height);
+}
+
+/* Xwidget view, macOS Cocoa part.  */
+
+@implementation XvWindow : NSView
+- (BOOL)isFlipped { return YES; }
+@end
+
+void
+nsxwidget_init_view (struct xwidget_view *xv,
+                     struct xwidget *xw,
+                     struct glyph_string *s,
+                     int x, int y)
+{
+  /* 'x_draw_xwidget_glyph_string' will calculate correct position and
+     size of clip to draw in emacs buffer window.  Thus, just begin at
+     origin with no crop.  */
+  xv->x = x;
+  xv->y = y;
+  xv->clip_left = 0;
+  xv->clip_right = xw->width;
+  xv->clip_top = 0;
+  xv->clip_bottom = xw->height;
+
+  xv->xvWindow = [[XvWindow alloc]
+                   initWithFrame:NSMakeRect (x, y, xw->width, xw->height)];
+  xv->xvWindow.xw = xw;
+  xv->xvWindow.xv = xv;
+
+  xw->xv = xv; /* For 1 to 1 relationship of webkit2.  */
+  [xv->xvWindow addSubview:xw->xwWindow];
+
+  xv->emacswindow = FRAME_NS_VIEW (s->f);
+  [xv->emacswindow addSubview:xv->xvWindow];
+}
+
+void
+nsxwidget_delete_view (struct xwidget_view *xv)
+{
+  if (!EQ (xv->model, Qnil))
+    {
+      struct xwidget *xw = XXWIDGET (xv->model);
+      [xw->xwWindow removeFromSuperviewWithoutNeedingDisplay];
+      xw->xv = NULL; /* Now model has no view.  */
+    }
+  [xv->xvWindow removeFromSuperviewWithoutNeedingDisplay];
+  [xv->xvWindow release];
+}
+
+void
+nsxwidget_show_view (struct xwidget_view *xv)
+{
+  xv->hidden = NO;
+  [xv->xvWindow setFrameOrigin:NSMakePoint(xv->x + xv->clip_left,
+                                           xv->y + xv->clip_top)];
+}
+
+void
+nsxwidget_hide_view (struct xwidget_view *xv)
+{
+  xv->hidden = YES;
+  [xv->xvWindow setFrameOrigin:NSMakePoint(10000, 10000)];
+}
+
+void
+nsxwidget_resize_view (struct xwidget_view *xv, int width, int height)
+{
+  [xv->xvWindow setFrameSize:NSMakeSize(width, height)];
+}
+
+void
+nsxwidget_move_view (struct xwidget_view *xv, int x, int y)
+{
+  [xv->xvWindow setFrameOrigin:NSMakePoint (x, y)];
+}
+
+/* Move model window in container (view window).  */
+void
+nsxwidget_move_widget_in_view (struct xwidget_view *xv, int x, int y)
+{
+  struct xwidget *xww = xv->xvWindow.xw;
+  [xww->xwWindow setFrameOrigin:NSMakePoint (x, y)];
+}
+
+void
+nsxwidget_set_needsdisplay (struct xwidget_view *xv)
+{
+  xv->xvWindow.needsDisplay = YES;
+}
diff --git a/src/xwidget.c b/src/xwidget.c
index 121510ebac..d63844ad92 100644
--- a/src/xwidget.c
+++ b/src/xwidget.c
@@ -23,21 +23,31 @@ Copyright (C) 2011-2019 Free Software Foundation, Inc.
 
 #include "lisp.h"
 #include "blockinput.h"
+#include "dispextern.h"
 #include "frame.h"
 #include "keyboard.h"
 #include "gtkutil.h"
 #include "sysstdio.h"
+#include "termhooks.h"
+#include "window.h"
 
+/* Include xwidget bottom end headers.  */
+#ifdef USE_GTK
 #include <webkit2/webkit2.h>
 #include <JavaScriptCore/JavaScript.h>
+#elif defined NS_IMPL_COCOA
+#include "nsxwidget.h"
+#endif
 
 /* Suppress GCC deprecation warnings starting in WebKitGTK+ 2.21.1 for
    webkit_javascript_result_get_global_context and
    webkit_javascript_result_get_value (Bug#33679).
    FIXME: Use the JavaScriptCore GLib API instead, and remove this hack.  */
+#ifdef USE_GTK
 #if WEBKIT_CHECK_VERSION (2, 21, 1) && GNUC_PREREQ (4, 2, 0)
 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
 #endif
+#endif
 
 static struct xwidget *
 allocate_xwidget (void)
@@ -56,6 +66,7 @@ #define XSETXWIDGET_VIEW(a, b) XSETPSEUDOVECTOR (a, b, PVEC_XWIDGET_VIEW)
 
 static struct xwidget_view *xwidget_view_lookup (struct xwidget *,
 						 struct window *);
+#ifdef USE_GTK
 static void webkit_view_load_changed_cb (WebKitWebView *,
                                          WebKitLoadEvent,
                                          gpointer);
@@ -69,6 +80,7 @@ webkit_decide_policy_cb (WebKitWebView *,
                          WebKitPolicyDecision *,
                          WebKitPolicyDecisionType,
                          gpointer);
+#endif
 
 
 DEFUN ("make-xwidget",
@@ -86,8 +98,10 @@ DEFUN ("make-xwidget",
    Lisp_Object title, Lisp_Object width, Lisp_Object height,
    Lisp_Object arguments, Lisp_Object buffer)
 {
+#ifdef USE_GTK
   if (!xg_gtk_initialized)
     error ("make-xwidget: GTK has not been initialized");
+#endif
   CHECK_SYMBOL (type);
   CHECK_FIXNAT (width);
   CHECK_FIXNAT (height);
@@ -102,10 +116,11 @@ DEFUN ("make-xwidget",
   xw->kill_without_query = false;
   XSETXWIDGET (val, xw);
   Vxwidget_list = Fcons (val, Vxwidget_list);
-  xw->widgetwindow_osr = NULL;
-  xw->widget_osr = NULL;
   xw->plist = Qnil;
 
+#ifdef USE_GTK
+  xw->widgetwindow_osr = NULL;
+  xw->widget_osr = NULL;
   if (EQ (xw->type, Qwebkit))
     {
       block_input ();
@@ -160,6 +175,9 @@ DEFUN ("make-xwidget",
 
       unblock_input ();
     }
+#elif defined NS_IMPL_COCOA
+  nsxwidget_init (xw);
+#endif
 
   return val;
 }
@@ -195,6 +213,7 @@ xwidget_hidden (struct xwidget_view *xv)
   return xv->hidden;
 }
 
+#ifdef USE_GTK
 static void
 xwidget_show_view (struct xwidget_view *xv)
 {
@@ -228,13 +247,14 @@ offscreen_damage_event (GtkWidget *widget, GdkEvent *event,
   if (GTK_IS_WIDGET (xv_widget))
     gtk_widget_queue_draw (GTK_WIDGET (xv_widget));
   else
-    printf ("Warning, offscreen_damage_event received invalid xv pointer:%p\n",
-            xv_widget);
+    message ("Warning, offscreen_damage_event received invalid xv pointer:%p\n",
+             xv_widget);
 
   return FALSE;
 }
+#endif /* USE_GTK */
 
-static void
+void
 store_xwidget_event_string (struct xwidget *xw, const char *eventname,
                             const char *eventstr)
 {
@@ -248,7 +268,27 @@ store_xwidget_event_string (struct xwidget *xw, const char *eventname,
   kbd_buffer_store_event (&event);
 }
 
-static void
+void
+store_xwidget_download_callback_event (struct xwidget *xw,
+                                       const char *url,
+                                       const char *mimetype,
+                                       const char *filename)
+{
+  struct input_event event;
+  Lisp_Object xwl;
+  XSETXWIDGET (xwl, xw);
+  EVENT_INIT (event);
+  event.kind = XWIDGET_EVENT;
+  event.frame_or_window = Qnil;
+  event.arg = list5 (intern ("download-callback"),
+                     xwl,
+                     build_string (url),
+                     build_string (mimetype),
+                     build_string (filename));
+  kbd_buffer_store_event (&event);
+}
+
+void
 store_xwidget_js_callback_event (struct xwidget *xw,
                                  Lisp_Object proc,
                                  Lisp_Object argument)
@@ -264,6 +304,7 @@ store_xwidget_js_callback_event (struct xwidget *xw,
 }
 
 
+#ifdef USE_GTK
 void
 webkit_view_load_changed_cb (WebKitWebView *webkitwebview,
                              WebKitLoadEvent load_event,
@@ -521,6 +562,7 @@ xwidget_osr_event_set_embedder (GtkWidget *widget, GdkEvent *event,
                                      gtk_widget_get_window (xv->widget));
   return FALSE;
 }
+#endif /* USE_GTK */
 
 
 /* Initializes and does initial placement of an xwidget view on screen.  */
@@ -530,8 +572,10 @@ xwidget_init_view (struct xwidget *xww,
                    int x, int y)
 {
 
+#ifdef USE_GTK
   if (!xg_gtk_initialized)
     error ("xwidget_init_view: GTK has not been initialized");
+#endif
 
   struct xwidget_view *xv = allocate_xwidget_view ();
   Lisp_Object val;
@@ -542,6 +586,7 @@ xwidget_init_view (struct xwidget *xww,
   XSETWINDOW (xv->w, s->w);
   XSETXWIDGET (xv->model, xww);
 
+#ifdef USE_GTK
   if (EQ (xww->type, Qwebkit))
     {
       xv->widget = gtk_drawing_area_new ();
@@ -599,6 +644,10 @@ xwidget_init_view (struct xwidget *xww,
   xv->x = x;
   xv->y = y;
   gtk_widget_show_all (xv->widgetwindow);
+#elif defined NS_IMPL_COCOA
+  nsxwidget_init_view (xv, xww, s, x, y);
+  nsxwidget_resize_view(xv, xww->width, xww->height);
+#endif
 
   return xv;
 }
@@ -611,24 +660,59 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
      initialization.  */
   struct xwidget *xww = s->xwidget;
   struct xwidget_view *xv = xwidget_view_lookup (xww, s->w);
+  int text_area_x, text_area_y, text_area_width, text_area_height;
   int clip_right;
   int clip_bottom;
   int clip_top;
   int clip_left;
 
   int x = s->x;
-  int y = s->y + (s->height / 2) - (xww->height / 2);
+  int y = s->y;
 
   /* Do initialization here in the display loop because there is no
      other time to know things like window placement etc.  Do not
      create a new view if we have found one that is usable.  */
+#ifdef USE_GTK
   if (!xv)
     xv = xwidget_init_view (xww, s, x, y);
-
-  int text_area_x, text_area_y, text_area_width, text_area_height;
+#elif defined NS_IMPL_COCOA
+  if (!xv)
+    {
+      /* Enforce 1 to 1, model and view for macOS Cocoa webkit2.  */
+      if (xww->xv)
+        {
+          if (xwidget_hidden (xww->xv))
+            {
+              Lisp_Object xvl;
+              XSETXWIDGET_VIEW (xvl, xww->xv);
+              Fdelete_xwidget_view (xvl);
+            }
+          else
+            {
+              message ("You can't share an xwidget (webkit2) among windows.");
+              return;
+            }
+        }
+      xv = xwidget_init_view (xww, s, x, y);
+    }
+#endif
 
   window_box (s->w, TEXT_AREA, &text_area_x, &text_area_y,
               &text_area_width, &text_area_height);
+
+  /* Resize xwidget webkit if its container window size is changed in
+     some ways, for example, a buffer became hidden in small split
+     window, then it can appear front in merged whole window.  */
+  if (EQ (xww->type, Qwebkit)
+      && (xww->width != text_area_width || xww->height != text_area_height))
+    {
+      Lisp_Object xwl;
+      XSETXWIDGET (xwl, xww);
+      Fxwidget_resize (xwl,
+                       make_int (text_area_width),
+                       make_int (text_area_height));
+    }
+
   clip_left = max (0, text_area_x - x);
   clip_right = max (clip_left,
 		    min (xww->width, text_area_x + text_area_width - x));
@@ -651,8 +735,14 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
 
   /* Has it moved?  */
   if (moved)
-    gtk_fixed_move (GTK_FIXED (FRAME_GTK_WIDGET (s->f)),
-		    xv->widgetwindow, x + clip_left, y + clip_top);
+    {
+#ifdef USE_GTK
+      gtk_fixed_move (GTK_FIXED (FRAME_GTK_WIDGET (s->f)),
+                      xv->widgetwindow, x + clip_left, y + clip_top);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_move_view (xv, x + clip_left, y + clip_top);
+#endif
+    }
 
   /* Clip the widget window if some parts happen to be outside
      drawable area.  An Emacs window is not a gtk window.  A gtk window
@@ -663,10 +753,16 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
       || xv->clip_bottom != clip_bottom
       || xv->clip_top != clip_top || xv->clip_left != clip_left)
     {
+#ifdef USE_GTK
       gtk_widget_set_size_request (xv->widgetwindow, clip_right - clip_left,
                                    clip_bottom - clip_top);
       gtk_fixed_move (GTK_FIXED (xv->widgetwindow), xv->widget, -clip_left,
                       -clip_top);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_resize_view (xv, clip_right - clip_left,
+                             clip_bottom - clip_top);
+      nsxwidget_move_widget_in_view (xv, -clip_left, -clip_top);
+#endif
 
       xv->clip_right = clip_right;
       xv->clip_bottom = clip_bottom;
@@ -680,22 +776,66 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
      xwidgets background.  It's just a visual glitch though.  */
   if (!xwidget_hidden (xv))
     {
+#ifdef USE_GTK
       gtk_widget_queue_draw (xv->widgetwindow);
       gtk_widget_queue_draw (xv->widget);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_set_needsdisplay (xv);
+#endif
     }
 }
 
-/* Macro that checks WEBKIT_IS_WEB_VIEW (xw->widget_osr) first.  */
+static bool
+xwidget_is_web_view (struct xwidget *xw)
+{
+#ifdef USE_GTK
+  return xw->widget_osr != NULL && WEBKIT_IS_WEB_VIEW (xw->widget_osr);
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_is_web_view (xw);
+#endif
+}
+
+/* Macro that checks xwidget hold webkit web view first.  */
 #define WEBKIT_FN_INIT()						\
   CHECK_XWIDGET (xwidget);						\
   struct xwidget *xw = XXWIDGET (xwidget);				\
-  if (!xw->widget_osr || !WEBKIT_IS_WEB_VIEW (xw->widget_osr))		\
+  if (!xwidget_is_web_view (xw))					\
     {									\
       fputs ("ERROR xw->widget_osr does not hold a webkit instance\n",	\
 	     stdout);							\
       return Qnil;							\
     }
 
+DEFUN ("xwidget-webkit-uri",
+       Fxwidget_webkit_uri, Sxwidget_webkit_uri,
+       1, 1, 0,
+       doc: /* Get the current URL of XWIDGET webkit.  */)
+  (Lisp_Object xwidget)
+{
+  WEBKIT_FN_INIT ();
+#ifdef USE_GTK
+  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
+  return build_string (webkit_web_view_get_uri (wkwv));
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_webkit_uri (xw);
+#endif
+}
+
+DEFUN ("xwidget-webkit-title",
+       Fxwidget_webkit_title, Sxwidget_webkit_title,
+       1, 1, 0,
+       doc: /* Get the current title of XWIDGET webkit.  */)
+  (Lisp_Object xwidget)
+{
+  WEBKIT_FN_INIT ();
+#ifdef USE_GTK
+  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
+  return build_string (webkit_web_view_get_title (wkwv));
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_webkit_title (xw);
+#endif
+}
+
 DEFUN ("xwidget-webkit-goto-uri",
        Fxwidget_webkit_goto_uri, Sxwidget_webkit_goto_uri,
        2, 2, 0,
@@ -705,7 +845,32 @@ DEFUN ("xwidget-webkit-goto-uri",
   WEBKIT_FN_INIT ();
   CHECK_STRING (uri);
   uri = ENCODE_FILE (uri);
+#ifdef USE_GTK
   webkit_web_view_load_uri (WEBKIT_WEB_VIEW (xw->widget_osr), SSDATA (uri));
+#elif defined NS_IMPL_COCOA
+  nsxwidget_webkit_goto_uri (xw, SSDATA (uri));
+#endif
+  return Qnil;
+}
+
+DEFUN ("xwidget-webkit-goto-history",
+       Fxwidget_webkit_goto_history, Sxwidget_webkit_goto_history,
+       2, 2, 0,
+       doc: /* Make the XWIDGET webkit load REL-POS (-1, 0, 1) page in browse history.  */)
+  (Lisp_Object xwidget, Lisp_Object rel_pos)
+{
+  WEBKIT_FN_INIT ();
+  CHECK_RANGED_INTEGER (rel_pos, -1, 1); /* -1, 0, 1 */
+#ifdef USE_GTK
+  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
+  switch (XFIXNAT (rel_pos)) {
+  case -1: webkit_web_view_go_back (wkwv); break;
+  case 0: webkit_web_view_reload (wkwv); break;
+  case 1: webkit_web_view_go_forward (wkwv); break;
+  }
+#elif defined NS_IMPL_COCOA
+  nsxwidget_webkit_goto_history (xw, XFIXNAT (rel_pos));
+#endif
   return Qnil;
 }
 
@@ -719,14 +884,19 @@ DEFUN ("xwidget-webkit-zoom",
   if (FLOATP (factor))
     {
       double zoom_change = XFLOAT_DATA (factor);
+#ifdef USE_GTK
       webkit_web_view_set_zoom_level
         (WEBKIT_WEB_VIEW (xw->widget_osr),
          webkit_web_view_get_zoom_level
          (WEBKIT_WEB_VIEW (xw->widget_osr)) + zoom_change);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_webkit_zoom (xw, zoom_change);
+#endif
     }
   return Qnil;
 }
 
+#ifdef USE_GTK
 /* Save script and fun in the script/callback save vector and return
    its index.  */
 static ptrdiff_t
@@ -748,6 +918,7 @@ save_script_callback (struct xwidget *xw, Lisp_Object script, Lisp_Object fun)
   ASET (cbs, idx, Fcons (make_mint_ptr (xlispstrdup (script)), fun));
   return idx;
 }
+#endif
 
 DEFUN ("xwidget-webkit-execute-script",
        Fxwidget_webkit_execute_script, Sxwidget_webkit_execute_script,
@@ -759,11 +930,15 @@ DEFUN ("xwidget-webkit-execute-script",
 {
   WEBKIT_FN_INIT ();
   CHECK_STRING (script);
-  if (!NILP (fun) && !FUNCTIONP (fun))
+  /* FUN will not be garbage collected if it is defined with `defun'
+     instead of `lambda'.  If it is garbage collected even though it
+     is `defun', we can counter by pinning the FUN's symbol.  */
+  if (!NILP (fun) && !NILP (Ffboundp (fun)))
     wrong_type_argument (Qinvalid_function, fun);
 
   script = ENCODE_SYSTEM (script);
 
+#ifdef USE_GTK
   /* Protect script and fun during GC.  */
   intptr_t idx = save_script_callback (xw, script, fun);
 
@@ -777,6 +952,9 @@ DEFUN ("xwidget-webkit-execute-script",
                                   NULL, /* cancelable */
                                   webkit_javascript_finished_cb,
 				  (gpointer) idx);
+#elif defined NS_IMPL_COCOA
+  nsxwidget_webkit_execute_script (xw, SSDATA (script), fun);
+#endif
   return Qnil;
 }
 
@@ -795,6 +973,7 @@ DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
   xw->height = h;
 
   /* If there is an offscreen widget resize it first.  */
+#ifdef USE_GTK
   if (xw->widget_osr)
     {
       gtk_window_resize (GTK_WINDOW (xw->widgetwindow_osr), xw->width,
@@ -803,6 +982,9 @@ DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
       gtk_widget_set_size_request (GTK_WIDGET (xw->widget_osr), xw->width,
                                    xw->height);
     }
+#elif defined NS_IMPL_COCOA
+  nsxwidget_resize (xw);
+#endif
 
   for (Lisp_Object tail = Vxwidget_view_list; CONSP (tail); tail = XCDR (tail))
     {
@@ -810,8 +992,14 @@ DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
         {
           struct xwidget_view *xv = XXWIDGET_VIEW (XCAR (tail));
           if (XXWIDGET (xv->model) == xw)
+            {
+#ifdef USE_GTK
               gtk_widget_set_size_request (GTK_WIDGET (xv->widget), xw->width,
                                            xw->height);
+#elif defined NS_IMPL_COCOA
+              nsxwidget_resize_view(xv, xw->width, xw->height);
+#endif
+            }
         }
     }
 
@@ -830,9 +1018,13 @@ DEFUN ("xwidget-size-request",
   (Lisp_Object xwidget)
 {
   CHECK_XWIDGET (xwidget);
+#ifdef USE_GTK
   GtkRequisition requisition;
   gtk_widget_size_request (XXWIDGET (xwidget)->widget_osr, &requisition);
   return list2i (requisition.width, requisition.height);
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_get_size(XXWIDGET (xwidget));
+#endif
 }
 
 DEFUN ("xwidgetp",
@@ -909,14 +1101,19 @@ DEFUN ("delete-xwidget-view",
 {
   CHECK_XWIDGET_VIEW (xwidget_view);
   struct xwidget_view *xv = XXWIDGET_VIEW (xwidget_view);
-  gtk_widget_destroy (xv->widgetwindow);
   Vxwidget_view_list = Fdelq (xwidget_view, Vxwidget_view_list);
+#ifdef USE_GTK
+  gtk_widget_destroy (xv->widgetwindow);
   /* xv->model still has signals pointing to the view.  There can be
      several views.  Find the matching signals and delete them all.  */
   g_signal_handlers_disconnect_matched  (XXWIDGET (xv->model)->widgetwindow_osr,
                                          G_SIGNAL_MATCH_DATA,
                                          0, 0, 0, 0,
                                          xv->widget);
+#elif defined NS_IMPL_COCOA
+  nsxwidget_delete_view (xv);
+#endif
+
   return Qnil;
 }
 
@@ -1022,7 +1219,10 @@ syms_of_xwidget (void)
   defsubr (&Sxwidget_query_on_exit_flag);
   defsubr (&Sset_xwidget_query_on_exit_flag);
 
+  defsubr (&Sxwidget_webkit_uri);
+  defsubr (&Sxwidget_webkit_title);
   defsubr (&Sxwidget_webkit_goto_uri);
+  defsubr (&Sxwidget_webkit_goto_history);
   defsubr (&Sxwidget_webkit_zoom);
   defsubr (&Sxwidget_webkit_execute_script);
   DEFSYM (Qwebkit, "webkit");
@@ -1193,11 +1393,19 @@ xwidget_end_redisplay (struct window *w, struct glyph_matrix *matrix)
 		     xwidget_end_redisplay (w->current_matrix);  */
 		  struct xwidget_view *xv
 		    = xwidget_view_lookup (glyph->u.xwidget, w);
+#ifdef USE_GTK
 		  /* FIXME: Is it safe to assume xwidget_view_lookup
 		     always succeeds here?  If so, this comment can be removed.
 		     If not, the code probably needs fixing.  */
 		  eassume (xv);
 		  xwidget_touch (xv);
+#elif defined NS_IMPL_COCOA
+                  /* In NS xwidget, xv can be NULL for the second or
+                     later views for a model, the result of 1 to 1
+                     model view relation enforcement.  */
+                  if (xv)
+                    xwidget_touch (xv);
+#endif
 		}
 	  }
     }
@@ -1214,9 +1422,21 @@ xwidget_end_redisplay (struct window *w, struct glyph_matrix *matrix)
           if (XWINDOW (xv->w) == w)
             {
               if (xwidget_touched (xv))
-                xwidget_show_view (xv);
+                {
+#ifdef USE_GTK
+                  xwidget_show_view (xv);
+#elif defined NS_IMPL_COCOA
+                  nsxwidget_show_view (xv);
+#endif
+                }
               else
-                xwidget_hide_view (xv);
+                {
+#ifdef USE_GTK
+                  xwidget_hide_view (xv);
+#elif defined NS_IMPL_COCOA
+                  nsxwidget_hide_view (xv);
+#endif
+                }
             }
         }
     }
@@ -1235,6 +1455,7 @@ kill_buffer_xwidgets (Lisp_Object buffer)
       {
         CHECK_XWIDGET (xwidget);
         struct xwidget *xw = XXWIDGET (xwidget);
+#ifdef USE_GTK
         if (xw->widget_osr && xw->widgetwindow_osr)
           {
             gtk_widget_destroy (xw->widget_osr);
@@ -1248,6 +1469,9 @@ kill_buffer_xwidgets (Lisp_Object buffer)
 		xfree (xmint_pointer (XCAR (cb)));
 	      ASET (xw->script_callbacks, idx, Qnil);
 	    }
+#elif defined NS_IMPL_COCOA
+        nsxwidget_kill (xw);
+#endif
       }
     }
 }
diff --git a/src/xwidget.h b/src/xwidget.h
index 1b6368daab..11260f98b1 100644
--- a/src/xwidget.h
+++ b/src/xwidget.h
@@ -29,7 +29,13 @@ #define XWIDGET_H_INCLUDED
 struct window;
 
 #ifdef HAVE_XWIDGETS
-# include <gtk/gtk.h>
+
+#if defined (USE_GTK)
+#include <gtk/gtk.h>
+#elif defined (NS_IMPL_COCOA) && defined (__OBJC__)
+#import <AppKit/NSView.h>
+#import "nsxwidget.h"
+#endif
 
 struct xwidget
 {
@@ -54,9 +60,25 @@ #define XWIDGET_H_INCLUDED
   int height;
   int width;
 
+#if defined (USE_GTK)
   /* For offscreen widgets, unused if not osr.  */
   GtkWidget *widget_osr;
   GtkWidget *widgetwindow_osr;
+#elif defined (NS_IMPL_COCOA)
+# ifdef __OBJC__
+  /* For offscreen widgets, unused if not osr.  */
+  NSView *xwWidget;
+  XwWindow *xwWindow;
+
+  /* Used only for xwidget types (such as webkit2) enforcing 1 to 1
+     relationship between model and view.  */
+  struct xwidget_view *xv;
+# else
+  void *xwWidget;
+  void *xwWindow;
+  struct xwidget_view *xv;
+# endif
+#endif
 
   /* Kill silently if Emacs is exited.  */
   bool_bf kill_without_query : 1;
@@ -75,9 +97,20 @@ #define XWIDGET_H_INCLUDED
   /* The "live" instance isn't drawn.  */
   bool hidden;
 
+#if defined (USE_GTK)
   GtkWidget *widget;
   GtkWidget *widgetwindow;
   GtkWidget *emacswindow;
+#elif defined (NS_IMPL_COCOA)
+# ifdef __OBJC__
+  XvWindow *xvWindow;
+  NSView *emacswindow;
+# else
+  void *xvWindow;
+  void *emacswindow;
+# endif
+#endif
+
   int x;
   int y;
   int clip_right;
@@ -116,6 +149,21 @@ #define XG_XWIDGET_VIEW "emacs_xwidget_view"
 struct xwidget *lookup_xwidget (Lisp_Object spec);
 void xwidget_end_redisplay (struct window *, struct glyph_matrix *);
 void kill_buffer_xwidgets (Lisp_Object);
+#ifdef NS_IMPL_COCOA
+/* Defined in 'xwidget.c'.  */
+void store_xwidget_event_string (struct xwidget *xw,
+                                 const char *eventname,
+                                 const char *eventstr);
+
+void store_xwidget_download_callback_event (struct xwidget *xw,
+                                            const char *url,
+                                            const char *mimetype,
+                                            const char *filename);
+
+void store_xwidget_js_callback_event (struct xwidget *xw,
+                                      Lisp_Object proc,
+                                      Lisp_Object argument);
+#endif
 #else
 INLINE_HEADER_BEGIN
 INLINE void syms_of_xwidget (void) {}
-- 
2.17.2 (Apple Git-113)




^ permalink raw reply related	[flat|nested] 49+ messages in thread

* [PATCH v5] Enable xwidgets on macOS
  2019-07-18 19:23 [PATCH v4] Enable xwidgets on macOS Sungbin Jo
@ 2019-07-19  4:16 ` Sungbin Jo
  2019-07-19 19:17   ` Alan Third
  2019-07-20  8:21   ` [PATCH v5] Enable xwidgets on macOS Eli Zaretskii
  0 siblings, 2 replies; 49+ messages in thread
From: Sungbin Jo @ 2019-07-19  4:16 UTC (permalink / raw)
  To: emacs-devel; +Cc: schwab, alan, eggert, monnier, Sungbin Jo

---
 configure.ac                     |  34 +-
 lisp/xwidget.el                  | 326 +++++++++++++----
 nextstep/templates/Info.plist.in |  12 +-
 src/Makefile.in                  |   1 +
 src/emacs.c                      |   2 +-
 src/nsterm.m                     |  22 +-
 src/nsxwidget.h                  |  80 ++++
 src/nsxwidget.m                  | 611 +++++++++++++++++++++++++++++++
 src/xwidget.c                    | 255 ++++++++++++-
 src/xwidget.h                    |  50 ++-
 10 files changed, 1289 insertions(+), 104 deletions(-)
 create mode 100644 src/nsxwidget.h
 create mode 100644 src/nsxwidget.m

diff --git a/configure.ac b/configure.ac
index c093d8650d..9685b65862 100644
--- a/configure.ac
+++ b/configure.ac
@@ -484,7 +484,7 @@ AC_DEFUN
  [with_file_notification=$with_features])
 
 OPTION_DEFAULT_OFF([xwidgets],
-  [enable use of some gtk widgets in Emacs buffers (requires gtk3)])
+  [enable use of xwidgets in Emacs buffers (requires gtk3 or macOS Cocoa)])
 
 ## For the times when you want to build Emacs but don't have
 ## a suitable makeinfo, and can live without the manuals.
@@ -2808,20 +2808,34 @@ AC_DEFUN
 
 
 dnl Enable xwidgets if GTK3 and WebKitGTK+ are available.
+dnl Enable xwidgets if macOS Cocoa and WebKit framework are available.
 HAVE_XWIDGETS=no
 XWIDGETS_OBJ=
 if test "$with_xwidgets" != "no"; then
-  test "$USE_GTK_TOOLKIT" = "GTK3" && test "$window_system" != "none" ||
-    AC_MSG_ERROR([xwidgets requested but gtk3 not used.])
+  if test "$USE_GTK_TOOLKIT" = "GTK3" && test "$window_system" != "none"; then
+    WEBKIT_REQUIRED=2.12
+    WEBKIT_MODULES="webkit2gtk-4.0 >= $WEBKIT_REQUIRED"
+    EMACS_CHECK_MODULES([WEBKIT], [$WEBKIT_MODULES])
+    HAVE_XWIDGETS=$HAVE_WEBKIT
+    XWIDGETS_OBJ="xwidget.o"
+  elif test "${NS_IMPL_COCOA}" = "yes"; then
+    dnl FIXME: Check framework WebKit2
+    dnl WEBKIT_REQUIRED=M.m.p
+    WEBKIT_LIBS="-Wl,-framework -Wl,WebKit"
+    WEBKIT_CFLAGS="-I/System/Library/Frameworks/WebKit.framework/Headers"
+    HAVE_WEBKIT="yes"
+    HAVE_XWIDGETS=$HAVE_WEBKIT
+    XWIDGETS_OBJ="xwidget.o"
+    NS_OBJC_OBJ="$NS_OBJC_OBJ nsxwidget.o"
+    dnl Update NS_OBJC_OBJ with added nsxwidget.o
+    AC_SUBST(NS_OBJC_OBJ)
+  else
+    AC_MSG_ERROR([xwidgets requested, it requires GTK3 as X window toolkit or macOS Cocoa as window system.])
+  fi
 
-  WEBKIT_REQUIRED=2.12
-  WEBKIT_MODULES="webkit2gtk-4.0 >= $WEBKIT_REQUIRED"
-  EMACS_CHECK_MODULES([WEBKIT], [$WEBKIT_MODULES])
-  HAVE_XWIDGETS=$HAVE_WEBKIT
   test $HAVE_XWIDGETS = yes ||
-    AC_MSG_ERROR([xwidgets requested but WebKitGTK+ not found.])
+    AC_MSG_ERROR([xwidgets requested but WebKitGTK+ or WebKit framework not found.])
 
-  XWIDGETS_OBJ=xwidget.o
   AC_DEFINE([HAVE_XWIDGETS], 1, [Define to 1 if you have xwidgets support.])
 fi
 AC_SUBST(XWIDGETS_OBJ)
@@ -5697,7 +5711,7 @@ AC_DEFUN
   Does Emacs directly use zlib?                           ${HAVE_ZLIB}
   Does Emacs have dynamic modules support?                ${HAVE_MODULES}
   Does Emacs use toolkit scroll bars?                     ${USE_TOOLKIT_SCROLL_BARS}
-  Does Emacs support Xwidgets (requires gtk3)?            ${HAVE_XWIDGETS}
+  Does Emacs support Xwidgets?                            ${HAVE_XWIDGETS}
   Does Emacs have threading support in lisp?              ${threads_enabled}
   Does Emacs support the portable dumper?                 ${with_pdumper}
   Does Emacs support legacy unexec dumping?               ${with_unexec}
diff --git a/lisp/xwidget.el b/lisp/xwidget.el
index 662a854ac3..9b146b0202 100644
--- a/lisp/xwidget.el
+++ b/lisp/xwidget.el
@@ -39,9 +39,10 @@
 (declare-function xwidget-buffer "xwidget.c" (xwidget))
 (declare-function xwidget-size-request "xwidget.c" (xwidget))
 (declare-function xwidget-resize "xwidget.c" (xwidget new-width new-height))
-(declare-function xwidget-webkit-execute-script "xwidget.c"
-                  (xwidget script &optional callback))
+(declare-function xwidget-webkit-uri "xwidget.c" (xwidget))
+(declare-function xwidget-webkit-title "xwidget.c" (xwidget))
 (declare-function xwidget-webkit-goto-uri "xwidget.c" (xwidget uri))
+(declare-function xwidget-webkit-goto-history "xwidget.c" (xwidget rel-pos))
 (declare-function xwidget-webkit-zoom "xwidget.c" (xwidget factor))
 (declare-function xwidget-plist "xwidget.c" (xwidget))
 (declare-function set-xwidget-plist "xwidget.c" (xwidget plist))
@@ -51,6 +52,10 @@
 (declare-function get-buffer-xwidgets "xwidget.c" (buffer))
 (declare-function xwidget-query-on-exit-flag "xwidget.c" (xwidget))
 
+(defgroup xwidget nil
+  "Displaying native widgets in Emacs buffers."
+  :group 'widgets)
+
 (defun xwidget-insert (pos type title width height &optional args)
   "Insert an xwidget at position POS.
 Supply the xwidget's TYPE, TITLE, WIDTH, and HEIGHT.
@@ -78,6 +83,8 @@ xwidget-at
 ;;; webkit support
 (require 'browse-url)
 (require 'image-mode);;for some image-mode alike functionality
+(require 'seq)
+(require 'url-handlers)
 
 ;;;###autoload
 (defun xwidget-webkit-browse-url (url &optional new-session)
@@ -96,6 +103,24 @@ xwidget-webkit-browse-url
         (xwidget-webkit-new-session url)
       (xwidget-webkit-goto-url url))))
 
+(defun xwidget-webkit-split-below ()
+  "Clone current URL into a new widget place in new window below.
+Get the URL of current session, then browse to the URL
+in `split-window-below' with a new xwidget webkit session."
+  (interactive)
+  (let ((url (xwidget-webkit-current-url)))
+    (with-selected-window (split-window-below)
+      (xwidget-webkit-new-session url))))
+
+(defun xwidget-webkit-split-right ()
+  "Clone current URL into a new widget place in new window right.
+Get the URL of current session, then browse to the URL
+in `split-window-right' with a new xwidget webkit session."
+  (interactive)
+  (let ((url (xwidget-webkit-current-url)))
+    (with-selected-window (split-window-right)
+      (xwidget-webkit-new-session url))))
+
 ;;todo.
 ;; - check that the webkit support is compiled in
 (defvar xwidget-webkit-mode-map
@@ -103,34 +128,42 @@ xwidget-webkit-mode-map
     (define-key map "g" 'xwidget-webkit-browse-url)
     (define-key map "a" 'xwidget-webkit-adjust-size-dispatch)
     (define-key map "b" 'xwidget-webkit-back)
+    (define-key map "f" 'xwidget-webkit-forward)
     (define-key map "r" 'xwidget-webkit-reload)
     (define-key map "t" (lambda () (interactive) (message "o"))) ;FIXME: ?!?
     (define-key map "\C-m" 'xwidget-webkit-insert-string)
-    (define-key map "w" 'xwidget-webkit-current-url)
+    (define-key map "w" 'xwidget-webkit-current-url-message-kill)
     (define-key map "+" 'xwidget-webkit-zoom-in)
     (define-key map "-" 'xwidget-webkit-zoom-out)
 
     ;;similar to image mode bindings
     (define-key map (kbd "SPC")                 'xwidget-webkit-scroll-up)
+    (define-key map (kbd "S-SPC")               'xwidget-webkit-scroll-down)
     (define-key map (kbd "DEL")                 'xwidget-webkit-scroll-down)
 
-    (define-key map [remap scroll-up]           'xwidget-webkit-scroll-up)
+    (define-key map [remap scroll-up]           'xwidget-webkit-scroll-up-line)
     (define-key map [remap scroll-up-command]   'xwidget-webkit-scroll-up)
 
-    (define-key map [remap scroll-down]         'xwidget-webkit-scroll-down)
+    (define-key map [remap scroll-down]         'xwidget-webkit-scroll-down-line)
     (define-key map [remap scroll-down-command] 'xwidget-webkit-scroll-down)
 
     (define-key map [remap forward-char]        'xwidget-webkit-scroll-forward)
     (define-key map [remap backward-char]       'xwidget-webkit-scroll-backward)
     (define-key map [remap right-char]          'xwidget-webkit-scroll-forward)
     (define-key map [remap left-char]           'xwidget-webkit-scroll-backward)
-    (define-key map [remap previous-line]       'xwidget-webkit-scroll-down)
-    (define-key map [remap next-line]           'xwidget-webkit-scroll-up)
+    (define-key map [remap previous-line]       'xwidget-webkit-scroll-down-line)
+    (define-key map [remap next-line]           'xwidget-webkit-scroll-up-line)
 
     ;; (define-key map [remap move-beginning-of-line] 'image-bol)
     ;; (define-key map [remap move-end-of-line]       'image-eol)
     (define-key map [remap beginning-of-buffer] 'xwidget-webkit-scroll-top)
     (define-key map [remap end-of-buffer]       'xwidget-webkit-scroll-bottom)
+
+    ;; For macOS xwidget webkit, we don't support multiple views for a
+    ;; model, instead, create a new session and model behind the scene.
+    (when (memq window-system '(mac ns))
+      (define-key map [remap split-window-below] 'xwidget-webkit-split-below)
+      (define-key map [remap split-window-right] 'xwidget-webkit-split-right))
     map)
   "Keymap for `xwidget-webkit-mode'.")
 
@@ -144,33 +177,69 @@ xwidget-webkit-zoom-out
   (interactive)
   (xwidget-webkit-zoom (xwidget-webkit-current-session) -0.1))
 
-(defun xwidget-webkit-scroll-up ()
-  "Scroll webkit up."
-  (interactive)
+(defun xwidget-webkit-scroll-up (&optional n)
+  "Scroll webkit up by N pixels or window height pixels.
+Stop if the bottom edge of the page is reached.
+If N is omitted or nil, scroll up by window height pixels."
+  (interactive "P")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(0, 50);"))
-
-(defun xwidget-webkit-scroll-down ()
-  "Scroll webkit down."
-  (interactive)
+   (format "window.scrollBy(0, %d);"
+           (or n (xwidget-window-inside-pixel-height (selected-window))))))
+
+(defun xwidget-webkit-scroll-down (&optional n)
+  "Scroll webkit down by N pixels or window height pixels.
+Stop if the top edge of the page is reached.
+If N is omitted or nil, scroll down by window height pixels."
+  (interactive "P")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(0, -50);"))
-
-(defun xwidget-webkit-scroll-forward ()
-  "Scroll webkit forwards."
-  (interactive)
+   (format "window.scrollBy(0, -%d);"
+           (or n (xwidget-window-inside-pixel-height (selected-window))))))
+
+(defcustom xwidget-webkit-scroll-line-height 50
+  "Default line height in pixels to scroll xwidget webkit."
+  :type 'integer)
+
+(defcustom xwidget-webkit-scroll-char-width 10
+  "Default char height in pixels to scroll xwidget webkit."
+  :type 'integer)
+
+(defun xwidget-webkit-scroll-up-line (&optional n)
+  "Scroll webkit up by N lines.
+The height of line is `xwidget-webkit-scroll-line-height' pixels.
+Stop if the bottom edge of the page is reached.
+If N is omitted or nil, scroll up by one line."
+  (interactive "p")
+  (xwidget-webkit-scroll-up (* n xwidget-webkit-scroll-line-height)))
+
+(defun xwidget-webkit-scroll-down-line (&optional n)
+  "Scroll webkit down by N lines.
+The height of line is `xwidget-webkit-scroll-line-height' pixels.
+Stop if the top edge of the page is reached.
+If N is omitted or nil, scroll down by one line."
+  (interactive "p")
+  (xwidget-webkit-scroll-down (* n xwidget-webkit-scroll-line-height)))
+
+(defun xwidget-webkit-scroll-forward (&optional n)
+  "Scroll webkit forwards by N chars.
+The width of char is `xwidget-webkit-scroll-char-width' pixels.
+If N is ommited or nil, scroll forwards by one char."
+  (interactive "p")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(50, 0);"))
-
-(defun xwidget-webkit-scroll-backward ()
-  "Scroll webkit backwards."
-  (interactive)
+   (format "window.scrollBy(%d, 0);"
+           (* n xwidget-webkit-scroll-char-width))))
+
+(defun xwidget-webkit-scroll-backward (&optional n)
+  "Scroll webkit backwards by N chars.
+The width of char is `xwidget-webkit-scroll-char-width' pixels.
+If N is ommited or nil, scroll backwards by one char."
+  (interactive "p")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(-50, 0);"))
+   (format "window.scrollBy(-%d, 0);"
+           (* n xwidget-webkit-scroll-char-width))))
 
 (defun xwidget-webkit-scroll-top ()
   "Scroll webkit to the very top."
@@ -184,7 +253,7 @@ xwidget-webkit-scroll-bottom
   (interactive)
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollTo(pageXOffset, window.document.body.clientHeight);"))
+   "window.scrollTo(pageXOffset, window.document.body.scrollHeight);"))
 
 ;; The xwidget event needs to go into a higher level handler
 ;; since the xwidget can generate an event even if it's offscreen.
@@ -208,7 +277,6 @@ xwidget-event-handler
        ;;TODO stopped working for some reason
        )
     ;;(funcall  xwidget-callback xwidget xwidget-event-type)
-    (message "xw callback %s" xwidget)
     (funcall  'xwidget-webkit-callback xwidget xwidget-event-type)))
 
 (defun xwidget-webkit-callback (xwidget xwidget-event-type)
@@ -219,43 +287,141 @@ xwidget-webkit-callback
        "error: callback called for xwidget with dead buffer")
     (with-current-buffer (xwidget-buffer xwidget)
       (cond ((eq xwidget-event-type 'load-changed)
-             (xwidget-webkit-execute-script
-              xwidget "document.title"
-              (lambda (title)
-                (xwidget-log "webkit finished loading: '%s'" title)
-                ;;TODO - check the native/internal scroll
-                ;;(xwidget-adjust-size-to-content xwidget)
-                (xwidget-webkit-adjust-size-to-window xwidget)
-                (rename-buffer (format "*xwidget webkit: %s *" title))))
-             (pop-to-buffer (current-buffer)))
+             ;; We do not change selected window for the finish of loading a page.
+             ;; And do not adjust webkit size to window here, the selected window
+             ;; can be the mini-buffer window unwantedly.
+             (let ((title (xwidget-webkit-title xwidget)))
+               (xwidget-log "webkit finished loading: %s" title)
+               (rename-buffer (format "*xwidget webkit: %s *" title) t)))
             ((eq xwidget-event-type 'decide-policy)
              (let ((strarg  (nth 3 last-input-event)))
                (if (string-match ".*#\\(.*\\)" strarg)
                    (xwidget-webkit-show-id-or-named-element
                     xwidget
                     (match-string 1 strarg)))))
+            ;; TODO: Response handling other than download.
+            ((eq xwidget-event-type 'download-callback)
+             (let ((url  (nth 3 last-input-event))
+                   (mime-type (nth 4 last-input-event))
+                   (file-name (nth 5 last-input-event)))
+               (xwidget-webkit-save-as-file url mime-type file-name)))
             ((eq xwidget-event-type 'javascript-callback)
              (let ((proc (nth 3 last-input-event))
                    (arg  (nth 4 last-input-event)))
-               (funcall proc arg)))
+               ;; Some javascript return vector as result
+               (funcall proc (if (vectorp arg) (seq-into arg 'list) arg))))
             (t (xwidget-log "unhandled event:%s" xwidget-event-type))))))
 
 (defvar bookmark-make-record-function)
+(defvar isearch-search-fun-function)
+(when (memq window-system '(mac ns))
+  (defcustom xwidget-webkit-enable-plugins nil
+    "Enable plugins for xwidget webkit.
+If non-nil, plugins are enabled.  Otherwise, disabled."
+    :type 'boolean))
+
 (define-derived-mode xwidget-webkit-mode
     special-mode "xwidget-webkit" "Xwidget webkit view mode."
     (setq buffer-read-only t)
+    (setq cursor-type nil)
     (setq-local bookmark-make-record-function
                 #'xwidget-webkit-bookmark-make-record)
+    (setq-local isearch-search-fun-function
+                #'xwidget-webkit-search-fun-function)
+    (setq-local isearch-lazy-highlight nil)
     ;; Keep track of [vh]scroll when switching buffers
     (image-mode-setup-winprops))
 
+;;; Download, save as file.
+
+(defcustom xwidget-webkit-download-dir "~/Downloads/"
+  "Directory where download file saved."
+  :type 'string)
+
+(defun xwidget-webkit-save-as-file (url mime-type &optional file-name)
+  "For XWIDGET webkit, save URL resource of MIME-TYPE as FILE-NAME."
+  (let ((save-name (read-file-name
+                    (format "Save '%s' file as: " mime-type)
+                    xwidget-webkit-download-dir
+                    (expand-file-name
+                     file-name
+                     xwidget-webkit-download-dir))))
+    (if (file-directory-p save-name)
+        (setq save-name
+              (expand-file-name (file-name-nondirectory file-name) save-name)))
+    (setq xwidget-webkit-download-dir (file-name-directory save-name))
+    (url-copy-file url save-name t)))
+
+;;; Bookmarks integration
+
+(defcustom xwidget-webkit-bookmark-jump-new-session nil
+  "Control bookmark jump to use new session or not.
+If non-nil, it will use a new session.  Otherwise, it will use
+`xwidget-webkit-last-session'.  When you set this variable to
+nil, consider further customization with
+`xwidget-webkit-last-session-buffer'."
+  :type 'boolean)
+
 (defun xwidget-webkit-bookmark-make-record ()
   "Integrate Emacs bookmarks with the webkit xwidget."
   (nconc (bookmark-make-record-default t t)
-         `((page     . ,(xwidget-webkit-current-url))
-           (handler  . (lambda (bmk) (browse-url
-                                 (bookmark-prop-get bmk 'page)))))))
-
+         `((page . ,(xwidget-webkit-current-url))
+           (handler  . (lambda (bmk)
+                         (xwidget-webkit-browse-url
+                          (bookmark-prop-get bmk 'page)
+                          xwidget-webkit-bookmark-jump-new-session))))))
+
+;;; Search text in page
+
+;; Initialize last search text length variable when isearch starts
+(defvar xwidget-webkit-isearch-last-length 0)
+(add-hook 'isearch-mode-hook
+          (lambda ()
+            (setq xwidget-webkit-isearch-last-length 0)))
+
+;; This is minimal. Regex and incremental search will be nice
+(defvar xwidget-webkit-search-js "
+var xwSearchForward = %s;
+var xwSearchRepeat = %s;
+var xwSearchString = '%s';
+if (window.getSelection() && !window.getSelection().isCollapsed) {
+  if (xwSearchRepeat) {
+    if (xwSearchForward)
+      window.getSelection().collapseToEnd();
+    else
+      window.getSelection().collapseToStart();
+  } else {
+    if (xwSearchForward)
+      window.getSelection().collapseToStart();
+    else {
+      var sel = window.getSelection();
+      window.getSelection().collapse(sel.focusNode, sel.focusOffset + 1);
+    }
+  }
+}
+window.find(xwSearchString, false, !xwSearchForward, true, false, true);
+")
+
+(defun xwidget-webkit-search-fun-function ()
+  "Return the function which perform the search in xwidget webkit."
+  (lambda (string &optional _bound _noerror _count)
+    (let* ((current-length (length string))
+           (search-forward (if isearch-forward "true" "false"))
+           (search-repeat
+            (if (eq current-length xwidget-webkit-isearch-last-length)
+                "true"
+              "false")))
+      (setq xwidget-webkit-isearch-last-length current-length)
+      (xwidget-webkit-execute-script
+       (xwidget-webkit-current-session)
+       (format xwidget-webkit-search-js
+               search-forward
+               search-repeat
+               (regexp-quote string)))
+      ;; Unconditionally avoid 'Failing I-search ...'
+      (goto-char (if isearch-forward (point-min) (point-max))))))
+
+;;; xwidget webkit session
 
 (defvar xwidget-webkit-last-session-buffer nil)
 
@@ -303,7 +469,7 @@ xwidget-webkit-activeelement-js"
 
 "
 
-  "javascript that finds the active element."
+  "Javascript that finds the active element."
   ;; Yes it's ugly, because:
   ;; - there is apparently no way to find the active frame other than recursion
   ;; - the js "for each" construct misbehaved on the "frames" collection
@@ -313,25 +479,29 @@ xwidget-webkit-activeelement-js"
   )
 
 (defun xwidget-webkit-insert-string ()
-  "Prompt for a string and insert it in the active field in the
-current webkit widget."
+  "Insert string into the active field in the current webkit widget."
   ;; Read out the string in the field first and provide for edit.
   (interactive)
+  ;; As the prompt needs to change based on the asynchronous execution results,
+  ;; the function must handle the string itself.
   (let ((xww (xwidget-webkit-current-session)))
+
     (xwidget-webkit-execute-script
      xww
      (concat xwidget-webkit-activeelement-js "
 (function () {
   var res = findactiveelement(document);
-  return [res.value, res.type];
+  if (res)
+    return [res.value, res.type];
 })();")
      (lambda (field)
+       "Prompt a string for the FIELD and insert in the active input."
        (let ((str (pcase field
-                    (`[,val "text"]
+                    (`(,val "text")
                      (read-string "Text: " val))
-                    (`[,val "password"]
+                    (`(,val "password")
                      (read-passwd "Password: " nil val))
-                    (`[,val "textarea"]
+                    (`(,val "textarea")
                      (xwidget-webkit-begin-edit-textarea xww val)))))
          (xwidget-webkit-execute-script
           xww
@@ -444,11 +614,23 @@ xwidget-webkit-adjust-size-dispatch
   (ignore-errors
     (recenter-top-bottom)))
 
+;; Utility functions, wanted in `window.el'
+
+(defun xwidget-window-inside-pixel-width (window)
+  "Return Emacs WINDOW body width in pixel."
+  (let ((edges (window-inside-pixel-edges window)))
+    (- (nth 2 edges) (nth 0 edges))))
+
+(defun xwidget-window-inside-pixel-height (window)
+  "Return Emacs WINDOW body height in pixel."
+  (let ((edges (window-inside-pixel-edges window)))
+    (- (nth 3 edges) (nth 1 edges))))
+
 (defun xwidget-webkit-adjust-size-to-window (xwidget &optional window)
   "Adjust the size of the webkit XWIDGET to fit the WINDOW."
   (xwidget-resize xwidget
-                  (window-pixel-width window)
-                  (window-pixel-height window)))
+                  (xwidget-window-inside-pixel-width window)
+                  (xwidget-window-inside-pixel-height window)))
 
 (defun xwidget-webkit-adjust-size (w h)
   "Manually set webkit size to width W, height H."
@@ -487,10 +669,13 @@ xwidget-webkit-new-session
                                               (get-buffer-create bufname)))
     ;; The xwidget id is stored in a text property, so we need to have
     ;; at least character in this buffer.
-    (insert " ")
-    (setq xw (xwidget-insert 1 'webkit bufname
-                             (window-pixel-width)
-                             (window-pixel-height)))
+    ;; Insert invisible url, good default for next `g' to browse url.
+    (let ((start (point)))
+      (insert url)
+      (put-text-property start (+ start (length url)) 'invisible t)
+      (setq xw (xwidget-insert start 'webkit bufname
+                               (xwidget-window-inside-pixel-width (selected-window))
+                               (xwidget-window-inside-pixel-height (selected-window)))))
     (xwidget-put xw 'callback 'xwidget-webkit-callback)
     (xwidget-webkit-mode)
     (xwidget-webkit-goto-uri (xwidget-webkit-last-session) url)))
@@ -506,23 +691,27 @@ xwidget-webkit-goto-url
 (defun xwidget-webkit-back ()
   "Go back in history."
   (interactive)
-  (xwidget-webkit-execute-script (xwidget-webkit-current-session)
-                                 "history.go(-1);"))
+  (xwidget-webkit-goto-history (xwidget-webkit-current-session) -1))
+
+(defun xwidget-webkit-forward ()
+  "Go forward in history."
+  (interactive)
+  (xwidget-webkit-goto-history (xwidget-webkit-current-session) 1))
 
 (defun xwidget-webkit-reload ()
-  "Reload current url."
+  "Reload current URL."
   (interactive)
-  (xwidget-webkit-execute-script (xwidget-webkit-current-session)
-                                 "history.go(0);"))
+  (xwidget-webkit-goto-history (xwidget-webkit-current-session) 0))
 
 (defun xwidget-webkit-current-url ()
-  "Get the webkit url and place it on the kill-ring."
+  "Get the current xwidget webkit URL."
   (interactive)
-  (xwidget-webkit-execute-script
-   (xwidget-webkit-current-session)
-   "document.URL" (lambda (rv)
-                    (let ((url (kill-new (or rv ""))))
-                      (message "url: %s" url)))))
+  (xwidget-webkit-uri (xwidget-webkit-current-session)))
+
+(defun xwidget-webkit-current-url-message-kill ()
+  "Display the current xwidget webkit URL and place it on the `kill-ring'."
+  (interactive)
+  (message "URL: %s" (kill-new (or (xwidget-webkit-current-url) ""))))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 (defun xwidget-webkit-get-selection (proc)
@@ -533,10 +722,9 @@ xwidget-webkit-get-selection
    proc))
 
 (defun xwidget-webkit-copy-selection-as-kill ()
-  "Get the webkit selection and put it on the kill-ring."
+  "Get the webkit selection and put it on the `kill-ring'."
   (interactive)
-  (xwidget-webkit-get-selection (lambda (selection) (kill-new selection))))
-
+  (xwidget-webkit-get-selection #'kill-new))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;; Xwidget plist management (similar to the process plist functions)
diff --git a/nextstep/templates/Info.plist.in b/nextstep/templates/Info.plist.in
index c1e50a8409..76efe95673 100644
--- a/nextstep/templates/Info.plist.in
+++ b/nextstep/templates/Info.plist.in
@@ -675,7 +675,15 @@ along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
 	</array>
 	<key>NSAppleScriptEnabled</key>
 	<string>YES</string>
-        <key>NSAppleEventsUsageDescription</key>
-        <string>Emacs requires permission to send AppleEvents to other applications.</string>
+	<key>NSAppleEventsUsageDescription</key>
+	<string>Emacs requires permission to send AppleEvents to other applications.</string>
+	<!-- For xwidget webkit to browse remote url,
+	     but this set no restriction at all.  Consult apple's documentation
+	     for detail information about `NSApplicationDefinedMask'. -->
+	<key>NSAppTransportSecurity</key>
+	<dict>
+		<key>NSAllowsArbitraryLoads</key>
+		<true/>
+	</dict>
 </dict>
 </plist>
diff --git a/src/Makefile.in b/src/Makefile.in
index fd05a45df5..0af650244d 100644
--- a/src/Makefile.in
+++ b/src/Makefile.in
@@ -434,6 +434,7 @@ SOME_MACHINE_OBJECTS =
   xterm.o xfns.o xmenu.o xselect.o xrdb.o xsmfns.o fringe.o image.o \
   fontset.o dbusbind.o cygw32.o \
   nsterm.o nsfns.o nsmenu.o nsselect.o nsimage.o nsfont.o macfont.o \
+  nsxwidget.o \
   w32.o w32console.o w32cygwinx.o w32fns.o w32heap.o w32inevt.o w32notify.o \
   w32menu.o w32proc.o w32reg.o w32select.o w32term.o w32xfns.o \
   w16select.o widget.o xfont.o ftfont.o xftfont.o ftxfont.o gtkutil.o \
diff --git a/src/emacs.c b/src/emacs.c
index ad661a081b..7c6871f1e7 100644
--- a/src/emacs.c
+++ b/src/emacs.c
@@ -1902,7 +1902,6 @@ main (int argc, char **argv)
       syms_of_xfns ();
       syms_of_xmenu ();
       syms_of_fontset ();
-      syms_of_xwidget ();
       syms_of_xsettings ();
 #ifdef HAVE_X_SM
       syms_of_xsmfns ();
@@ -1979,6 +1978,7 @@ main (int argc, char **argv)
 #endif /* HAVE_W32NOTIFY */
 #endif /* WINDOWSNT */
 
+      syms_of_xwidget ();
       syms_of_threads ();
       syms_of_profiler ();
       syms_of_pdumper ();
diff --git a/src/nsterm.m b/src/nsterm.m
index 02331826d9..9479c40006 100644
--- a/src/nsterm.m
+++ b/src/nsterm.m
@@ -49,6 +49,7 @@ Updated by Christian Limpach (chris@nice.ch)
 #include "nsterm.h"
 #include "systime.h"
 #include "character.h"
+#include "xwidget.h"
 #include "fontset.h"
 #include "composite.h"
 #include "ccl.h"
@@ -2411,7 +2412,7 @@ so some key presses (TAB) are swallowed by the system.  */
 }
 
 static int
-ns_note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
+ns_note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y, BOOL dragging)
 /*   ------------------------------------------------------------------------
      Called by EmacsView on mouseMovement events.  Passes on
      to emacs mainstream code if we moved off of a rect of interest
@@ -2420,17 +2421,24 @@ so some key presses (TAB) are swallowed by the system.  */
 {
   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
   NSRect *r;
+  BOOL force_update = NO;
 
   // NSTRACE ("note_mouse_movement");
 
   dpyinfo->last_mouse_motion_frame = frame;
   r = &dpyinfo->last_mouse_glyph;
 
+  /* If the last rect is too large (ex, xwidget webkit), update at
+     every move, or resizing by dragging modeline or vertical split is
+     very hard to make its way.  */
+  if (dragging && (r->size.width > 32 || r->size.height > 32))
+    force_update = YES;
+
   /* Note, this doesn't get called for enter/leave, since we don't have a
      position.  Those are taken care of in the corresponding NSView methods.  */
 
-  /* Has movement gone beyond last rect we were tracking?  */
-  if (x < r->origin.x || x >= r->origin.x + r->size.width
+  /* Has movement gone beyond last rect we were tracking? */
+  if (force_update || x < r->origin.x || x >= r->origin.x + r->size.width
       || y < r->origin.y || y >= r->origin.y + r->size.height)
     {
       ns_update_begin (frame);
@@ -4182,6 +4190,10 @@ overwriting cursor (usually when cursor on a tab).  */
         }
       break;
 
+    case XWIDGET_GLYPH:
+      x_draw_xwidget_glyph_string (s);
+      break;
+
     case STRETCH_GLYPH:
       ns_dumpglyphs_stretch (s);
       break;
@@ -6835,6 +6847,7 @@ - (void)mouseMoved: (NSEvent *)e
   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
   Lisp_Object frame;
   NSPoint pt;
+  BOOL dragging;
 
   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
 
@@ -6877,7 +6890,8 @@ - (void)mouseMoved: (NSEvent *)e
       last_mouse_window = window;
     }
 
-  if (!ns_note_mouse_movement (emacsframe, pt.x, pt.y))
+  dragging = (e.type == NSEventTypeLeftMouseDragged);
+  if (!ns_note_mouse_movement (emacsframe, pt.x, pt.y, dragging))
     help_echo_string = previous_help_echo_string;
 
   XSETFRAME (frame, emacsframe);
diff --git a/src/nsxwidget.h b/src/nsxwidget.h
new file mode 100644
index 0000000000..6af5fe5a4d
--- /dev/null
+++ b/src/nsxwidget.h
@@ -0,0 +1,80 @@
+/* Header for NS Cocoa part of xwidget and webkit widget.
+
+Copyright (C) 2011-2017 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 <http://www.gnu.org/licenses/>.  */
+
+#ifndef NSXWIDGET_H_INCLUDED
+#define NSXWIDGET_H_INCLUDED
+
+/* This file can be included from non-objc files through 'xwidget.h'.  */
+#ifdef __OBJC__
+#import <AppKit/NSView.h>
+#endif
+
+#include "dispextern.h"
+#include "lisp.h"
+#include "xwidget.h"
+
+/* Functions for xwidget webkit.  */
+
+bool nsxwidget_is_web_view (struct xwidget *xw);
+Lisp_Object nsxwidget_webkit_uri (struct xwidget *xw);
+Lisp_Object nsxwidget_webkit_title (struct xwidget *xw);
+void nsxwidget_webkit_goto_uri (struct xwidget *xw, const char *uri);
+void nsxwidget_webkit_goto_history (struct xwidget *xw, int rel_pos);
+void nsxwidget_webkit_zoom (struct xwidget *xw, double zoom_change);
+void nsxwidget_webkit_execute_script (struct xwidget *xw, const char *script,
+                                      Lisp_Object fun);
+
+/* Functions for xwidget model.  */
+
+#ifdef __OBJC__
+@interface XwWindow : NSView
+@property struct xwidget *xw;
+@end
+#endif
+
+void nsxwidget_init (struct xwidget *xw);
+void nsxwidget_kill (struct xwidget *xw);
+void nsxwidget_resize (struct xwidget *xw);
+Lisp_Object nsxwidget_get_size (struct xwidget *xw);
+
+/* Functions for xwidget view.  */
+
+#ifdef __OBJC__
+@interface XvWindow : NSView
+@property struct xwidget *xw;
+@property struct xwidget_view *xv;
+@end
+#endif
+
+void nsxwidget_init_view (struct xwidget_view *xv,
+                          struct xwidget *xww,
+                          struct glyph_string *s,
+                          int x, int y);
+void nsxwidget_delete_view (struct xwidget_view *xv);
+
+void nsxwidget_show_view (struct xwidget_view *xv);
+void nsxwidget_hide_view (struct xwidget_view *xv);
+void nsxwidget_resize_view (struct xwidget_view *xv,
+                            int widget, int height);
+
+void nsxwidget_move_view (struct xwidget_view *xv, int x, int y);
+void nsxwidget_move_widget_in_view (struct xwidget_view *xv, int x, int y);
+void nsxwidget_set_needsdisplay (struct xwidget_view *xv);
+
+#endif /* NSXWIDGET_H_INCLUDED */
diff --git a/src/nsxwidget.m b/src/nsxwidget.m
new file mode 100644
index 0000000000..8d8a92d09c
--- /dev/null
+++ b/src/nsxwidget.m
@@ -0,0 +1,611 @@
+/* NS Cocoa part implementation of xwidget and webkit widget.
+
+Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2017 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 <http://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 xwiget implementation;
+   Specifically NSView level view sharing / copying is not working.
+
+   *** So only one view can be associcated 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 xwiget.  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];
+  configuration.userContentController = scriptor;
+
+  /* Enable inspect element context menu item for debugging.  */
+  [configuration.preferences setValue:@YES
+                               forKey:@"developerExtrasEnabled"];
+
+  Lisp_Object enablePlugins =
+    Fintern (build_string ("xwidget-webkit-enable-plugins"), Qnil);
+  if (!EQ (Fsymbol_value (enablePlugins), Qnil))
+    configuration.preferences.plugInsEnabled = YES;
+
+  self = [super initWithFrame:frame configuration:configuration];
+  if (self)
+    {
+      self.xw = xw;
+      self.urlScriptBlocked = [[NSMutableDictionary alloc] init];
+      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"];
+      [scriptor addUserScript:[[WKUserScript alloc]
+                                initWithSource:xwScript
+                                 injectionTime:
+                                  WKUserScriptInjectionTimeAtDocumentStart
+                                forMainFrameOnly:NO]];
+    }
+  return self;
+}
+
+#if 0
+/* Non ARC - just to check lifecycle.  */
+- (void)dealloc
+{
+  NSLog (@"XwWebView dealloc");
+  [super dealloc];
+}
+#endif
+
+- (void)webView:(WKWebView *)webView
+didFinishNavigation:(WKNavigation *)navigation
+{
+  if (EQ (Fbuffer_live_p (self.xw->buffer), Qt))
+    store_xwidget_event_string (self.xw, "load-changed", "");
+}
+
+- (void)webView:(WKWebView *)webView
+decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
+decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
+{
+  switch (navigationAction.navigationType) {
+  case WKNavigationTypeLinkActivated:
+    decisionHandler (WKNavigationActionPolicyAllow);
+    break;
+  default:
+    // decisionHandler (WKNavigationActionPolicyCancel);
+    decisionHandler (WKNavigationActionPolicyAllow);
+    break;
+  }
+}
+
+- (void)webView:(WKWebView *)webView
+decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
+decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
+{
+  if (!navigationResponse.canShowMIMEType)
+    {
+      NSString *url = navigationResponse.response.URL.absoluteString;
+      NSString *mimetype = navigationResponse.response.MIMEType;
+      NSString *filename = navigationResponse.response.suggestedFilename;
+      decisionHandler (WKNavigationResponsePolicyCancel);
+      store_xwidget_download_callback_event (self.xw,
+                                             url.UTF8String,
+                                             mimetype.UTF8String,
+                                             filename.UTF8String);
+      return;
+    }
+  decisionHandler (WKNavigationResponsePolicyAllow);
+
+  self.urlScriptBlocked[navigationResponse.response.URL] =
+    [NSNumber numberWithBool:NO];
+  if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]])
+    {
+      NSDictionary *headers =
+        ((NSHTTPURLResponse *) navigationResponse.response).allHeaderFields;
+      NSString *value = headers[@"Content-Security-Policy"];
+      if (value)
+        {
+          /* TODO: Sloppy parsing of 'Content-Security-Policy' value.  */
+          NSRange sandbox = [value rangeOfString:@"sandbox"];
+          if (sandbox.location != NSNotFound
+              && (sandbox.location == 0
+                  || [value characterAtIndex:(sandbox.location - 1)] == ' '
+                  || [value characterAtIndex:(sandbox.location - 1)] == ';'))
+            {
+              NSRange allowScripts = [value rangeOfString:@"allow-scripts"];
+              if (allowScripts.location == NSNotFound
+                  || allowScripts.location < sandbox.location)
+                self.urlScriptBlocked[navigationResponse.response.URL] =
+                  [NSNumber numberWithBool:YES];
+            }
+        }
+    }
+}
+
+/* No additional new webview or emacs window will be created
+   for <a ... target="_blank">.  */
+- (WKWebView *)webView:(WKWebView *)webView
+createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
+   forNavigationAction:(WKNavigationAction *)navigationAction
+        windowFeatures:(WKWindowFeatures *)windowFeatures
+{
+  if (!navigationAction.targetFrame.isMainFrame)
+    [webView loadRequest:navigationAction.request];
+  return nil;
+}
+
+/* Open panel for file upload.  */
+- (void)webView:(WKWebView *)webView
+runOpenPanelWithParameters:(WKOpenPanelParameters *)parameters
+initiatedByFrame:(WKFrameInfo *)frame
+completionHandler:(void (^)(NSArray<NSURL *> *URLs))completionHandler
+{
+  NSOpenPanel *openPanel = [NSOpenPanel openPanel];
+  openPanel.canChooseFiles = YES;
+  openPanel.canChooseDirectories = NO;
+  openPanel.allowsMultipleSelection = parameters.allowsMultipleSelection;
+  if ([openPanel runModal] == NSModalResponseOK)
+    completionHandler (openPanel.URLs);
+  else
+    completionHandler (nil);
+}
+
+/* By forwarding mouse events to emacs view (frame)
+   - Mouse click in webview selects the window contains the webview.
+   - Correct mouse hand/arrow/I-beam is displayed (TODO: not perfect yet).
+*/
+
+- (void)mouseDown:(NSEvent *)event
+{
+  [self.xw->xv->emacswindow mouseDown:event];
+  [super mouseDown:event];
+}
+
+- (void)mouseUp:(NSEvent *)event
+{
+  [self.xw->xv->emacswindow mouseUp:event];
+  [super mouseUp:event];
+}
+
+/* Basically we want keyboard events handled by emacs unless an input
+   element has focus.  Especially, while incremental search, we set
+   emacs as first responder to avoid focus held in an input element
+   with matching text.  */
+
+- (void)keyDown:(NSEvent *)event
+{
+  Lisp_Object var = Fintern (build_string ("isearch-mode"), Qnil);
+  Lisp_Object val = buffer_local_value (var, Fcurrent_buffer ());
+  if (!EQ (val, Qunbound) && !EQ (val, Qnil))
+    {
+      [self.window makeFirstResponder:self.xw->xv->emacswindow];
+      [self.xw->xv->emacswindow keyDown:event];
+      return;
+    }
+
+  /* Emacs handles keyboard events when javascript is blocked.  */
+  if ([self.urlScriptBlocked[self.URL] boolValue])
+    {
+      [self.xw->xv->emacswindow keyDown:event];
+      return;
+    }
+
+  [self evaluateJavaScript:@"xwHasFocus()"
+         completionHandler:^(id result, NSError *error) {
+      if (error)
+        {
+          NSLog (@"xwHasFocus: %@", error);
+          [self.xw->xv->emacswindow keyDown:event];
+        }
+      else if (result)
+        {
+          NSNumber *hasFocus = result; /* __NSCFBoolean */
+          if (!hasFocus.boolValue)
+            [self.xw->xv->emacswindow keyDown:event];
+          else
+            [super keyDown:event];
+        }
+    }];
+}
+
+- (void)interpretKeyEvents:(NSArray<NSEvent *> *)eventArray
+{
+  /* We should do nothing and do not forward (default implementation
+     if we not override here) to let emacs collect key events and ask
+     interpretKeyEvents to its superclass.  */
+}
+
+static NSString *xwScript;
++ (void)initialize
+{
+  /* Find out if an input element has focus.
+     Message to script message handler when 'C-g' key down.  */
+  if (!xwScript)
+    xwScript =
+      @"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.  */
+
+static Lisp_Object build_string_with_nsstr (NSString *nsstr);
+
+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 build_string_with_nsstr (xwWebView.URL.absoluteString);
+}
+
+Lisp_Object
+nsxwidget_webkit_title (struct xwidget *xw)
+{
+  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
+  return build_string_with_nsstr (xwWebView.title);
+}
+
+/* @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;
+  }
+}
+
+void
+nsxwidget_webkit_zoom (struct xwidget *xw, double zoom_change)
+{
+  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
+  xwWebView.magnification += zoom_change;
+  /* TODO: setMagnification:centeredAtPoint.  */
+}
+
+/* Build lisp string */
+static Lisp_Object
+build_string_with_nsstr (NSString *nsstr)
+{
+  const char *utfstr = [nsstr UTF8String];
+  NSUInteger bytes = [nsstr lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
+  return make_string (utfstr, bytes);
+}
+
+/* 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 build_string_with_nsstr ((NSString *) value);
+  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_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_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 (build_string_with_nsstr (prop_key),
+                                  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
+
+/* Xwidget model, macOS Cocoa part.  */
+
+void
+nsxwidget_init(struct xwidget *xw)
+{
+  block_input ();
+  NSRect rect = NSMakeRect (0, 0, xw->width, xw->height);
+  xw->xwWidget = [[XwWebView alloc]
+                   initWithFrame:rect
+                   configuration:[[WKWebViewConfiguration alloc] init]
+                         xwidget:xw];
+  xw->xwWindow = [[XwWindow alloc]
+                   initWithFrame:rect];
+  [xw->xwWindow addSubview:xw->xwWidget];
+  xw->xv = NULL; /* for 1 to 1 relationship of webkit2.  */
+  unblock_input ();
+}
+
+void
+nsxwidget_kill (struct xwidget *xw)
+{
+  if (xw)
+    {
+      WKUserContentController *scriptor =
+        ((XwWebView *) xw->xwWidget).configuration.userContentController;
+      [scriptor removeAllUserScripts];
+      [scriptor removeScriptMessageHandlerForName:@"keyDown"];
+      [scriptor release];
+      if (xw->xv)
+        xw->xv->model = Qnil; /* Make sure related view stale.  */
+
+      /* This stops playing audio when a xwidget-webkit buffer is
+         killed.  I could not find other solution.  */
+      nsxwidget_webkit_goto_uri (xw, "about:blank");
+
+      [((XwWebView *) xw->xwWidget).urlScriptBlocked release];
+      [xw->xwWidget removeFromSuperviewWithoutNeedingDisplay];
+      [xw->xwWidget release];
+      [xw->xwWindow removeFromSuperviewWithoutNeedingDisplay];
+      [xw->xwWindow release];
+      xw->xwWidget = nil;
+    }
+}
+
+void
+nsxwidget_resize (struct xwidget *xw)
+{
+  if (xw->xwWidget)
+    {
+      [xw->xwWindow setFrameSize:NSMakeSize(xw->width, xw->height)];
+      [xw->xwWidget setFrameSize:NSMakeSize(xw->width, xw->height)];
+    }
+}
+
+Lisp_Object
+nsxwidget_get_size (struct xwidget *xw)
+{
+  return list2i (xw->xwWidget.frame.size.width,
+                 xw->xwWidget.frame.size.height);
+}
+
+/* Xwidget view, macOS Cocoa part.  */
+
+@implementation XvWindow : NSView
+- (BOOL)isFlipped { return YES; }
+@end
+
+void
+nsxwidget_init_view (struct xwidget_view *xv,
+                     struct xwidget *xw,
+                     struct glyph_string *s,
+                     int x, int y)
+{
+  /* 'x_draw_xwidget_glyph_string' will calculate correct position and
+     size of clip to draw in emacs buffer window.  Thus, just begin at
+     origin with no crop.  */
+  xv->x = x;
+  xv->y = y;
+  xv->clip_left = 0;
+  xv->clip_right = xw->width;
+  xv->clip_top = 0;
+  xv->clip_bottom = xw->height;
+
+  xv->xvWindow = [[XvWindow alloc]
+                   initWithFrame:NSMakeRect (x, y, xw->width, xw->height)];
+  xv->xvWindow.xw = xw;
+  xv->xvWindow.xv = xv;
+
+  xw->xv = xv; /* For 1 to 1 relationship of webkit2.  */
+  [xv->xvWindow addSubview:xw->xwWindow];
+
+  xv->emacswindow = FRAME_NS_VIEW (s->f);
+  [xv->emacswindow addSubview:xv->xvWindow];
+}
+
+void
+nsxwidget_delete_view (struct xwidget_view *xv)
+{
+  if (!EQ (xv->model, Qnil))
+    {
+      struct xwidget *xw = XXWIDGET (xv->model);
+      [xw->xwWindow removeFromSuperviewWithoutNeedingDisplay];
+      xw->xv = NULL; /* Now model has no view.  */
+    }
+  [xv->xvWindow removeFromSuperviewWithoutNeedingDisplay];
+  [xv->xvWindow release];
+}
+
+void
+nsxwidget_show_view (struct xwidget_view *xv)
+{
+  xv->hidden = NO;
+  [xv->xvWindow setFrameOrigin:NSMakePoint(xv->x + xv->clip_left,
+                                           xv->y + xv->clip_top)];
+}
+
+void
+nsxwidget_hide_view (struct xwidget_view *xv)
+{
+  xv->hidden = YES;
+  [xv->xvWindow setFrameOrigin:NSMakePoint(10000, 10000)];
+}
+
+void
+nsxwidget_resize_view (struct xwidget_view *xv, int width, int height)
+{
+  [xv->xvWindow setFrameSize:NSMakeSize(width, height)];
+}
+
+void
+nsxwidget_move_view (struct xwidget_view *xv, int x, int y)
+{
+  [xv->xvWindow setFrameOrigin:NSMakePoint (x, y)];
+}
+
+/* Move model window in container (view window).  */
+void
+nsxwidget_move_widget_in_view (struct xwidget_view *xv, int x, int y)
+{
+  struct xwidget *xww = xv->xvWindow.xw;
+  [xww->xwWindow setFrameOrigin:NSMakePoint (x, y)];
+}
+
+void
+nsxwidget_set_needsdisplay (struct xwidget_view *xv)
+{
+  xv->xvWindow.needsDisplay = YES;
+}
diff --git a/src/xwidget.c b/src/xwidget.c
index 121510ebac..8e21311e03 100644
--- a/src/xwidget.c
+++ b/src/xwidget.c
@@ -23,21 +23,31 @@ Copyright (C) 2011-2019 Free Software Foundation, Inc.
 
 #include "lisp.h"
 #include "blockinput.h"
+#include "dispextern.h"
 #include "frame.h"
 #include "keyboard.h"
 #include "gtkutil.h"
 #include "sysstdio.h"
+#include "termhooks.h"
+#include "window.h"
 
+/* Include xwidget bottom end headers.  */
+#ifdef USE_GTK
 #include <webkit2/webkit2.h>
 #include <JavaScriptCore/JavaScript.h>
+#elif defined NS_IMPL_COCOA
+#include "nsxwidget.h"
+#endif
 
 /* Suppress GCC deprecation warnings starting in WebKitGTK+ 2.21.1 for
    webkit_javascript_result_get_global_context and
    webkit_javascript_result_get_value (Bug#33679).
    FIXME: Use the JavaScriptCore GLib API instead, and remove this hack.  */
+#ifdef USE_GTK
 #if WEBKIT_CHECK_VERSION (2, 21, 1) && GNUC_PREREQ (4, 2, 0)
 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
 #endif
+#endif
 
 static struct xwidget *
 allocate_xwidget (void)
@@ -56,6 +66,7 @@ #define XSETXWIDGET_VIEW(a, b) XSETPSEUDOVECTOR (a, b, PVEC_XWIDGET_VIEW)
 
 static struct xwidget_view *xwidget_view_lookup (struct xwidget *,
 						 struct window *);
+#ifdef USE_GTK
 static void webkit_view_load_changed_cb (WebKitWebView *,
                                          WebKitLoadEvent,
                                          gpointer);
@@ -69,6 +80,7 @@ webkit_decide_policy_cb (WebKitWebView *,
                          WebKitPolicyDecision *,
                          WebKitPolicyDecisionType,
                          gpointer);
+#endif
 
 
 DEFUN ("make-xwidget",
@@ -86,8 +98,10 @@ DEFUN ("make-xwidget",
    Lisp_Object title, Lisp_Object width, Lisp_Object height,
    Lisp_Object arguments, Lisp_Object buffer)
 {
+#ifdef USE_GTK
   if (!xg_gtk_initialized)
     error ("make-xwidget: GTK has not been initialized");
+#endif
   CHECK_SYMBOL (type);
   CHECK_FIXNAT (width);
   CHECK_FIXNAT (height);
@@ -102,10 +116,11 @@ DEFUN ("make-xwidget",
   xw->kill_without_query = false;
   XSETXWIDGET (val, xw);
   Vxwidget_list = Fcons (val, Vxwidget_list);
-  xw->widgetwindow_osr = NULL;
-  xw->widget_osr = NULL;
   xw->plist = Qnil;
 
+#ifdef USE_GTK
+  xw->widgetwindow_osr = NULL;
+  xw->widget_osr = NULL;
   if (EQ (xw->type, Qwebkit))
     {
       block_input ();
@@ -160,6 +175,9 @@ DEFUN ("make-xwidget",
 
       unblock_input ();
     }
+#elif defined NS_IMPL_COCOA
+  nsxwidget_init (xw);
+#endif
 
   return val;
 }
@@ -195,6 +213,7 @@ xwidget_hidden (struct xwidget_view *xv)
   return xv->hidden;
 }
 
+#ifdef USE_GTK
 static void
 xwidget_show_view (struct xwidget_view *xv)
 {
@@ -228,13 +247,14 @@ offscreen_damage_event (GtkWidget *widget, GdkEvent *event,
   if (GTK_IS_WIDGET (xv_widget))
     gtk_widget_queue_draw (GTK_WIDGET (xv_widget));
   else
-    printf ("Warning, offscreen_damage_event received invalid xv pointer:%p\n",
-            xv_widget);
+    message ("Warning, offscreen_damage_event received invalid xv pointer:%p\n",
+             xv_widget);
 
   return FALSE;
 }
+#endif /* USE_GTK */
 
-static void
+void
 store_xwidget_event_string (struct xwidget *xw, const char *eventname,
                             const char *eventstr)
 {
@@ -248,7 +268,27 @@ store_xwidget_event_string (struct xwidget *xw, const char *eventname,
   kbd_buffer_store_event (&event);
 }
 
-static void
+void
+store_xwidget_download_callback_event (struct xwidget *xw,
+                                       const char *url,
+                                       const char *mimetype,
+                                       const char *filename)
+{
+  struct input_event event;
+  Lisp_Object xwl;
+  XSETXWIDGET (xwl, xw);
+  EVENT_INIT (event);
+  event.kind = XWIDGET_EVENT;
+  event.frame_or_window = Qnil;
+  event.arg = list5 (intern ("download-callback"),
+                     xwl,
+                     build_string (url),
+                     build_string (mimetype),
+                     build_string (filename));
+  kbd_buffer_store_event (&event);
+}
+
+void
 store_xwidget_js_callback_event (struct xwidget *xw,
                                  Lisp_Object proc,
                                  Lisp_Object argument)
@@ -264,6 +304,7 @@ store_xwidget_js_callback_event (struct xwidget *xw,
 }
 
 
+#ifdef USE_GTK
 void
 webkit_view_load_changed_cb (WebKitWebView *webkitwebview,
                              WebKitLoadEvent load_event,
@@ -521,6 +562,7 @@ xwidget_osr_event_set_embedder (GtkWidget *widget, GdkEvent *event,
                                      gtk_widget_get_window (xv->widget));
   return FALSE;
 }
+#endif /* USE_GTK */
 
 
 /* Initializes and does initial placement of an xwidget view on screen.  */
@@ -530,8 +572,10 @@ xwidget_init_view (struct xwidget *xww,
                    int x, int y)
 {
 
+#ifdef USE_GTK
   if (!xg_gtk_initialized)
     error ("xwidget_init_view: GTK has not been initialized");
+#endif
 
   struct xwidget_view *xv = allocate_xwidget_view ();
   Lisp_Object val;
@@ -542,6 +586,7 @@ xwidget_init_view (struct xwidget *xww,
   XSETWINDOW (xv->w, s->w);
   XSETXWIDGET (xv->model, xww);
 
+#ifdef USE_GTK
   if (EQ (xww->type, Qwebkit))
     {
       xv->widget = gtk_drawing_area_new ();
@@ -599,6 +644,10 @@ xwidget_init_view (struct xwidget *xww,
   xv->x = x;
   xv->y = y;
   gtk_widget_show_all (xv->widgetwindow);
+#elif defined NS_IMPL_COCOA
+  nsxwidget_init_view (xv, xww, s, x, y);
+  nsxwidget_resize_view(xv, xww->width, xww->height);
+#endif
 
   return xv;
 }
@@ -611,24 +660,59 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
      initialization.  */
   struct xwidget *xww = s->xwidget;
   struct xwidget_view *xv = xwidget_view_lookup (xww, s->w);
+  int text_area_x, text_area_y, text_area_width, text_area_height;
   int clip_right;
   int clip_bottom;
   int clip_top;
   int clip_left;
 
   int x = s->x;
-  int y = s->y + (s->height / 2) - (xww->height / 2);
+  int y = s->y;
 
   /* Do initialization here in the display loop because there is no
      other time to know things like window placement etc.  Do not
      create a new view if we have found one that is usable.  */
+#ifdef USE_GTK
   if (!xv)
     xv = xwidget_init_view (xww, s, x, y);
-
-  int text_area_x, text_area_y, text_area_width, text_area_height;
+#elif defined NS_IMPL_COCOA
+  if (!xv)
+    {
+      /* Enforce 1 to 1, model and view for macOS Cocoa webkit2.  */
+      if (xww->xv)
+        {
+          if (xwidget_hidden (xww->xv))
+            {
+              Lisp_Object xvl;
+              XSETXWIDGET_VIEW (xvl, xww->xv);
+              Fdelete_xwidget_view (xvl);
+            }
+          else
+            {
+              message ("You can't share an xwidget (webkit2) among windows.");
+              return;
+            }
+        }
+      xv = xwidget_init_view (xww, s, x, y);
+    }
+#endif
 
   window_box (s->w, TEXT_AREA, &text_area_x, &text_area_y,
               &text_area_width, &text_area_height);
+
+  /* Resize xwidget webkit if its container window size is changed in
+     some ways, for example, a buffer became hidden in small split
+     window, then it can appear front in merged whole window.  */
+  if (EQ (xww->type, Qwebkit)
+      && (xww->width != text_area_width || xww->height != text_area_height))
+    {
+      Lisp_Object xwl;
+      XSETXWIDGET (xwl, xww);
+      Fxwidget_resize (xwl,
+                       make_int (text_area_width),
+                       make_int (text_area_height));
+    }
+
   clip_left = max (0, text_area_x - x);
   clip_right = max (clip_left,
 		    min (xww->width, text_area_x + text_area_width - x));
@@ -651,8 +735,14 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
 
   /* Has it moved?  */
   if (moved)
-    gtk_fixed_move (GTK_FIXED (FRAME_GTK_WIDGET (s->f)),
-		    xv->widgetwindow, x + clip_left, y + clip_top);
+    {
+#ifdef USE_GTK
+      gtk_fixed_move (GTK_FIXED (FRAME_GTK_WIDGET (s->f)),
+                      xv->widgetwindow, x + clip_left, y + clip_top);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_move_view (xv, x + clip_left, y + clip_top);
+#endif
+    }
 
   /* Clip the widget window if some parts happen to be outside
      drawable area.  An Emacs window is not a gtk window.  A gtk window
@@ -663,10 +753,16 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
       || xv->clip_bottom != clip_bottom
       || xv->clip_top != clip_top || xv->clip_left != clip_left)
     {
+#ifdef USE_GTK
       gtk_widget_set_size_request (xv->widgetwindow, clip_right - clip_left,
                                    clip_bottom - clip_top);
       gtk_fixed_move (GTK_FIXED (xv->widgetwindow), xv->widget, -clip_left,
                       -clip_top);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_resize_view (xv, clip_right - clip_left,
+                             clip_bottom - clip_top);
+      nsxwidget_move_widget_in_view (xv, -clip_left, -clip_top);
+#endif
 
       xv->clip_right = clip_right;
       xv->clip_bottom = clip_bottom;
@@ -680,22 +776,66 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
      xwidgets background.  It's just a visual glitch though.  */
   if (!xwidget_hidden (xv))
     {
+#ifdef USE_GTK
       gtk_widget_queue_draw (xv->widgetwindow);
       gtk_widget_queue_draw (xv->widget);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_set_needsdisplay (xv);
+#endif
     }
 }
 
-/* Macro that checks WEBKIT_IS_WEB_VIEW (xw->widget_osr) first.  */
+static bool
+xwidget_is_web_view (struct xwidget *xw)
+{
+#ifdef USE_GTK
+  return xw->widget_osr != NULL && WEBKIT_IS_WEB_VIEW (xw->widget_osr);
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_is_web_view (xw);
+#endif
+}
+
+/* Macro that checks xwidget hold webkit web view first.  */
 #define WEBKIT_FN_INIT()						\
   CHECK_XWIDGET (xwidget);						\
   struct xwidget *xw = XXWIDGET (xwidget);				\
-  if (!xw->widget_osr || !WEBKIT_IS_WEB_VIEW (xw->widget_osr))		\
+  if (!xwidget_is_web_view (xw))					\
     {									\
       fputs ("ERROR xw->widget_osr does not hold a webkit instance\n",	\
 	     stdout);							\
       return Qnil;							\
     }
 
+DEFUN ("xwidget-webkit-uri",
+       Fxwidget_webkit_uri, Sxwidget_webkit_uri,
+       1, 1, 0,
+       doc: /* Get the current URL of XWIDGET webkit.  */)
+  (Lisp_Object xwidget)
+{
+  WEBKIT_FN_INIT ();
+#ifdef USE_GTK
+  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
+  return build_string (webkit_web_view_get_uri (wkwv));
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_webkit_uri (xw);
+#endif
+}
+
+DEFUN ("xwidget-webkit-title",
+       Fxwidget_webkit_title, Sxwidget_webkit_title,
+       1, 1, 0,
+       doc: /* Get the current title of XWIDGET webkit.  */)
+  (Lisp_Object xwidget)
+{
+  WEBKIT_FN_INIT ();
+#ifdef USE_GTK
+  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
+  return build_string (webkit_web_view_get_title (wkwv));
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_webkit_title (xw);
+#endif
+}
+
 DEFUN ("xwidget-webkit-goto-uri",
        Fxwidget_webkit_goto_uri, Sxwidget_webkit_goto_uri,
        2, 2, 0,
@@ -705,7 +845,32 @@ DEFUN ("xwidget-webkit-goto-uri",
   WEBKIT_FN_INIT ();
   CHECK_STRING (uri);
   uri = ENCODE_FILE (uri);
+#ifdef USE_GTK
   webkit_web_view_load_uri (WEBKIT_WEB_VIEW (xw->widget_osr), SSDATA (uri));
+#elif defined NS_IMPL_COCOA
+  nsxwidget_webkit_goto_uri (xw, SSDATA (uri));
+#endif
+  return Qnil;
+}
+
+DEFUN ("xwidget-webkit-goto-history",
+       Fxwidget_webkit_goto_history, Sxwidget_webkit_goto_history,
+       2, 2, 0,
+       doc: /* Make the XWIDGET webkit load REL-POS (-1, 0, 1) page in browse history.  */)
+  (Lisp_Object xwidget, Lisp_Object rel_pos)
+{
+  WEBKIT_FN_INIT ();
+  CHECK_RANGED_INTEGER (rel_pos, -1, 1); /* -1, 0, 1 */
+#ifdef USE_GTK
+  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
+  switch (XFIXNAT (rel_pos)) {
+  case -1: webkit_web_view_go_back (wkwv); break;
+  case 0: webkit_web_view_reload (wkwv); break;
+  case 1: webkit_web_view_go_forward (wkwv); break;
+  }
+#elif defined NS_IMPL_COCOA
+  nsxwidget_webkit_goto_history (xw, XFIXNAT (rel_pos));
+#endif
   return Qnil;
 }
 
@@ -719,14 +884,19 @@ DEFUN ("xwidget-webkit-zoom",
   if (FLOATP (factor))
     {
       double zoom_change = XFLOAT_DATA (factor);
+#ifdef USE_GTK
       webkit_web_view_set_zoom_level
         (WEBKIT_WEB_VIEW (xw->widget_osr),
          webkit_web_view_get_zoom_level
          (WEBKIT_WEB_VIEW (xw->widget_osr)) + zoom_change);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_webkit_zoom (xw, zoom_change);
+#endif
     }
   return Qnil;
 }
 
+#ifdef USE_GTK
 /* Save script and fun in the script/callback save vector and return
    its index.  */
 static ptrdiff_t
@@ -748,6 +918,7 @@ save_script_callback (struct xwidget *xw, Lisp_Object script, Lisp_Object fun)
   ASET (cbs, idx, Fcons (make_mint_ptr (xlispstrdup (script)), fun));
   return idx;
 }
+#endif
 
 DEFUN ("xwidget-webkit-execute-script",
        Fxwidget_webkit_execute_script, Sxwidget_webkit_execute_script,
@@ -759,11 +930,12 @@ DEFUN ("xwidget-webkit-execute-script",
 {
   WEBKIT_FN_INIT ();
   CHECK_STRING (script);
-  if (!NILP (fun) && !FUNCTIONP (fun))
+  if (!FUNCTIONP (fun))
     wrong_type_argument (Qinvalid_function, fun);
 
   script = ENCODE_SYSTEM (script);
 
+#ifdef USE_GTK
   /* Protect script and fun during GC.  */
   intptr_t idx = save_script_callback (xw, script, fun);
 
@@ -777,6 +949,9 @@ DEFUN ("xwidget-webkit-execute-script",
                                   NULL, /* cancelable */
                                   webkit_javascript_finished_cb,
 				  (gpointer) idx);
+#elif defined NS_IMPL_COCOA
+  nsxwidget_webkit_execute_script (xw, SSDATA (script), fun);
+#endif
   return Qnil;
 }
 
@@ -795,6 +970,7 @@ DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
   xw->height = h;
 
   /* If there is an offscreen widget resize it first.  */
+#ifdef USE_GTK
   if (xw->widget_osr)
     {
       gtk_window_resize (GTK_WINDOW (xw->widgetwindow_osr), xw->width,
@@ -803,6 +979,9 @@ DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
       gtk_widget_set_size_request (GTK_WIDGET (xw->widget_osr), xw->width,
                                    xw->height);
     }
+#elif defined NS_IMPL_COCOA
+  nsxwidget_resize (xw);
+#endif
 
   for (Lisp_Object tail = Vxwidget_view_list; CONSP (tail); tail = XCDR (tail))
     {
@@ -810,8 +989,14 @@ DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
         {
           struct xwidget_view *xv = XXWIDGET_VIEW (XCAR (tail));
           if (XXWIDGET (xv->model) == xw)
+            {
+#ifdef USE_GTK
               gtk_widget_set_size_request (GTK_WIDGET (xv->widget), xw->width,
                                            xw->height);
+#elif defined NS_IMPL_COCOA
+              nsxwidget_resize_view(xv, xw->width, xw->height);
+#endif
+            }
         }
     }
 
@@ -830,9 +1015,13 @@ DEFUN ("xwidget-size-request",
   (Lisp_Object xwidget)
 {
   CHECK_XWIDGET (xwidget);
+#ifdef USE_GTK
   GtkRequisition requisition;
   gtk_widget_size_request (XXWIDGET (xwidget)->widget_osr, &requisition);
   return list2i (requisition.width, requisition.height);
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_get_size(XXWIDGET (xwidget));
+#endif
 }
 
 DEFUN ("xwidgetp",
@@ -909,14 +1098,19 @@ DEFUN ("delete-xwidget-view",
 {
   CHECK_XWIDGET_VIEW (xwidget_view);
   struct xwidget_view *xv = XXWIDGET_VIEW (xwidget_view);
-  gtk_widget_destroy (xv->widgetwindow);
   Vxwidget_view_list = Fdelq (xwidget_view, Vxwidget_view_list);
+#ifdef USE_GTK
+  gtk_widget_destroy (xv->widgetwindow);
   /* xv->model still has signals pointing to the view.  There can be
      several views.  Find the matching signals and delete them all.  */
   g_signal_handlers_disconnect_matched  (XXWIDGET (xv->model)->widgetwindow_osr,
                                          G_SIGNAL_MATCH_DATA,
                                          0, 0, 0, 0,
                                          xv->widget);
+#elif defined NS_IMPL_COCOA
+  nsxwidget_delete_view (xv);
+#endif
+
   return Qnil;
 }
 
@@ -1022,7 +1216,10 @@ syms_of_xwidget (void)
   defsubr (&Sxwidget_query_on_exit_flag);
   defsubr (&Sset_xwidget_query_on_exit_flag);
 
+  defsubr (&Sxwidget_webkit_uri);
+  defsubr (&Sxwidget_webkit_title);
   defsubr (&Sxwidget_webkit_goto_uri);
+  defsubr (&Sxwidget_webkit_goto_history);
   defsubr (&Sxwidget_webkit_zoom);
   defsubr (&Sxwidget_webkit_execute_script);
   DEFSYM (Qwebkit, "webkit");
@@ -1193,11 +1390,19 @@ xwidget_end_redisplay (struct window *w, struct glyph_matrix *matrix)
 		     xwidget_end_redisplay (w->current_matrix);  */
 		  struct xwidget_view *xv
 		    = xwidget_view_lookup (glyph->u.xwidget, w);
+#ifdef USE_GTK
 		  /* FIXME: Is it safe to assume xwidget_view_lookup
 		     always succeeds here?  If so, this comment can be removed.
 		     If not, the code probably needs fixing.  */
 		  eassume (xv);
 		  xwidget_touch (xv);
+#elif defined NS_IMPL_COCOA
+                  /* In NS xwidget, xv can be NULL for the second or
+                     later views for a model, the result of 1 to 1
+                     model view relation enforcement.  */
+                  if (xv)
+                    xwidget_touch (xv);
+#endif
 		}
 	  }
     }
@@ -1214,9 +1419,21 @@ xwidget_end_redisplay (struct window *w, struct glyph_matrix *matrix)
           if (XWINDOW (xv->w) == w)
             {
               if (xwidget_touched (xv))
-                xwidget_show_view (xv);
+                {
+#ifdef USE_GTK
+                  xwidget_show_view (xv);
+#elif defined NS_IMPL_COCOA
+                  nsxwidget_show_view (xv);
+#endif
+                }
               else
-                xwidget_hide_view (xv);
+                {
+#ifdef USE_GTK
+                  xwidget_hide_view (xv);
+#elif defined NS_IMPL_COCOA
+                  nsxwidget_hide_view (xv);
+#endif
+                }
             }
         }
     }
@@ -1235,6 +1452,7 @@ kill_buffer_xwidgets (Lisp_Object buffer)
       {
         CHECK_XWIDGET (xwidget);
         struct xwidget *xw = XXWIDGET (xwidget);
+#ifdef USE_GTK
         if (xw->widget_osr && xw->widgetwindow_osr)
           {
             gtk_widget_destroy (xw->widget_osr);
@@ -1248,6 +1466,9 @@ kill_buffer_xwidgets (Lisp_Object buffer)
 		xfree (xmint_pointer (XCAR (cb)));
 	      ASET (xw->script_callbacks, idx, Qnil);
 	    }
+#elif defined NS_IMPL_COCOA
+        nsxwidget_kill (xw);
+#endif
       }
     }
 }
diff --git a/src/xwidget.h b/src/xwidget.h
index 1b6368daab..11260f98b1 100644
--- a/src/xwidget.h
+++ b/src/xwidget.h
@@ -29,7 +29,13 @@ #define XWIDGET_H_INCLUDED
 struct window;
 
 #ifdef HAVE_XWIDGETS
-# include <gtk/gtk.h>
+
+#if defined (USE_GTK)
+#include <gtk/gtk.h>
+#elif defined (NS_IMPL_COCOA) && defined (__OBJC__)
+#import <AppKit/NSView.h>
+#import "nsxwidget.h"
+#endif
 
 struct xwidget
 {
@@ -54,9 +60,25 @@ #define XWIDGET_H_INCLUDED
   int height;
   int width;
 
+#if defined (USE_GTK)
   /* For offscreen widgets, unused if not osr.  */
   GtkWidget *widget_osr;
   GtkWidget *widgetwindow_osr;
+#elif defined (NS_IMPL_COCOA)
+# ifdef __OBJC__
+  /* For offscreen widgets, unused if not osr.  */
+  NSView *xwWidget;
+  XwWindow *xwWindow;
+
+  /* Used only for xwidget types (such as webkit2) enforcing 1 to 1
+     relationship between model and view.  */
+  struct xwidget_view *xv;
+# else
+  void *xwWidget;
+  void *xwWindow;
+  struct xwidget_view *xv;
+# endif
+#endif
 
   /* Kill silently if Emacs is exited.  */
   bool_bf kill_without_query : 1;
@@ -75,9 +97,20 @@ #define XWIDGET_H_INCLUDED
   /* The "live" instance isn't drawn.  */
   bool hidden;
 
+#if defined (USE_GTK)
   GtkWidget *widget;
   GtkWidget *widgetwindow;
   GtkWidget *emacswindow;
+#elif defined (NS_IMPL_COCOA)
+# ifdef __OBJC__
+  XvWindow *xvWindow;
+  NSView *emacswindow;
+# else
+  void *xvWindow;
+  void *emacswindow;
+# endif
+#endif
+
   int x;
   int y;
   int clip_right;
@@ -116,6 +149,21 @@ #define XG_XWIDGET_VIEW "emacs_xwidget_view"
 struct xwidget *lookup_xwidget (Lisp_Object spec);
 void xwidget_end_redisplay (struct window *, struct glyph_matrix *);
 void kill_buffer_xwidgets (Lisp_Object);
+#ifdef NS_IMPL_COCOA
+/* Defined in 'xwidget.c'.  */
+void store_xwidget_event_string (struct xwidget *xw,
+                                 const char *eventname,
+                                 const char *eventstr);
+
+void store_xwidget_download_callback_event (struct xwidget *xw,
+                                            const char *url,
+                                            const char *mimetype,
+                                            const char *filename);
+
+void store_xwidget_js_callback_event (struct xwidget *xw,
+                                      Lisp_Object proc,
+                                      Lisp_Object argument);
+#endif
 #else
 INLINE_HEADER_BEGIN
 INLINE void syms_of_xwidget (void) {}
-- 
2.17.2 (Apple Git-113)




^ permalink raw reply related	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-19  4:16 ` [PATCH v5] " Sungbin Jo
@ 2019-07-19 19:17   ` Alan Third
  2019-07-19 19:25     ` Savannah down (was: [PATCH v5] Enable xwidgets on macOS) Paul Eggert
  2019-07-20  8:21   ` [PATCH v5] Enable xwidgets on macOS Eli Zaretskii
  1 sibling, 1 reply; 49+ messages in thread
From: Alan Third @ 2019-07-19 19:17 UTC (permalink / raw)
  To: Sungbin Jo; +Cc: schwab, eggert, monnier, emacs-devel

Hi, thanks for continuing to work on this. Is there still work to be
done before we push to master?

Before that it would be helpful if you could add a commit message as
described in CONTRIBUTE. To get you started here’s what I added to a
previous patch (Savannah appears to be down):

https://github.com/emacs-mirror/emacs/commit/4f5c264a412c4187d86f5e43218d6ffb7de1bf76

although I think it should have a ‘Co-authored by:’ line for the
original author whose name escapes me just now.


> +++ b/src/nsxwidget.h
> @@ -0,0 +1,80 @@
> +/* Header for NS Cocoa part of xwidget and webkit widget.
> +
> +Copyright (C) 2011-2017 Free Software Foundation, Inc.
                 ^^^^^^^^^
I think that should just be this year as it’s a new file.

> +++ b/src/nsxwidget.m
> @@ -0,0 +1,611 @@
> +/* NS Cocoa part implementation of xwidget and webkit widget.
> +
> +Copyright (C) 1989, 1992-1994, 2005-2006, 2008-2017 Free Software
> +Foundation, Inc.

Same here.

> +#if 0
> +/* Non ARC - just to check lifecycle.  */
> +- (void)dealloc
> +{
> +  NSLog (@"XwWebView dealloc");
> +  [super dealloc];
> +}
> +#endif

Is this code just for testing and should be removed?

I don’t see anything wrong with the patch other than some unclear
English in the comments. I think we’d be best to push to master in the
hopes that people will try it out and report any bugs; nobody but me
seems to have tried the branch I created before.
-- 
Alan Third



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: Savannah down (was: [PATCH v5] Enable xwidgets on macOS)
  2019-07-19 19:17   ` Alan Third
@ 2019-07-19 19:25     ` Paul Eggert
  0 siblings, 0 replies; 49+ messages in thread
From: Paul Eggert @ 2019-07-19 19:25 UTC (permalink / raw)
  To: Alan Third, Sungbin Jo; +Cc: schwab, monnier, emacs-devel

Alan Third wrote:
> Savannah appears to be down

Yes, https://quitter.im/fsfstatus says "We're experiencing a general network 
outage. Extended downtime is expected." That was 50 minutes ago. Most likely has 
something to do with their recent IPv4-vs-IPv6 problems.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-19  4:16 ` [PATCH v5] " Sungbin Jo
  2019-07-19 19:17   ` Alan Third
@ 2019-07-20  8:21   ` Eli Zaretskii
  2019-07-23 18:36     ` 조성빈
  1 sibling, 1 reply; 49+ messages in thread
From: Eli Zaretskii @ 2019-07-20  8:21 UTC (permalink / raw)
  To: Sungbin Jo; +Cc: alan, emacs-devel

> From: Sungbin Jo <pcr910303@icloud.com>
> Date: Fri, 19 Jul 2019 13:16:54 +0900
> Cc: schwab@suse.de, alan@idiocy.org, eggert@cs.ucla.edu,
>  monnier@iro.umontreal.ca, Sungbin Jo <pcr910303@icloud.com>
> 
> ---
>  configure.ac                     |  34 +-
>  lisp/xwidget.el                  | 326 +++++++++++++----
>  nextstep/templates/Info.plist.in |  12 +-
>  src/Makefile.in                  |   1 +
>  src/emacs.c                      |   2 +-
>  src/nsterm.m                     |  22 +-
>  src/nsxwidget.h                  |  80 ++++
>  src/nsxwidget.m                  | 611 +++++++++++++++++++++++++++++++
>  src/xwidget.c                    | 255 ++++++++++++-
>  src/xwidget.h                    |  50 ++-
>  10 files changed, 1289 insertions(+), 104 deletions(-)
>  create mode 100644 src/nsxwidget.h
>  create mode 100644 src/nsxwidget.m

Thanks for working on this.

Please include the commit log message, formatted according to
ChangeLog rules (see CONTRIBUTE for the details).  Some of the
questions below are because the log message was missing, and the
rationale for some changes was therefore not stated.

Also, I see that this changeset includes changes that are unrelated to
macOS support of xwidgets; I suggest to separate these two parts, as
the other part should be considered in its effect on all platforms.

> +(defun xwidget-webkit-split-below ()
> +  "Clone current URL into a new widget place in new window below.
> +Get the URL of current session, then browse to the URL
> +in `split-window-below' with a new xwidget webkit session."

The second sentence is unclear: what do you mean by "browse to the URL
in `split-window-below'"?  How does one "browse to" something, and
what does "in" mean when `split-window-below' is a command?

> +(defun xwidget-webkit-split-right ()
> +  "Clone current URL into a new widget place in new window right.
> +Get the URL of current session, then browse to the URL
> +in `split-window-right' with a new xwidget webkit session."

Same here.

>      (define-key map (kbd "SPC")                 'xwidget-webkit-scroll-up)
> +    (define-key map (kbd "S-SPC")               'xwidget-webkit-scroll-down)

Couldn't this new binding be a nuisance if the user holds the Shift
key for some reason?

> -    (define-key map [remap scroll-up]           'xwidget-webkit-scroll-up)
> +    (define-key map [remap scroll-up]           'xwidget-webkit-scroll-up-line)
>      (define-key map [remap scroll-up-command]   'xwidget-webkit-scroll-up)
>  
> -    (define-key map [remap scroll-down]         'xwidget-webkit-scroll-down)
> +    (define-key map [remap scroll-down]         'xwidget-webkit-scroll-down-line)
[...]
> -    (define-key map [remap previous-line]       'xwidget-webkit-scroll-down)
> -    (define-key map [remap next-line]           'xwidget-webkit-scroll-up)
> +    (define-key map [remap previous-line]       'xwidget-webkit-scroll-down-line)
> +    (define-key map [remap next-line]           'xwidget-webkit-scroll-up-line)

What is the rationale for these changes?

>      (define-key map [remap scroll-down-command] 'xwidget-webkit-scroll-down)
>  
>      (define-key map [remap forward-char]        'xwidget-webkit-scroll-forward)
>      (define-key map [remap backward-char]       'xwidget-webkit-scroll-backward)
>      (define-key map [remap right-char]          'xwidget-webkit-scroll-forward)
>      (define-key map [remap left-char]           'xwidget-webkit-scroll-backward)
>  
>      ;; (define-key map [remap move-beginning-of-line] 'image-bol)
>      ;; (define-key map [remap move-end-of-line]       'image-eol)
>      (define-key map [remap beginning-of-buffer] 'xwidget-webkit-scroll-top)
>      (define-key map [remap end-of-buffer]       'xwidget-webkit-scroll-bottom)
> +    ;; For macOS xwidget webkit, we don't support multiple views for a
> +    ;; model, instead, create a new session and model behind the scene.
> +    (when (memq window-system '(mac ns))
> +      (define-key map [remap split-window-below] 'xwidget-webkit-split-below)
> +      (define-key map [remap split-window-right] 'xwidget-webkit-split-right))

It could be confusing to have the same key invoke different commands
on different platforms.  So maybe it is better to simply display a
message saying multiple views aren't supported on macOS?

> +(defun xwidget-webkit-scroll-up (&optional n)
> +  "Scroll webkit up by N pixels or window height pixels.
> +Stop if the bottom edge of the page is reached.
> +If N is omitted or nil, scroll up by window height pixels."

Suggest to rename N to ARG and reword the doc string:

     "Scroll webkit up by ARG pixels; or full window height if no ARG.
   Stop if bottom of page is reached.
   Interactively, ARG is the prefix numeric argument.
   Negative ARG scrolls down."

> +(defun xwidget-webkit-scroll-down (&optional n)
> +  "Scroll webkit down by N pixels or window height pixels.
> +Stop if the top edge of the page is reached.
> +If N is omitted or nil, scroll down by window height pixels."

Same here.

> +(defcustom xwidget-webkit-scroll-line-height 50
> +  "Default line height in pixels to scroll xwidget webkit."
> +  :type 'integer)
[...]
> +(defcustom xwidget-webkit-scroll-char-width 10
> +  "Default char height in pixels to scroll xwidget webkit."
> +  :type 'integer)

Why do we need these defaults?  Can't we use the height and the width
of the default face's font instead?

> +(defun xwidget-webkit-scroll-forward (&optional n)
> +  "Scroll webkit forwards by N chars.

I suggest to say "scroll horizontally, otherwise "by N characters"
sounds surprising.

> +(defun xwidget-webkit-scroll-backward (&optional n)
> +  "Scroll webkit backwards by N chars.

Please use "back", not "backwards".

> @@ -184,7 +253,7 @@ xwidget-webkit-scroll-bottom
>    (interactive)
>    (xwidget-webkit-execute-script
>     (xwidget-webkit-current-session)
> -   "window.scrollTo(pageXOffset, window.document.body.clientHeight);"))
> +   "window.scrollTo(pageXOffset, window.document.body.scrollHeight);"))

Why this change?

> @@ -219,43 +287,141 @@ xwidget-webkit-callback
>         "error: callback called for xwidget with dead buffer")
>      (with-current-buffer (xwidget-buffer xwidget)
>        (cond ((eq xwidget-event-type 'load-changed)
> -             (xwidget-webkit-execute-script
> -              xwidget "document.title"
> -              (lambda (title)
> -                (xwidget-log "webkit finished loading: '%s'" title)
> -                ;;TODO - check the native/internal scroll
> -                ;;(xwidget-adjust-size-to-content xwidget)
> -                (xwidget-webkit-adjust-size-to-window xwidget)
> -                (rename-buffer (format "*xwidget webkit: %s *" title))))
> -             (pop-to-buffer (current-buffer)))
> +             ;; We do not change selected window for the finish of loading a page.
> +             ;; And do not adjust webkit size to window here, the selected window
> +             ;; can be the mini-buffer window unwantedly.
> +             (let ((title (xwidget-webkit-title xwidget)))
> +               (xwidget-log "webkit finished loading: %s" title)
> +               (rename-buffer (format "*xwidget webkit: %s *" title) t)))
>              ((eq xwidget-event-type 'decide-policy)
>               (let ((strarg  (nth 3 last-input-event)))
>                 (if (string-match ".*#\\(.*\\)" strarg)
>                     (xwidget-webkit-show-id-or-named-element
>                      xwidget
>                      (match-string 1 strarg)))))
> +            ;; TODO: Response handling other than download.
> +            ((eq xwidget-event-type 'download-callback)
> +             (let ((url  (nth 3 last-input-event))
> +                   (mime-type (nth 4 last-input-event))
> +                   (file-name (nth 5 last-input-event)))
> +               (xwidget-webkit-save-as-file url mime-type file-name)))
>              ((eq xwidget-event-type 'javascript-callback)
>               (let ((proc (nth 3 last-input-event))
>                     (arg  (nth 4 last-input-event)))
> -               (funcall proc arg)))
> +               ;; Some javascript return vector as result
> +               (funcall proc (if (vectorp arg) (seq-into arg 'list) arg))))
>              (t (xwidget-log "unhandled event:%s" xwidget-event-type))))))

Can you explain the rationale for these changes?

> +(defvar isearch-search-fun-function)
> +(when (memq window-system '(mac ns))
> +  (defcustom xwidget-webkit-enable-plugins nil
> +    "Enable plugins for xwidget webkit.
> +If non-nil, plugins are enabled.  Otherwise, disabled."
> +    :type 'boolean))

I think all defcustoms here should be platform-independent.  You can
say in the doc string that the value is only used on macOS.

>  (define-derived-mode xwidget-webkit-mode
>      special-mode "xwidget-webkit" "Xwidget webkit view mode."
>      (setq buffer-read-only t)
> +    (setq cursor-type nil)

Why this change?

> +    (setq-local isearch-search-fun-function
> +                #'xwidget-webkit-search-fun-function)
> +    (setq-local isearch-lazy-highlight nil)

And these?

> +(defcustom xwidget-webkit-download-dir "~/Downloads/"
> +  "Directory where download file saved."

"Directory where download files are saved."

> +  :type 'string)

Shouldn't this be 'file instead?

Also, whenever you add or modify a defcustom, please always supply a
:version tag.

> +(defun xwidget-webkit-save-as-file (url mime-type &optional file-name)
> +  "For XWIDGET webkit, save URL resource of MIME-TYPE as FILE-NAME."

The doc string doesn't say what file name will be used if FILE-NAME is
omitted or nil.

> +  (let ((save-name (read-file-name
> +                    (format "Save '%s' file as: " mime-type)

This prompt will be confusing.  It will, for example say

  Save app/xdiff file as:

Maybe this prompt would be slightly better:

  (format "Save URL `%s' of type `%s' in file/directory: " url mime-type)

> +    (if (file-directory-p save-name)
> +        (setq save-name
> +              (expand-file-name (file-name-nondirectory file-name) save-name)))

This should be mentioned in the doc string.

> +(defcustom xwidget-webkit-bookmark-jump-new-session nil
> +  "Control bookmark jump to use new session or not.
> +If non-nil, it will use a new session.  Otherwise, it will use
> +`xwidget-webkit-last-session'.  When you set this variable to
> +nil, consider further customization with
> +`xwidget-webkit-last-session-buffer'."
> +  :type 'boolean)

The first sentence will be more informative if it said

  If non-nil, use a new xwidget webkit session after bookmark jump.

Also, a :version tag is missing.

>  (defun xwidget-webkit-bookmark-make-record ()
>    "Integrate Emacs bookmarks with the webkit xwidget."

This doc string doesn't describe what the function does.

> +;; Initialize last search text length variable when isearch starts

Please add a period at the end of this sentence.

> +(add-hook 'isearch-mode-hook
> +          (lambda ()
> +            (setq xwidget-webkit-isearch-last-length 0)))
> +
> +;; This is minimal. Regex and incremental search will be nice
                     ^^
Our convention is to have two spaces between sentences.

More generally, I wonder whether its a good idea to unconditionally
add to isearch-mode-hook just because this file was loaded.

> +(defvar xwidget-webkit-search-js "
> +var xwSearchForward = %s;
> +var xwSearchRepeat = %s;
> +var xwSearchString = '%s';
> +if (window.getSelection() && !window.getSelection().isCollapsed) {
> +  if (xwSearchRepeat) {
> +    if (xwSearchForward)
> +      window.getSelection().collapseToEnd();
> +    else
> +      window.getSelection().collapseToStart();
> +  } else {
> +    if (xwSearchForward)
> +      window.getSelection().collapseToStart();
> +    else {
> +      var sel = window.getSelection();
> +      window.getSelection().collapse(sel.focusNode, sel.focusOffset + 1);
> +    }
> +  }
> +}
> +window.find(xwSearchString, false, !xwSearchForward, true, false, true);
> +")

This defvar should have a doc string.

> +;; Utility functions, wanted in `window.el'

What do you mean by "wanted" here?

> @@ -506,23 +691,27 @@ xwidget-webkit-goto-url
>  (defun xwidget-webkit-back ()
>    "Go back in history."
>    (interactive)
> -  (xwidget-webkit-execute-script (xwidget-webkit-current-session)
> -                                 "history.go(-1);"))
> +  (xwidget-webkit-goto-history (xwidget-webkit-current-session) -1))

What is the rationale for this change?

> +(defun xwidget-webkit-forward ()
> +  "Go forward in history."

The doc string should somehow make clear that this function is about
xwidgets.  A reference to the history variable would also be nice.

>  (defun xwidget-webkit-current-url ()
> -  "Get the webkit url and place it on the kill-ring."
> +  "Get the current xwidget webkit URL."
>    (interactive)
> -  (xwidget-webkit-execute-script
> -   (xwidget-webkit-current-session)
> -   "document.URL" (lambda (rv)
> -                    (let ((url (kill-new (or rv ""))))
> -                      (message "url: %s" url)))))
> +  (xwidget-webkit-uri (xwidget-webkit-current-session)))
> +
> +(defun xwidget-webkit-current-url-message-kill ()
> +  "Display the current xwidget webkit URL and place it on the `kill-ring'."
> +  (interactive)
> +  (message "URL: %s" (kill-new (or (xwidget-webkit-current-url) ""))))

You are changing the user-visible behavior here.  Why is that a good
idea?

In any case, user-visible changes should be called out in NEWS.

> +  /* If the last rect is too large (ex, xwidget webkit), update at
> +     every move, or resizing by dragging modeline or vertical split is
> +     very hard to make its way.  */
> +  if (dragging && (r->size.width > 32 || r->size.height > 32))

Is it wise to have these values hard-coded?  What do these values
represent?

> -  /* Has movement gone beyond last rect we were tracking?  */
> -  if (x < r->origin.x || x >= r->origin.x + r->size.width
> +  /* Has movement gone beyond last rect we were tracking? */

Why did you change the comment here?

> @@ -611,24 +660,59 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
>       initialization.  */
>    struct xwidget *xww = s->xwidget;
>    struct xwidget_view *xv = xwidget_view_lookup (xww, s->w);
> +  int text_area_x, text_area_y, text_area_width, text_area_height;
>    int clip_right;
>    int clip_bottom;
>    int clip_top;
>    int clip_left;
>  
>    int x = s->x;
> -  int y = s->y + (s->height / 2) - (xww->height / 2);
> +  int y = s->y;

Why this change?

> +  /* Resize xwidget webkit if its container window size is changed in
> +     some ways, for example, a buffer became hidden in small split
> +     window, then it can appear front in merged whole window.  */
> +  if (EQ (xww->type, Qwebkit)
> +      && (xww->width != text_area_width || xww->height != text_area_height))
> +    {
> +      Lisp_Object xwl;
> +      XSETXWIDGET (xwl, xww);
> +      Fxwidget_resize (xwl,
> +                       make_int (text_area_width),
> +                       make_int (text_area_height));
> +    }

And this one?

> +DEFUN ("xwidget-webkit-uri",
> +       Fxwidget_webkit_uri, Sxwidget_webkit_uri,
> +       1, 1, 0,
> +       doc: /* Get the current URL of XWIDGET webkit.  */)
> +  (Lisp_Object xwidget)
> +{
> +  WEBKIT_FN_INIT ();
> +#ifdef USE_GTK
> +  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
> +  return build_string (webkit_web_view_get_uri (wkwv));
> +#elif defined NS_IMPL_COCOA
> +  return nsxwidget_webkit_uri (xw);
> +#endif
> +}
> +
> +DEFUN ("xwidget-webkit-title",
> +       Fxwidget_webkit_title, Sxwidget_webkit_title,
> +       1, 1, 0,
> +       doc: /* Get the current title of XWIDGET webkit.  */)
> +  (Lisp_Object xwidget)
> +{
> +  WEBKIT_FN_INIT ();
> +#ifdef USE_GTK
> +  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
> +  return build_string (webkit_web_view_get_title (wkwv));
> +#elif defined NS_IMPL_COCOA
> +  return nsxwidget_webkit_title (xw);
> +#endif

These new functions should be called out in NEWS.

> +DEFUN ("xwidget-webkit-goto-history",
> +       Fxwidget_webkit_goto_history, Sxwidget_webkit_goto_history,
> +       2, 2, 0,
> +       doc: /* Make the XWIDGET webkit load REL-POS (-1, 0, 1) page in browse history.  */)
> +  (Lisp_Object xwidget, Lisp_Object rel_pos)
> +{
> +  WEBKIT_FN_INIT ();
> +  CHECK_RANGED_INTEGER (rel_pos, -1, 1); /* -1, 0, 1 */
> +#ifdef USE_GTK
> +  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
> +  switch (XFIXNAT (rel_pos)) {
> +  case -1: webkit_web_view_go_back (wkwv); break;
> +  case 0: webkit_web_view_reload (wkwv); break;
> +  case 1: webkit_web_view_go_forward (wkwv); break;
> +  }
> +#elif defined NS_IMPL_COCOA
> +  nsxwidget_webkit_goto_history (xw, XFIXNAT (rel_pos));
> +#endif
>    return Qnil;
>  }

Likewise.

> @@ -759,11 +930,12 @@ DEFUN ("xwidget-webkit-execute-script",
>  {
>    WEBKIT_FN_INIT ();
>    CHECK_STRING (script);
> -  if (!NILP (fun) && !FUNCTIONP (fun))
> +  if (!FUNCTIONP (fun))
>      wrong_type_argument (Qinvalid_function, fun);

Why this change?

> +#elif defined NS_IMPL_COCOA
> +  return nsxwidget_get_size(XXWIDGET (xwidget));
                             ^^
Our convention is to leave one space between the name of a function
and the opening parenthesis of the argument list.

> @@ -909,14 +1098,19 @@ DEFUN ("delete-xwidget-view",
>  {
>    CHECK_XWIDGET_VIEW (xwidget_view);
>    struct xwidget_view *xv = XXWIDGET_VIEW (xwidget_view);
> -  gtk_widget_destroy (xv->widgetwindow);
>    Vxwidget_view_list = Fdelq (xwidget_view, Vxwidget_view_list);
> +#ifdef USE_GTK
> +  gtk_widget_destroy (xv->widgetwindow);

This changes the order of calls.  What is the reason for that?

Thanks again for working on this.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-20  8:21   ` [PATCH v5] Enable xwidgets on macOS Eli Zaretskii
@ 2019-07-23 18:36     ` 조성빈
  2019-07-25 18:51       ` 조성빈
  0 siblings, 1 reply; 49+ messages in thread
From: 조성빈 @ 2019-07-23 18:36 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: alan, emacs-devel



> 2019. 7. 20. 오후 5:21, Eli Zaretskii <eliz@gnu.org> 작성:
> 
>> From: Sungbin Jo <pcr910303@icloud.com>
>> Date: Fri, 19 Jul 2019 13:16:54 +0900
>> Cc: schwab@suse.de, alan@idiocy.org, eggert@cs.ucla.edu,
>> monnier@iro.umontreal.ca, Sungbin Jo <pcr910303@icloud.com>
>> 
>> ---
>> configure.ac                     |  34 +-
>> lisp/xwidget.el                  | 326 +++++++++++++----
>> nextstep/templates/Info.plist.in |  12 +-
>> src/Makefile.in                  |   1 +
>> src/emacs.c                      |   2 +-
>> src/nsterm.m                     |  22 +-
>> src/nsxwidget.h                  |  80 ++++
>> src/nsxwidget.m                  | 611 +++++++++++++++++++++++++++++++
>> src/xwidget.c                    | 255 ++++++++++++-
>> src/xwidget.h                    |  50 ++-
>> 10 files changed, 1289 insertions(+), 104 deletions(-)
>> create mode 100644 src/nsxwidget.h
>> create mode 100644 src/nsxwidget.m
> 
> Thanks for working on this.
> 
> Please include the commit log message, formatted according to
> ChangeLog rules (see CONTRIBUTE for the details).  Some of the
> questions below are because the log message was missing, and the
> rationale for some changes was therefore not stated.

Ok, I’ll include the log message when committing.

> Also, I see that this changeset includes changes that are unrelated to
> macOS support of xwidgets; I suggest to separate these two parts, as
> the other part should be considered in its effect on all platforms.

AFAIU, I should split these changes into two-or-more commits. Am I correct?

>> +(defun xwidget-webkit-split-below ()
>> +  "Clone current URL into a new widget place in new window below.
>> +Get the URL of current session, then browse to the URL
>> +in `split-window-below' with a new xwidget webkit session."
> 
> The second sentence is unclear: what do you mean by "browse to the URL
> in `split-window-below'"?  How does one "browse to" something, and
> what does "in" mean when `split-window-below' is a command?

These functions used to be binded on split-window-{below,right}.
It used to create a new xwidget webkit session as the usual split-window-{below,right}
behavior is to display the same buffer, but xwidget webkit in macOS Cocoa doesn’t support
simultaneously displaying it in the same time.
These functions’ names changes to `xwidget-webkit-clone-and-split-below' in the next patch.

>> +(defun xwidget-webkit-split-right ()
>> +  "Clone current URL into a new widget place in new window right.
>> +Get the URL of current session, then browse to the URL
>> +in `split-window-right' with a new xwidget webkit session."
> 
> Same here.
> 
>>     (define-key map (kbd "SPC")                 'xwidget-webkit-scroll-up)
>> +    (define-key map (kbd "S-SPC")               'xwidget-webkit-scroll-down)
> 
> Couldn't this new binding be a nuisance if the user holds the Shift
> key for some reason?

This binding (S-SPC) exists in at least in macOS Safari & FF.
I think if one uses SPC to scroll up the view, they will expect S-SPC to scroll down.

>> -    (define-key map [remap scroll-up]           'xwidget-webkit-scroll-up)
>> +    (define-key map [remap scroll-up]           'xwidget-webkit-scroll-up-line)
>>     (define-key map [remap scroll-up-command]   'xwidget-webkit-scroll-up)
>> 
>> -    (define-key map [remap scroll-down]         'xwidget-webkit-scroll-down)
>> +    (define-key map [remap scroll-down]         'xwidget-webkit-scroll-down-line)
> [...]
>> -    (define-key map [remap previous-line]       'xwidget-webkit-scroll-down)
>> -    (define-key map [remap next-line]           'xwidget-webkit-scroll-up)
>> +    (define-key map [remap previous-line]       'xwidget-webkit-scroll-down-line)
>> +    (define-key map [remap next-line]           'xwidget-webkit-scroll-up-line)
> 
> What is the rationale for these changes?

The functions are now configurable.
The ones without the -line postfix gets an interactive argument of pixel values.
The ones with them gets an interactive argument of line numbers, and the value of
line height in pixel is a customizable variable.

>>     (define-key map [remap scroll-down-command] 'xwidget-webkit-scroll-down)
>> 
>>     (define-key map [remap forward-char]        'xwidget-webkit-scroll-forward)
>>     (define-key map [remap backward-char]       'xwidget-webkit-scroll-backward)
>>     (define-key map [remap right-char]          'xwidget-webkit-scroll-forward)
>>     (define-key map [remap left-char]           'xwidget-webkit-scroll-backward)
>> 
>>     ;; (define-key map [remap move-beginning-of-line] 'image-bol)
>>     ;; (define-key map [remap move-end-of-line]       'image-eol)
>>     (define-key map [remap beginning-of-buffer] 'xwidget-webkit-scroll-top)
>>     (define-key map [remap end-of-buffer]       'xwidget-webkit-scroll-bottom)
>> +    ;; For macOS xwidget webkit, we don't support multiple views for a
>> +    ;; model, instead, create a new session and model behind the scene.
>> +    (when (memq window-system '(mac ns))
>> +      (define-key map [remap split-window-below] 'xwidget-webkit-split-below)
>> +      (define-key map [remap split-window-right] 'xwidget-webkit-split-right))
> 
> It could be confusing to have the same key invoke different commands
> on different platforms.  So maybe it is better to simply display a
> message saying multiple views aren't supported on macOS?

Reverted.

>> +(defun xwidget-webkit-scroll-up (&optional n)
>> +  "Scroll webkit up by N pixels or window height pixels.
>> +Stop if the bottom edge of the page is reached.
>> +If N is omitted or nil, scroll up by window height pixels."
> 
> Suggest to rename N to ARG and reword the doc string:
> 
>     "Scroll webkit up by ARG pixels; or full window height if no ARG.
>   Stop if bottom of page is reached.
>   Interactively, ARG is the prefix numeric argument.
>   Negative ARG scrolls down.”

Ok.

>> +(defun xwidget-webkit-scroll-down (&optional n)
>> +  "Scroll webkit down by N pixels or window height pixels.
>> +Stop if the top edge of the page is reached.
>> +If N is omitted or nil, scroll down by window height pixels."
> 
> Same here.

Ok.

>> +(defcustom xwidget-webkit-scroll-line-height 50
>> +  "Default line height in pixels to scroll xwidget webkit."
>> +  :type 'integer)
> [...]
>> +(defcustom xwidget-webkit-scroll-char-width 10
>> +  "Default char height in pixels to scroll xwidget webkit."
>> +  :type 'integer)
> 
> Why do we need these defaults?  Can't we use the height and the width
> of the default face's font instead?

Removed defcustom and changed related functions to use `window-font-height’ and
`window-font-width'.

>> +(defun xwidget-webkit-scroll-forward (&optional n)
>> +  "Scroll webkit forwards by N chars.
> 
> I suggest to say "scroll horizontally, otherwise "by N characters"
> sounds surprising.

Ok.

>> +(defun xwidget-webkit-scroll-backward (&optional n)
>> +  "Scroll webkit backwards by N chars.
> 
> Please use "back", not "backwards”.

Ok.

>> @@ -184,7 +253,7 @@ xwidget-webkit-scroll-bottom
>>   (interactive)
>>   (xwidget-webkit-execute-script
>>    (xwidget-webkit-current-session)
>> -   "window.scrollTo(pageXOffset, window.document.body.clientHeight);"))
>> +   "window.scrollTo(pageXOffset, window.document.body.scrollHeight);"))
> 
> Why this change?

It’s a fix to scroll to the bottom of the page.
The previous one has edge cases, e.g. when there are horizontal scroll bars.

>> @@ -219,43 +287,141 @@ xwidget-webkit-callback
>>        "error: callback called for xwidget with dead buffer")
>>     (with-current-buffer (xwidget-buffer xwidget)
>>       (cond ((eq xwidget-event-type 'load-changed)
>> -             (xwidget-webkit-execute-script
>> -              xwidget "document.title"
>> -              (lambda (title)
>> -                (xwidget-log "webkit finished loading: '%s'" title)
>> -                ;;TODO - check the native/internal scroll
>> -                ;;(xwidget-adjust-size-to-content xwidget)
>> -                (xwidget-webkit-adjust-size-to-window xwidget)
>> -                (rename-buffer (format "*xwidget webkit: %s *" title))))
>> -             (pop-to-buffer (current-buffer)))
>> +             ;; We do not change selected window for the finish of loading a page.
>> +             ;; And do not adjust webkit size to window here, the selected window
>> +             ;; can be the mini-buffer window unwantedly.
>> +             (let ((title (xwidget-webkit-title xwidget)))
>> +               (xwidget-log "webkit finished loading: %s" title)
>> +               (rename-buffer (format "*xwidget webkit: %s *" title) t)))
>>             ((eq xwidget-event-type 'decide-policy)
>>              (let ((strarg  (nth 3 last-input-event)))
>>                (if (string-match ".*#\\(.*\\)" strarg)
>>                    (xwidget-webkit-show-id-or-named-element
>>                     xwidget
>>                     (match-string 1 strarg)))))
>> +            ;; TODO: Response handling other than download.
>> +            ((eq xwidget-event-type 'download-callback)
>> +             (let ((url  (nth 3 last-input-event))
>> +                   (mime-type (nth 4 last-input-event))
>> +                   (file-name (nth 5 last-input-event)))
>> +               (xwidget-webkit-save-as-file url mime-type file-name)))
>>             ((eq xwidget-event-type 'javascript-callback)
>>              (let ((proc (nth 3 last-input-event))
>>                    (arg  (nth 4 last-input-event)))
>> -               (funcall proc arg)))
>> +               ;; Some javascript return vector as result
>> +               (funcall proc (if (vectorp arg) (seq-into arg 'list) arg))))
>>             (t (xwidget-log "unhandled event:%s" xwidget-event-type))))))
> 
> Can you explain the rationale for these changes?

Hmm… The first hunk looks like it’s using the new function `xwidget-webkit-title'.
The call to `xwidget-webkit-adjust-size-to-window' was removed as the webkit can
finish reloading at any time, and if the mini-buffer is focused at the point,
the call misplaces the xwidget buffer.

The second hunk is for handling download-callback events in xwidget. 
The event generator function is there, but it is only called in Cocoa Webkit.
It’s not implemented in the GTK one, but it wouldn’t matter running.

I reverted the third hunk and related changes.

>> +(defvar isearch-search-fun-function)
>> +(when (memq window-system '(mac ns))
>> +  (defcustom xwidget-webkit-enable-plugins nil
>> +    "Enable plugins for xwidget webkit.
>> +If non-nil, plugins are enabled.  Otherwise, disabled."
>> +    :type 'boolean))
> 
> I think all defcustoms here should be platform-independent.  You can
> say in the doc string that the value is only used on macOS.

Should I change it to a defvar? Or should I remove this variable at all?

>> (define-derived-mode xwidget-webkit-mode
>>     special-mode "xwidget-webkit" "Xwidget webkit view mode."
>>     (setq buffer-read-only t)
>> +    (setq cursor-type nil)
> 
> Why this change?
> 
>> +    (setq-local isearch-search-fun-function
>> +                #'xwidget-webkit-search-fun-function)
>> +    (setq-local isearch-lazy-highlight nil)
> 
> And these?

I vaguely remember both were because of implementing website isearch.
I remember isearch working months ago… but it doesn’t now. :-(
I reverted the related changes.
I’ll take a look at them other time.

>> +(defcustom xwidget-webkit-download-dir "~/Downloads/"
>> +  "Directory where download file saved."
> 
> "Directory where download files are saved."
> 
>> +  :type 'string)
> 
> Shouldn't this be 'file instead?

Ok.

> Also, whenever you add or modify a defcustom, please always supply a
> :version tag.

Ok.

>> +(defun xwidget-webkit-save-as-file (url mime-type &optional file-name)
>> +  "For XWIDGET webkit, save URL resource of MIME-TYPE as FILE-NAME."
> 
> The doc string doesn't say what file name will be used if FILE-NAME is
> omitted or nil.

While fixing the doc string, I found out FILE-NAME shouldn’t be an optional argument :-(
Fixed.

>> +  (let ((save-name (read-file-name
>> +                    (format "Save '%s' file as: " mime-type)
> 
> This prompt will be confusing.  It will, for example say
> 
>  Save app/xdiff file as:
> 
> Maybe this prompt would be slightly better:
> 
>  (format "Save URL `%s' of type `%s' in file/directory: " url mime-type)

Ok.

>> +    (if (file-directory-p save-name)
>> +        (setq save-name
>> +              (expand-file-name (file-name-nondirectory file-name) save-name)))
> 
> This should be mentioned in the doc string.

Ok.

>> +(defcustom xwidget-webkit-bookmark-jump-new-session nil
>> +  "Control bookmark jump to use new session or not.
>> +If non-nil, it will use a new session.  Otherwise, it will use
>> +`xwidget-webkit-last-session'.  When you set this variable to
>> +nil, consider further customization with
>> +`xwidget-webkit-last-session-buffer'."
>> +  :type 'boolean)
> 
> The first sentence will be more informative if it said
> 
>  If non-nil, use a new xwidget webkit session after bookmark jump.
> 
> Also, a :version tag is missing.

Ok.

>> (defun xwidget-webkit-bookmark-make-record ()
>>   "Integrate Emacs bookmarks with the webkit xwidget."
> 
> This doc string doesn't describe what the function does.

Ok.

>> +;; Initialize last search text length variable when isearch starts
> 
> Please add a period at the end of this sentence.
> 
>> +(add-hook 'isearch-mode-hook
>> +          (lambda ()
>> +            (setq xwidget-webkit-isearch-last-length 0)))
>> +
>> +;; This is minimal. Regex and incremental search will be nice
>                     ^^
> Our convention is to have two spaces between sentences.
> 
> More generally, I wonder whether its a good idea to unconditionally
> add to isearch-mode-hook just because this file was loaded.

Removed all isearch-related code.

>> +(defvar xwidget-webkit-search-js "
>> +var xwSearchForward = %s;
>> +var xwSearchRepeat = %s;
>> +var xwSearchString = '%s';
>> +if (window.getSelection() && !window.getSelection().isCollapsed) {
>> +  if (xwSearchRepeat) {
>> +    if (xwSearchForward)
>> +      window.getSelection().collapseToEnd();
>> +    else
>> +      window.getSelection().collapseToStart();
>> +  } else {
>> +    if (xwSearchForward)
>> +      window.getSelection().collapseToStart();
>> +    else {
>> +      var sel = window.getSelection();
>> +      window.getSelection().collapse(sel.focusNode, sel.focusOffset + 1);
>> +    }
>> +  }
>> +}
>> +window.find(xwSearchString, false, !xwSearchForward, true, false, true);
>> +")
> 
> This defvar should have a doc string.
> 
>> +;; Utility functions, wanted in `window.el'
> 
> What do you mean by "wanted” here?

Removed the mention of `window.el'.

>> @@ -506,23 +691,27 @@ xwidget-webkit-goto-url
>> (defun xwidget-webkit-back ()
>>   "Go back in history."
>>   (interactive)
>> -  (xwidget-webkit-execute-script (xwidget-webkit-current-session)
>> -                                 "history.go(-1);"))
>> +  (xwidget-webkit-goto-history (xwidget-webkit-current-session) -1))
> 
> What is the rationale for this change?

It’s using the newly defined function in C `xwidget-webkit-goto-history'.

>> +(defun xwidget-webkit-forward ()
>> +  "Go forward in history."
> 
> The doc string should somehow make clear that this function is about
> xwidgets.  A reference to the history variable would also be nice.

Changed doc string, but I’m not sure about what the history variable you’re referencing is.

>> (defun xwidget-webkit-current-url ()
>> -  "Get the webkit url and place it on the kill-ring."
>> +  "Get the current xwidget webkit URL."
>>   (interactive)
>> -  (xwidget-webkit-execute-script
>> -   (xwidget-webkit-current-session)
>> -   "document.URL" (lambda (rv)
>> -                    (let ((url (kill-new (or rv ""))))
>> -                      (message "url: %s" url)))))
>> +  (xwidget-webkit-uri (xwidget-webkit-current-session)))
>> +
>> +(defun xwidget-webkit-current-url-message-kill ()
>> +  "Display the current xwidget webkit URL and place it on the `kill-ring'."
>> +  (interactive)
>> +  (message "URL: %s" (kill-new (or (xwidget-webkit-current-url) ""))))
> 
> You are changing the user-visible behavior here.  Why is that a good
> idea?
> 
> In any case, user-visible changes should be called out in NEWS.

IMHO, the new name is more clearer.
However, I reverted to the previous behavior.

>> +  /* If the last rect is too large (ex, xwidget webkit), update at
>> +     every move, or resizing by dragging modeline or vertical split is
>> +     very hard to make its way.  */
>> +  if (dragging && (r->size.width > 32 || r->size.height > 32))
> 
> Is it wise to have these values hard-coded?  What do these values
> represent?

Sorry, I’m not sure about how these values are selected.
Looks like it’s just heuristics, but I’m not sure.

>> -  /* Has movement gone beyond last rect we were tracking?  */
>> -  if (x < r->origin.x || x >= r->origin.x + r->size.width
>> +  /* Has movement gone beyond last rect we were tracking? */
> 
> Why did you change the comment here?

Reverted.

>> @@ -611,24 +660,59 @@ when there are  (struct glyph_string *s)
>>      initialization.  */
>>   struct xwidget *xww = s->xwidget;
>>   struct xwidget_view *xv = xwidget_view_lookup (xww, s->w);
>> +  int text_area_x, text_area_y, text_area_width, text_area_height;
>>   int clip_right;
>>   int clip_bottom;
>>   int clip_top;
>>   int clip_left;
>> 
>>   int x = s->x;
>> -  int y = s->y + (s->height / 2) - (xww->height / 2);
>> +  int y = s->y;
> 
> Why this change?

I’m not sure why xwidgets should be top-aligned, it looks like it’s due to
personal preference of the original patch author.
Reverted.

>> +  /* Resize xwidget webkit if its container window size is changed in
>> +     some ways, for example, a buffer became hidden in small split
>> +     window, then it can appear front in merged whole window.  */
>> +  if (EQ (xww->type, Qwebkit)
>> +      && (xww->width != text_area_width || xww->height != text_area_height))
>> +    {
>> +      Lisp_Object xwl;
>> +      XSETXWIDGET (xwl, xww);
>> +      Fxwidget_resize (xwl,
>> +                       make_int (text_area_width),
>> +                       make_int (text_area_height));
>> +    }
> 
> And this one?

This is due to the removement of the call `xwidget-webkit-adjust-size-to-window'
explained above.

>> +DEFUN ("xwidget-webkit-uri",
>> +       Fxwidget_webkit_uri, Sxwidget_webkit_uri,
>> +       1, 1, 0,
>> +       doc: /* Get the current URL of XWIDGET webkit.  */)
>> +  (Lisp_Object xwidget)
>> +{
>> +  WEBKIT_FN_INIT ();
>> +#ifdef USE_GTK
>> +  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
>> +  return build_string (webkit_web_view_get_uri (wkwv));
>> +#elif defined NS_IMPL_COCOA
>> +  return nsxwidget_webkit_uri (xw);
>> +#endif
>> +}
>> +
>> +DEFUN ("xwidget-webkit-title",
>> +       Fxwidget_webkit_title, Sxwidget_webkit_title,
>> +       1, 1, 0,
>> +       doc: /* Get the current title of XWIDGET webkit.  */)
>> +  (Lisp_Object xwidget)
>> +{
>> +  WEBKIT_FN_INIT ();
>> +#ifdef USE_GTK
>> +  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
>> +  return build_string (webkit_web_view_get_title (wkwv));
>> +#elif defined NS_IMPL_COCOA
>> +  return nsxwidget_webkit_title (xw);
>> +#endif
> 
> These new functions should be called out in NEWS.

Ok.

>> +DEFUN ("xwidget-webkit-goto-history",
>> +       Fxwidget_webkit_goto_history, Sxwidget_webkit_goto_history,
>> +       2, 2, 0,
>> +       doc: /* Make the XWIDGET webkit load REL-POS (-1, 0, 1) page in browse history.  */)
>> +  (Lisp_Object xwidget, Lisp_Object rel_pos)
>> +{
>> +  WEBKIT_FN_INIT ();
>> +  CHECK_RANGED_INTEGER (rel_pos, -1, 1); /* -1, 0, 1 */
>> +#ifdef USE_GTK
>> +  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
>> +  switch (XFIXNAT (rel_pos)) {
>> +  case -1: webkit_web_view_go_back (wkwv); break;
>> +  case 0: webkit_web_view_reload (wkwv); break;
>> +  case 1: webkit_web_view_go_forward (wkwv); break;
>> +  }
>> +#elif defined NS_IMPL_COCOA
>> +  nsxwidget_webkit_goto_history (xw, XFIXNAT (rel_pos));
>> +#endif
>>   return Qnil;
>> }
> 
> Likewise.
> 
>> @@ -759,11 +930,12 @@ DEFUN ("xwidget-webkit-execute-script",
>> {
>>   WEBKIT_FN_INIT ();
>>   CHECK_STRING (script);
>> -  if (!NILP (fun) && !FUNCTIONP (fun))
>> +  if (!FUNCTIONP (fun))
>>     wrong_type_argument (Qinvalid_function, fun);
> 
> Why this change?

That was an mistake. Reverted.

>> +#elif defined NS_IMPL_COCOA
>> +  return nsxwidget_get_size(XXWIDGET (xwidget));
>                             ^^
> Our convention is to leave one space between the name of a function
> and the opening parenthesis of the argument list.

Fixed.

>> @@ -909,14 +1098,19 @@ DEFUN ("delete-xwidget-view",
>> {
>>   CHECK_XWIDGET_VIEW (xwidget_view);
>>   struct xwidget_view *xv = XXWIDGET_VIEW (xwidget_view);
>> -  gtk_widget_destroy (xv->widgetwindow);
>>   Vxwidget_view_list = Fdelq (xwidget_view, Vxwidget_view_list);
>> +#ifdef USE_GTK
>> +  gtk_widget_destroy (xv->widgetwindow);
> 
> This changes the order of calls.  What is the reason for that?

Reverted.

> Thanks again for working on this.




^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-23 18:36     ` 조성빈
@ 2019-07-25 18:51       ` 조성빈
  2019-07-26  5:55         ` Eli Zaretskii
                           ` (2 more replies)
  0 siblings, 3 replies; 49+ messages in thread
From: 조성빈 @ 2019-07-25 18:51 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: alan, emacs-devel

[-- Attachment #1: Type: text/plain, Size: 83 bytes --]

Hello, I have prepared three patches to apply on master.
Can anyone review these?


[-- Attachment #2: 0001-Add-xwidget-webkit-support-for-macOS.patch --]
[-- Type: application/octet-stream, Size: 54511 bytes --]

From 6d95860c506233502b8b9d59609e653085412092 Mon Sep 17 00:00:00 2001
From: Sungbin Jo <pcr910303@icloud.com>
Date: Thu, 25 Jul 2019 23:55:42 +0900
Subject: [PATCH 1/3] Add xwidget webkit support for macOS

Co-authored-by: Jaesup Kwak <veshboo@gmail.com>

* configure.ac: Allow '--with-xwidgets' for "${NS_IMPL_COCOA}".
* etc/NEWS: Mention new feature.
* etc/TODO: Remove done TODO to implement xwidget in NeXTstep port.
* lisp/xwidget.el (xwidget-webkit-clone-and-split-below)
(xwidget-webkit-clone-and-split-right): New procedures.
(xwidget-webkit-callback): Remove call to
'xwidget-webkit-adjust-size-to-window' as adjusting xwidget size is
handled in 'x_draw_xwidget_glyph_string'.
(xwidget-webkit-enable-plugins): New variable.
* nextstep/templates/Info.plist.in: Add 'NSAppTransportSecurity'.
* src/Makefile.in: Add nsxwidget.o for compilation.
* src/emacs.c (main): Move conditional call to 'syms_of_xwidget'.
* src/nsterm.m (ns_draw_glyph_string): Add case for 'XWIDGET_GLYPH'.
(note_mouse_movement mouseMoved): Make it easy to resize window by
dragging mode-line or vertical separator adjacent to large glyph.
* src/nsxwidget.h src/nsxwidget.m: Newly added files, xwidget webkit
backend for macOS Cocoa.
* src/xwidget.c (Fmake_xwidget, xwidget_init_view)
(x_draw_xwidget_glyph_string, xwidget_is_web_view)
(Fxwidget_webkit_goto_uri, Fxwidget_webkit_zoom, Fxwidget_resize)
(Fxwidget_size_request, Fdelete_xwidget_view, xwidget_end_redisplay)
(kill_buffer_xwidgets): Add macOS Cocoa specific functions and code
with 'NS_IMPL_COCOA' and guard GTK specific functions and code with
'USE_GTK'.
(x_draw_xwidget_glyph_string): Handle adjusting xwidget size.
* src/xwidget.h (xwidget, xwidget_view): Add macOS Cocoa specific
fields with 'NS_IMPL_COCOA' and guard GTK specific fields with
USE_GTK.
---
 configure.ac                     |  34 +-
 etc/NEWS                         |  12 +
 etc/TODO                         |   9 -
 lisp/xwidget.el                  |  28 +-
 nextstep/templates/Info.plist.in |  12 +-
 src/Makefile.in                  |   1 +
 src/emacs.c                      |   2 +-
 src/nsterm.m                     |  20 +-
 src/nsxwidget.h                  |  77 +++++
 src/nsxwidget.m                  | 564 +++++++++++++++++++++++++++++++
 src/xwidget.c                    | 177 +++++++++-
 src/xwidget.h                    |  45 ++-
 12 files changed, 937 insertions(+), 44 deletions(-)
 create mode 100644 src/nsxwidget.h
 create mode 100644 src/nsxwidget.m

diff --git a/configure.ac b/configure.ac
index c093d8650d..9685b65862 100644
--- a/configure.ac
+++ b/configure.ac
@@ -484,7 +484,7 @@ AC_DEFUN
  [with_file_notification=$with_features])
 
 OPTION_DEFAULT_OFF([xwidgets],
-  [enable use of some gtk widgets in Emacs buffers (requires gtk3)])
+  [enable use of xwidgets in Emacs buffers (requires gtk3 or macOS Cocoa)])
 
 ## For the times when you want to build Emacs but don't have
 ## a suitable makeinfo, and can live without the manuals.
@@ -2808,20 +2808,34 @@ AC_DEFUN
 
 
 dnl Enable xwidgets if GTK3 and WebKitGTK+ are available.
+dnl Enable xwidgets if macOS Cocoa and WebKit framework are available.
 HAVE_XWIDGETS=no
 XWIDGETS_OBJ=
 if test "$with_xwidgets" != "no"; then
-  test "$USE_GTK_TOOLKIT" = "GTK3" && test "$window_system" != "none" ||
-    AC_MSG_ERROR([xwidgets requested but gtk3 not used.])
+  if test "$USE_GTK_TOOLKIT" = "GTK3" && test "$window_system" != "none"; then
+    WEBKIT_REQUIRED=2.12
+    WEBKIT_MODULES="webkit2gtk-4.0 >= $WEBKIT_REQUIRED"
+    EMACS_CHECK_MODULES([WEBKIT], [$WEBKIT_MODULES])
+    HAVE_XWIDGETS=$HAVE_WEBKIT
+    XWIDGETS_OBJ="xwidget.o"
+  elif test "${NS_IMPL_COCOA}" = "yes"; then
+    dnl FIXME: Check framework WebKit2
+    dnl WEBKIT_REQUIRED=M.m.p
+    WEBKIT_LIBS="-Wl,-framework -Wl,WebKit"
+    WEBKIT_CFLAGS="-I/System/Library/Frameworks/WebKit.framework/Headers"
+    HAVE_WEBKIT="yes"
+    HAVE_XWIDGETS=$HAVE_WEBKIT
+    XWIDGETS_OBJ="xwidget.o"
+    NS_OBJC_OBJ="$NS_OBJC_OBJ nsxwidget.o"
+    dnl Update NS_OBJC_OBJ with added nsxwidget.o
+    AC_SUBST(NS_OBJC_OBJ)
+  else
+    AC_MSG_ERROR([xwidgets requested, it requires GTK3 as X window toolkit or macOS Cocoa as window system.])
+  fi
 
-  WEBKIT_REQUIRED=2.12
-  WEBKIT_MODULES="webkit2gtk-4.0 >= $WEBKIT_REQUIRED"
-  EMACS_CHECK_MODULES([WEBKIT], [$WEBKIT_MODULES])
-  HAVE_XWIDGETS=$HAVE_WEBKIT
   test $HAVE_XWIDGETS = yes ||
-    AC_MSG_ERROR([xwidgets requested but WebKitGTK+ not found.])
+    AC_MSG_ERROR([xwidgets requested but WebKitGTK+ or WebKit framework not found.])
 
-  XWIDGETS_OBJ=xwidget.o
   AC_DEFINE([HAVE_XWIDGETS], 1, [Define to 1 if you have xwidgets support.])
 fi
 AC_SUBST(XWIDGETS_OBJ)
@@ -5697,7 +5711,7 @@ AC_DEFUN
   Does Emacs directly use zlib?                           ${HAVE_ZLIB}
   Does Emacs have dynamic modules support?                ${HAVE_MODULES}
   Does Emacs use toolkit scroll bars?                     ${USE_TOOLKIT_SCROLL_BARS}
-  Does Emacs support Xwidgets (requires gtk3)?            ${HAVE_XWIDGETS}
+  Does Emacs support Xwidgets?                            ${HAVE_XWIDGETS}
   Does Emacs have threading support in lisp?              ${threads_enabled}
   Does Emacs support the portable dumper?                 ${with_pdumper}
   Does Emacs support legacy unexec dumping?               ${with_unexec}
diff --git a/etc/NEWS b/etc/NEWS
index 5313270411..52b49bab75 100644
--- a/etc/NEWS
+++ b/etc/NEWS
@@ -2440,6 +2440,18 @@ was able to 'set' modifiers without the knowledge of the user.
 ** On NS multicolor font display is enabled again since it is also
 implemented in Emacs on free operating systems via Cairo drawing.
 
+** On macOS, Xwidget is now supported.
+If Emacs was built with xwidget support, you can access the embedded
+webkit browser with 'M-x xwidget-webkit-browse-url'.  Viewing two
+instances of xwidget webkit is not supported.
+
+*** New functions for xwidget-webkit mode
+'xwidget-webkit-clone-and-split-below',
+'xwidget-webkit-clone-and-split-right'.
+
+*** New variable 'xwidget-webkit-enable-plugins'.
+
+
 \f
 ----------------------------------------------------------------------
 This file is part of GNU Emacs.
diff --git a/etc/TODO b/etc/TODO
index a065763933..bda1cf8f9e 100644
--- a/etc/TODO
+++ b/etc/TODO
@@ -640,15 +640,6 @@ from the emacsclient process.
 
 This sections contains features found in other official Emacs ports.
 
-**** Support for xwidgets
-
-Emacs 25 has support for xwidgets, a system to include operating
-system components into an Emacs buffer.  The components range from
-simple buttons to webkit (effectively, a web browser).
-
-Currently, xwidgets works only for the gtk+ framework but it is
-designed to be compatible with multiple Emacs ports.
-
 **** Respect 'frame-inhibit-implied-resize'
 
 When the variable 'frame-inhibit-implied-resize' is non-nil, frames
diff --git a/lisp/xwidget.el b/lisp/xwidget.el
index 662a854ac3..f01822c792 100644
--- a/lisp/xwidget.el
+++ b/lisp/xwidget.el
@@ -96,6 +96,24 @@ xwidget-webkit-browse-url
         (xwidget-webkit-new-session url)
       (xwidget-webkit-goto-url url))))
 
+(defun xwidget-webkit-clone-and-split-below ()
+  "Clone current URL into a new widget place in new window below.
+Get the URL of current session, then browse to the URL
+in `split-window-below' with a new xwidget webkit session."
+  (interactive)
+  (let ((url (xwidget-webkit-current-url)))
+    (with-selected-window (split-window-below)
+      (xwidget-webkit-new-session url))))
+
+(defun xwidget-webkit-clone-and-split-right ()
+  "Clone current URL into a new widget place in new window right.
+Get the URL of current session, then browse to the URL
+in `split-window-right' with a new xwidget webkit session."
+  (interactive)
+  (let ((url (xwidget-webkit-current-url)))
+    (with-selected-window (split-window-right)
+      (xwidget-webkit-new-session url))))
+
 ;;todo.
 ;; - check that the webkit support is compiled in
 (defvar xwidget-webkit-mode-map
@@ -223,9 +241,8 @@ xwidget-webkit-callback
               xwidget "document.title"
               (lambda (title)
                 (xwidget-log "webkit finished loading: '%s'" title)
-                ;;TODO - check the native/internal scroll
-                ;;(xwidget-adjust-size-to-content xwidget)
-                (xwidget-webkit-adjust-size-to-window xwidget)
+                ;; Do not adjust webkit size to window here, the selected window
+                ;; can be the mini-buffer window unwantedly.
                 (rename-buffer (format "*xwidget webkit: %s *" title))))
              (pop-to-buffer (current-buffer)))
             ((eq xwidget-event-type 'decide-policy)
@@ -241,6 +258,11 @@ xwidget-webkit-callback
             (t (xwidget-log "unhandled event:%s" xwidget-event-type))))))
 
 (defvar bookmark-make-record-function)
+(when (memq window-system '(mac ns))
+  (defvar xwidget-webkit-enable-plugins nil
+    "Enable plugins for xwidget webkit.
+If non-nil, plugins are enabled.  Otherwise, disabled."))
+
 (define-derived-mode xwidget-webkit-mode
     special-mode "xwidget-webkit" "Xwidget webkit view mode."
     (setq buffer-read-only t)
diff --git a/nextstep/templates/Info.plist.in b/nextstep/templates/Info.plist.in
index c1e50a8409..76efe95673 100644
--- a/nextstep/templates/Info.plist.in
+++ b/nextstep/templates/Info.plist.in
@@ -675,7 +675,15 @@ along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
 	</array>
 	<key>NSAppleScriptEnabled</key>
 	<string>YES</string>
-        <key>NSAppleEventsUsageDescription</key>
-        <string>Emacs requires permission to send AppleEvents to other applications.</string>
+	<key>NSAppleEventsUsageDescription</key>
+	<string>Emacs requires permission to send AppleEvents to other applications.</string>
+	<!-- For xwidget webkit to browse remote url,
+	     but this set no restriction at all.  Consult apple's documentation
+	     for detail information about `NSApplicationDefinedMask'. -->
+	<key>NSAppTransportSecurity</key>
+	<dict>
+		<key>NSAllowsArbitraryLoads</key>
+		<true/>
+	</dict>
 </dict>
 </plist>
diff --git a/src/Makefile.in b/src/Makefile.in
index fd05a45df5..0af650244d 100644
--- a/src/Makefile.in
+++ b/src/Makefile.in
@@ -434,6 +434,7 @@ SOME_MACHINE_OBJECTS =
   xterm.o xfns.o xmenu.o xselect.o xrdb.o xsmfns.o fringe.o image.o \
   fontset.o dbusbind.o cygw32.o \
   nsterm.o nsfns.o nsmenu.o nsselect.o nsimage.o nsfont.o macfont.o \
+  nsxwidget.o \
   w32.o w32console.o w32cygwinx.o w32fns.o w32heap.o w32inevt.o w32notify.o \
   w32menu.o w32proc.o w32reg.o w32select.o w32term.o w32xfns.o \
   w16select.o widget.o xfont.o ftfont.o xftfont.o ftxfont.o gtkutil.o \
diff --git a/src/emacs.c b/src/emacs.c
index cc5818393a..f3b91182cf 100644
--- a/src/emacs.c
+++ b/src/emacs.c
@@ -1902,7 +1902,6 @@ main (int argc, char **argv)
       syms_of_xfns ();
       syms_of_xmenu ();
       syms_of_fontset ();
-      syms_of_xwidget ();
       syms_of_xsettings ();
 #ifdef HAVE_X_SM
       syms_of_xsmfns ();
@@ -1979,6 +1978,7 @@ main (int argc, char **argv)
 #endif /* HAVE_W32NOTIFY */
 #endif /* WINDOWSNT */
 
+      syms_of_xwidget ();
       syms_of_threads ();
       syms_of_profiler ();
       syms_of_pdumper ();
diff --git a/src/nsterm.m b/src/nsterm.m
index 02331826d9..7b4bfa4321 100644
--- a/src/nsterm.m
+++ b/src/nsterm.m
@@ -49,6 +49,7 @@ Updated by Christian Limpach (chris@nice.ch)
 #include "nsterm.h"
 #include "systime.h"
 #include "character.h"
+#include "xwidget.h"
 #include "fontset.h"
 #include "composite.h"
 #include "ccl.h"
@@ -2411,7 +2412,7 @@ so some key presses (TAB) are swallowed by the system.  */
 }
 
 static int
-ns_note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y)
+ns_note_mouse_movement (struct frame *frame, CGFloat x, CGFloat y, BOOL dragging)
 /*   ------------------------------------------------------------------------
      Called by EmacsView on mouseMovement events.  Passes on
      to emacs mainstream code if we moved off of a rect of interest
@@ -2420,17 +2421,24 @@ so some key presses (TAB) are swallowed by the system.  */
 {
   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (frame);
   NSRect *r;
+  BOOL force_update = NO;
 
   // NSTRACE ("note_mouse_movement");
 
   dpyinfo->last_mouse_motion_frame = frame;
   r = &dpyinfo->last_mouse_glyph;
 
+  /* If the last rect is too large (ex, xwidget webkit), update at
+     every move, or resizing by dragging modeline or vertical split is
+     very hard to make its way.  */
+  if (dragging && (r->size.width > 32 || r->size.height > 32))
+    force_update = YES;
+
   /* Note, this doesn't get called for enter/leave, since we don't have a
      position.  Those are taken care of in the corresponding NSView methods.  */
 
   /* Has movement gone beyond last rect we were tracking?  */
-  if (x < r->origin.x || x >= r->origin.x + r->size.width
+  if (force_update || x < r->origin.x || x >= r->origin.x + r->size.width
       || y < r->origin.y || y >= r->origin.y + r->size.height)
     {
       ns_update_begin (frame);
@@ -4182,6 +4190,10 @@ overwriting cursor (usually when cursor on a tab).  */
         }
       break;
 
+    case XWIDGET_GLYPH:
+      x_draw_xwidget_glyph_string (s);
+      break;
+
     case STRETCH_GLYPH:
       ns_dumpglyphs_stretch (s);
       break;
@@ -6835,6 +6847,7 @@ - (void)mouseMoved: (NSEvent *)e
   struct ns_display_info *dpyinfo = FRAME_DISPLAY_INFO (emacsframe);
   Lisp_Object frame;
   NSPoint pt;
+  BOOL dragging;
 
   NSTRACE_WHEN (NSTRACE_GROUP_EVENTS, "[EmacsView mouseMoved:]");
 
@@ -6877,7 +6890,8 @@ - (void)mouseMoved: (NSEvent *)e
       last_mouse_window = window;
     }
 
-  if (!ns_note_mouse_movement (emacsframe, pt.x, pt.y))
+  dragging = (e.type == NSEventTypeLeftMouseDragged);
+  if (!ns_note_mouse_movement (emacsframe, pt.x, pt.y, dragging))
     help_echo_string = previous_help_echo_string;
 
   XSETFRAME (frame, emacsframe);
diff --git a/src/nsxwidget.h b/src/nsxwidget.h
new file mode 100644
index 0000000000..7e2a3e0c40
--- /dev/null
+++ b/src/nsxwidget.h
@@ -0,0 +1,77 @@
+/* Header for NS Cocoa part of xwidget and webkit widget.
+
+Copyright (C) 2019 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 <http://www.gnu.org/licenses/>.  */
+
+#ifndef NSXWIDGET_H_INCLUDED
+#define NSXWIDGET_H_INCLUDED
+
+/* This file can be included from non-objc files through 'xwidget.h'.  */
+#ifdef __OBJC__
+#import <AppKit/NSView.h>
+#endif
+
+#include "dispextern.h"
+#include "lisp.h"
+#include "xwidget.h"
+
+/* Functions for xwidget webkit.  */
+
+bool nsxwidget_is_web_view (struct xwidget *xw);
+void nsxwidget_webkit_goto_uri (struct xwidget *xw, const char *uri);
+void nsxwidget_webkit_zoom (struct xwidget *xw, double zoom_change);
+void nsxwidget_webkit_execute_script (struct xwidget *xw, const char *script,
+                                      Lisp_Object fun);
+
+/* Functions for xwidget model.  */
+
+#ifdef __OBJC__
+@interface XwWindow : NSView
+@property struct xwidget *xw;
+@end
+#endif
+
+void nsxwidget_init (struct xwidget *xw);
+void nsxwidget_kill (struct xwidget *xw);
+void nsxwidget_resize (struct xwidget *xw);
+Lisp_Object nsxwidget_get_size (struct xwidget *xw);
+
+/* Functions for xwidget view.  */
+
+#ifdef __OBJC__
+@interface XvWindow : NSView
+@property struct xwidget *xw;
+@property struct xwidget_view *xv;
+@end
+#endif
+
+void nsxwidget_init_view (struct xwidget_view *xv,
+                          struct xwidget *xww,
+                          struct glyph_string *s,
+                          int x, int y);
+void nsxwidget_delete_view (struct xwidget_view *xv);
+
+void nsxwidget_show_view (struct xwidget_view *xv);
+void nsxwidget_hide_view (struct xwidget_view *xv);
+void nsxwidget_resize_view (struct xwidget_view *xv,
+                            int widget, int height);
+
+void nsxwidget_move_view (struct xwidget_view *xv, int x, int y);
+void nsxwidget_move_widget_in_view (struct xwidget_view *xv, int x, int y);
+void nsxwidget_set_needsdisplay (struct xwidget_view *xv);
+
+#endif /* NSXWIDGET_H_INCLUDED */
diff --git a/src/nsxwidget.m b/src/nsxwidget.m
new file mode 100644
index 0000000000..df6c06f59a
--- /dev/null
+++ b/src/nsxwidget.m
@@ -0,0 +1,564 @@
+/* NS Cocoa part implementation of xwidget and webkit widget.
+
+Copyright (C) 2019 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 <http://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 xwiget implementation;
+   Specifically NSView level view sharing / copying is not working.
+
+   *** So only one view can be associcated 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 xwiget.  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];
+  configuration.userContentController = scriptor;
+
+  /* Enable inspect element context menu item for debugging.  */
+  [configuration.preferences setValue:@YES
+                               forKey:@"developerExtrasEnabled"];
+
+  Lisp_Object enablePlugins =
+    Fintern (build_string ("xwidget-webkit-enable-plugins"), Qnil);
+  if (!EQ (Fsymbol_value (enablePlugins), Qnil))
+    configuration.preferences.plugInsEnabled = YES;
+
+  self = [super initWithFrame:frame configuration:configuration];
+  if (self)
+    {
+      self.xw = xw;
+      self.urlScriptBlocked = [[NSMutableDictionary alloc] init];
+      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"];
+      [scriptor addUserScript:[[WKUserScript alloc]
+                                initWithSource:xwScript
+                                 injectionTime:
+                                  WKUserScriptInjectionTimeAtDocumentStart
+                                forMainFrameOnly:NO]];
+    }
+  return self;
+}
+
+- (void)webView:(WKWebView *)webView
+didFinishNavigation:(WKNavigation *)navigation
+{
+  if (EQ (Fbuffer_live_p (self.xw->buffer), Qt))
+    store_xwidget_event_string (self.xw, "load-changed", "");
+}
+
+- (void)webView:(WKWebView *)webView
+decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
+decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
+{
+  switch (navigationAction.navigationType) {
+  case WKNavigationTypeLinkActivated:
+    decisionHandler (WKNavigationActionPolicyAllow);
+    break;
+  default:
+    // decisionHandler (WKNavigationActionPolicyCancel);
+    decisionHandler (WKNavigationActionPolicyAllow);
+    break;
+  }
+}
+
+- (void)webView:(WKWebView *)webView
+decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
+decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
+{
+  decisionHandler (WKNavigationResponsePolicyAllow);
+
+  self.urlScriptBlocked[navigationResponse.response.URL] =
+    [NSNumber numberWithBool:NO];
+  if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]])
+    {
+      NSDictionary *headers =
+        ((NSHTTPURLResponse *) navigationResponse.response).allHeaderFields;
+      NSString *value = headers[@"Content-Security-Policy"];
+      if (value)
+        {
+          /* TODO: Sloppy parsing of 'Content-Security-Policy' value.  */
+          NSRange sandbox = [value rangeOfString:@"sandbox"];
+          if (sandbox.location != NSNotFound
+              && (sandbox.location == 0
+                  || [value characterAtIndex:(sandbox.location - 1)] == ' '
+                  || [value characterAtIndex:(sandbox.location - 1)] == ';'))
+            {
+              NSRange allowScripts = [value rangeOfString:@"allow-scripts"];
+              if (allowScripts.location == NSNotFound
+                  || allowScripts.location < sandbox.location)
+                self.urlScriptBlocked[navigationResponse.response.URL] =
+                  [NSNumber numberWithBool:YES];
+            }
+        }
+    }
+}
+
+/* No additional new webview or emacs window will be created
+   for <a ... target="_blank">.  */
+- (WKWebView *)webView:(WKWebView *)webView
+createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration
+   forNavigationAction:(WKNavigationAction *)navigationAction
+        windowFeatures:(WKWindowFeatures *)windowFeatures
+{
+  if (!navigationAction.targetFrame.isMainFrame)
+    [webView loadRequest:navigationAction.request];
+  return nil;
+}
+
+/* Open panel for file upload.  */
+- (void)webView:(WKWebView *)webView
+runOpenPanelWithParameters:(WKOpenPanelParameters *)parameters
+initiatedByFrame:(WKFrameInfo *)frame
+completionHandler:(void (^)(NSArray<NSURL *> *URLs))completionHandler
+{
+  NSOpenPanel *openPanel = [NSOpenPanel openPanel];
+  openPanel.canChooseFiles = YES;
+  openPanel.canChooseDirectories = NO;
+  openPanel.allowsMultipleSelection = parameters.allowsMultipleSelection;
+  if ([openPanel runModal] == NSModalResponseOK)
+    completionHandler (openPanel.URLs);
+  else
+    completionHandler (nil);
+}
+
+/* By forwarding mouse events to emacs view (frame)
+   - Mouse click in webview selects the window contains the webview.
+   - Correct mouse hand/arrow/I-beam is displayed (TODO: not perfect yet).
+*/
+
+- (void)mouseDown:(NSEvent *)event
+{
+  [self.xw->xv->emacswindow mouseDown:event];
+  [super mouseDown:event];
+}
+
+- (void)mouseUp:(NSEvent *)event
+{
+  [self.xw->xv->emacswindow mouseUp:event];
+  [super mouseUp:event];
+}
+
+/* Basically we want keyboard events handled by emacs unless an input
+   element has focus.  Especially, while incremental search, we set
+   emacs as first responder to avoid focus held in an input element
+   with matching text.  */
+
+- (void)keyDown:(NSEvent *)event
+{
+  Lisp_Object var = Fintern (build_string ("isearch-mode"), Qnil);
+  Lisp_Object val = buffer_local_value (var, Fcurrent_buffer ());
+  if (!EQ (val, Qunbound) && !EQ (val, Qnil))
+    {
+      [self.window makeFirstResponder:self.xw->xv->emacswindow];
+      [self.xw->xv->emacswindow keyDown:event];
+      return;
+    }
+
+  /* Emacs handles keyboard events when javascript is blocked.  */
+  if ([self.urlScriptBlocked[self.URL] boolValue])
+    {
+      [self.xw->xv->emacswindow keyDown:event];
+      return;
+    }
+
+  [self evaluateJavaScript:@"xwHasFocus()"
+         completionHandler:^(id result, NSError *error) {
+      if (error)
+        {
+          NSLog (@"xwHasFocus: %@", error);
+          [self.xw->xv->emacswindow keyDown:event];
+        }
+      else if (result)
+        {
+          NSNumber *hasFocus = result; /* __NSCFBoolean */
+          if (!hasFocus.boolValue)
+            [self.xw->xv->emacswindow keyDown:event];
+          else
+            [super keyDown:event];
+        }
+    }];
+}
+
+- (void)interpretKeyEvents:(NSArray<NSEvent *> *)eventArray
+{
+  /* We should do nothing and do not forward (default implementation
+     if we not override here) to let emacs collect key events and ask
+     interpretKeyEvents to its superclass.  */
+}
+
+static NSString *xwScript;
++ (void)initialize
+{
+  /* Find out if an input element has focus.
+     Message to script message handler when 'C-g' key down.  */
+  if (!xwScript)
+    xwScript =
+      @"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.  */
+
+static Lisp_Object build_string_with_nsstr (NSString *nsstr);
+
+bool
+nsxwidget_is_web_view (struct xwidget *xw)
+{
+  return xw->xwWidget != NULL &&
+    [xw->xwWidget isKindOfClass:WKWebView.class];
+}
+/* @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_zoom (struct xwidget *xw, double zoom_change)
+{
+  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
+  xwWebView.magnification += zoom_change;
+  /* TODO: setMagnification:centeredAtPoint.  */
+}
+
+/* Build lisp string */
+static Lisp_Object
+build_string_with_nsstr (NSString *nsstr)
+{
+  const char *utfstr = [nsstr UTF8String];
+  NSUInteger bytes = [nsstr lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
+  return make_string (utfstr, bytes);
+}
+
+/* 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 build_string_with_nsstr ((NSString *) value);
+  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_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_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 (build_string_with_nsstr (prop_key),
+                                  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
+
+/* Xwidget model, macOS Cocoa part.  */
+
+void
+nsxwidget_init(struct xwidget *xw)
+{
+  block_input ();
+  NSRect rect = NSMakeRect (0, 0, xw->width, xw->height);
+  xw->xwWidget = [[XwWebView alloc]
+                   initWithFrame:rect
+                   configuration:[[WKWebViewConfiguration alloc] init]
+                         xwidget:xw];
+  xw->xwWindow = [[XwWindow alloc]
+                   initWithFrame:rect];
+  [xw->xwWindow addSubview:xw->xwWidget];
+  xw->xv = NULL; /* for 1 to 1 relationship of webkit2.  */
+  unblock_input ();
+}
+
+void
+nsxwidget_kill (struct xwidget *xw)
+{
+  if (xw)
+    {
+      WKUserContentController *scriptor =
+        ((XwWebView *) xw->xwWidget).configuration.userContentController;
+      [scriptor removeAllUserScripts];
+      [scriptor removeScriptMessageHandlerForName:@"keyDown"];
+      [scriptor release];
+      if (xw->xv)
+        xw->xv->model = Qnil; /* Make sure related view stale.  */
+
+      /* This stops playing audio when a xwidget-webkit buffer is
+         killed.  I could not find other solution.  */
+      nsxwidget_webkit_goto_uri (xw, "about:blank");
+
+      [((XwWebView *) xw->xwWidget).urlScriptBlocked release];
+      [xw->xwWidget removeFromSuperviewWithoutNeedingDisplay];
+      [xw->xwWidget release];
+      [xw->xwWindow removeFromSuperviewWithoutNeedingDisplay];
+      [xw->xwWindow release];
+      xw->xwWidget = nil;
+    }
+}
+
+void
+nsxwidget_resize (struct xwidget *xw)
+{
+  if (xw->xwWidget)
+    {
+      [xw->xwWindow setFrameSize:NSMakeSize(xw->width, xw->height)];
+      [xw->xwWidget setFrameSize:NSMakeSize(xw->width, xw->height)];
+    }
+}
+
+Lisp_Object
+nsxwidget_get_size (struct xwidget *xw)
+{
+  return list2i (xw->xwWidget.frame.size.width,
+                 xw->xwWidget.frame.size.height);
+}
+
+/* Xwidget view, macOS Cocoa part.  */
+
+@implementation XvWindow : NSView
+- (BOOL)isFlipped { return YES; }
+@end
+
+void
+nsxwidget_init_view (struct xwidget_view *xv,
+                     struct xwidget *xw,
+                     struct glyph_string *s,
+                     int x, int y)
+{
+  /* 'x_draw_xwidget_glyph_string' will calculate correct position and
+     size of clip to draw in emacs buffer window.  Thus, just begin at
+     origin with no crop.  */
+  xv->x = x;
+  xv->y = y;
+  xv->clip_left = 0;
+  xv->clip_right = xw->width;
+  xv->clip_top = 0;
+  xv->clip_bottom = xw->height;
+
+  xv->xvWindow = [[XvWindow alloc]
+                   initWithFrame:NSMakeRect (x, y, xw->width, xw->height)];
+  xv->xvWindow.xw = xw;
+  xv->xvWindow.xv = xv;
+
+  xw->xv = xv; /* For 1 to 1 relationship of webkit2.  */
+  [xv->xvWindow addSubview:xw->xwWindow];
+
+  xv->emacswindow = FRAME_NS_VIEW (s->f);
+  [xv->emacswindow addSubview:xv->xvWindow];
+}
+
+void
+nsxwidget_delete_view (struct xwidget_view *xv)
+{
+  if (!EQ (xv->model, Qnil))
+    {
+      struct xwidget *xw = XXWIDGET (xv->model);
+      [xw->xwWindow removeFromSuperviewWithoutNeedingDisplay];
+      xw->xv = NULL; /* Now model has no view.  */
+    }
+  [xv->xvWindow removeFromSuperviewWithoutNeedingDisplay];
+  [xv->xvWindow release];
+}
+
+void
+nsxwidget_show_view (struct xwidget_view *xv)
+{
+  xv->hidden = NO;
+  [xv->xvWindow setFrameOrigin:NSMakePoint(xv->x + xv->clip_left,
+                                           xv->y + xv->clip_top)];
+}
+
+void
+nsxwidget_hide_view (struct xwidget_view *xv)
+{
+  xv->hidden = YES;
+  [xv->xvWindow setFrameOrigin:NSMakePoint(10000, 10000)];
+}
+
+void
+nsxwidget_resize_view (struct xwidget_view *xv, int width, int height)
+{
+  [xv->xvWindow setFrameSize:NSMakeSize(width, height)];
+}
+
+void
+nsxwidget_move_view (struct xwidget_view *xv, int x, int y)
+{
+  [xv->xvWindow setFrameOrigin:NSMakePoint (x, y)];
+}
+
+/* Move model window in container (view window).  */
+void
+nsxwidget_move_widget_in_view (struct xwidget_view *xv, int x, int y)
+{
+  struct xwidget *xww = xv->xvWindow.xw;
+  [xww->xwWindow setFrameOrigin:NSMakePoint (x, y)];
+}
+
+void
+nsxwidget_set_needsdisplay (struct xwidget_view *xv)
+{
+  xv->xvWindow.needsDisplay = YES;
+}
diff --git a/src/xwidget.c b/src/xwidget.c
index 121510ebac..b841516c9f 100644
--- a/src/xwidget.c
+++ b/src/xwidget.c
@@ -23,21 +23,31 @@ Copyright (C) 2011-2019 Free Software Foundation, Inc.
 
 #include "lisp.h"
 #include "blockinput.h"
+#include "dispextern.h"
 #include "frame.h"
 #include "keyboard.h"
 #include "gtkutil.h"
 #include "sysstdio.h"
+#include "termhooks.h"
+#include "window.h"
 
+/* Include xwidget bottom end headers.  */
+#ifdef USE_GTK
 #include <webkit2/webkit2.h>
 #include <JavaScriptCore/JavaScript.h>
+#elif defined NS_IMPL_COCOA
+#include "nsxwidget.h"
+#endif
 
 /* Suppress GCC deprecation warnings starting in WebKitGTK+ 2.21.1 for
    webkit_javascript_result_get_global_context and
    webkit_javascript_result_get_value (Bug#33679).
    FIXME: Use the JavaScriptCore GLib API instead, and remove this hack.  */
+#ifdef USE_GTK
 #if WEBKIT_CHECK_VERSION (2, 21, 1) && GNUC_PREREQ (4, 2, 0)
 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
 #endif
+#endif
 
 static struct xwidget *
 allocate_xwidget (void)
@@ -56,6 +66,7 @@ #define XSETXWIDGET_VIEW(a, b) XSETPSEUDOVECTOR (a, b, PVEC_XWIDGET_VIEW)
 
 static struct xwidget_view *xwidget_view_lookup (struct xwidget *,
 						 struct window *);
+#ifdef USE_GTK
 static void webkit_view_load_changed_cb (WebKitWebView *,
                                          WebKitLoadEvent,
                                          gpointer);
@@ -69,6 +80,7 @@ webkit_decide_policy_cb (WebKitWebView *,
                          WebKitPolicyDecision *,
                          WebKitPolicyDecisionType,
                          gpointer);
+#endif
 
 
 DEFUN ("make-xwidget",
@@ -86,8 +98,10 @@ DEFUN ("make-xwidget",
    Lisp_Object title, Lisp_Object width, Lisp_Object height,
    Lisp_Object arguments, Lisp_Object buffer)
 {
+#ifdef USE_GTK
   if (!xg_gtk_initialized)
     error ("make-xwidget: GTK has not been initialized");
+#endif
   CHECK_SYMBOL (type);
   CHECK_FIXNAT (width);
   CHECK_FIXNAT (height);
@@ -102,10 +116,11 @@ DEFUN ("make-xwidget",
   xw->kill_without_query = false;
   XSETXWIDGET (val, xw);
   Vxwidget_list = Fcons (val, Vxwidget_list);
-  xw->widgetwindow_osr = NULL;
-  xw->widget_osr = NULL;
   xw->plist = Qnil;
 
+#ifdef USE_GTK
+  xw->widgetwindow_osr = NULL;
+  xw->widget_osr = NULL;
   if (EQ (xw->type, Qwebkit))
     {
       block_input ();
@@ -160,6 +175,9 @@ DEFUN ("make-xwidget",
 
       unblock_input ();
     }
+#elif defined NS_IMPL_COCOA
+  nsxwidget_init (xw);
+#endif
 
   return val;
 }
@@ -195,6 +213,7 @@ xwidget_hidden (struct xwidget_view *xv)
   return xv->hidden;
 }
 
+#ifdef USE_GTK
 static void
 xwidget_show_view (struct xwidget_view *xv)
 {
@@ -228,13 +247,14 @@ offscreen_damage_event (GtkWidget *widget, GdkEvent *event,
   if (GTK_IS_WIDGET (xv_widget))
     gtk_widget_queue_draw (GTK_WIDGET (xv_widget));
   else
-    printf ("Warning, offscreen_damage_event received invalid xv pointer:%p\n",
-            xv_widget);
+    message ("Warning, offscreen_damage_event received invalid xv pointer:%p\n",
+             xv_widget);
 
   return FALSE;
 }
+#endif /* USE_GTK */
 
-static void
+void
 store_xwidget_event_string (struct xwidget *xw, const char *eventname,
                             const char *eventstr)
 {
@@ -248,7 +268,7 @@ store_xwidget_event_string (struct xwidget *xw, const char *eventname,
   kbd_buffer_store_event (&event);
 }
 
-static void
+void
 store_xwidget_js_callback_event (struct xwidget *xw,
                                  Lisp_Object proc,
                                  Lisp_Object argument)
@@ -264,6 +284,7 @@ store_xwidget_js_callback_event (struct xwidget *xw,
 }
 
 
+#ifdef USE_GTK
 void
 webkit_view_load_changed_cb (WebKitWebView *webkitwebview,
                              WebKitLoadEvent load_event,
@@ -521,6 +542,7 @@ xwidget_osr_event_set_embedder (GtkWidget *widget, GdkEvent *event,
                                      gtk_widget_get_window (xv->widget));
   return FALSE;
 }
+#endif /* USE_GTK */
 
 
 /* Initializes and does initial placement of an xwidget view on screen.  */
@@ -530,8 +552,10 @@ xwidget_init_view (struct xwidget *xww,
                    int x, int y)
 {
 
+#ifdef USE_GTK
   if (!xg_gtk_initialized)
     error ("xwidget_init_view: GTK has not been initialized");
+#endif
 
   struct xwidget_view *xv = allocate_xwidget_view ();
   Lisp_Object val;
@@ -542,6 +566,7 @@ xwidget_init_view (struct xwidget *xww,
   XSETWINDOW (xv->w, s->w);
   XSETXWIDGET (xv->model, xww);
 
+#ifdef USE_GTK
   if (EQ (xww->type, Qwebkit))
     {
       xv->widget = gtk_drawing_area_new ();
@@ -599,6 +624,10 @@ xwidget_init_view (struct xwidget *xww,
   xv->x = x;
   xv->y = y;
   gtk_widget_show_all (xv->widgetwindow);
+#elif defined NS_IMPL_COCOA
+  nsxwidget_init_view (xv, xww, s, x, y);
+  nsxwidget_resize_view(xv, xww->width, xww->height);
+#endif
 
   return xv;
 }
@@ -611,6 +640,7 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
      initialization.  */
   struct xwidget *xww = s->xwidget;
   struct xwidget_view *xv = xwidget_view_lookup (xww, s->w);
+  int text_area_x, text_area_y, text_area_width, text_area_height;
   int clip_right;
   int clip_bottom;
   int clip_top;
@@ -622,13 +652,47 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
   /* Do initialization here in the display loop because there is no
      other time to know things like window placement etc.  Do not
      create a new view if we have found one that is usable.  */
+#ifdef USE_GTK
   if (!xv)
     xv = xwidget_init_view (xww, s, x, y);
-
-  int text_area_x, text_area_y, text_area_width, text_area_height;
+#elif defined NS_IMPL_COCOA
+  if (!xv)
+    {
+      /* Enforce 1 to 1, model and view for macOS Cocoa webkit2.  */
+      if (xww->xv)
+        {
+          if (xwidget_hidden (xww->xv))
+            {
+              Lisp_Object xvl;
+              XSETXWIDGET_VIEW (xvl, xww->xv);
+              Fdelete_xwidget_view (xvl);
+            }
+          else
+            {
+              message ("You can't share an xwidget (webkit2) among windows.");
+              return;
+            }
+        }
+      xv = xwidget_init_view (xww, s, x, y);
+    }
+#endif
 
   window_box (s->w, TEXT_AREA, &text_area_x, &text_area_y,
               &text_area_width, &text_area_height);
+
+  /* Resize xwidget webkit if its container window size is changed in
+     some ways, for example, a buffer became hidden in small split
+     window, then it can appear front in merged whole window.  */
+  if (EQ (xww->type, Qwebkit)
+      && (xww->width != text_area_width || xww->height != text_area_height))
+    {
+      Lisp_Object xwl;
+      XSETXWIDGET (xwl, xww);
+      Fxwidget_resize (xwl,
+                       make_int (text_area_width),
+                       make_int (text_area_height));
+    }
+
   clip_left = max (0, text_area_x - x);
   clip_right = max (clip_left,
 		    min (xww->width, text_area_x + text_area_width - x));
@@ -651,8 +715,14 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
 
   /* Has it moved?  */
   if (moved)
-    gtk_fixed_move (GTK_FIXED (FRAME_GTK_WIDGET (s->f)),
-		    xv->widgetwindow, x + clip_left, y + clip_top);
+    {
+#ifdef USE_GTK
+      gtk_fixed_move (GTK_FIXED (FRAME_GTK_WIDGET (s->f)),
+                      xv->widgetwindow, x + clip_left, y + clip_top);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_move_view (xv, x + clip_left, y + clip_top);
+#endif
+    }
 
   /* Clip the widget window if some parts happen to be outside
      drawable area.  An Emacs window is not a gtk window.  A gtk window
@@ -663,10 +733,16 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
       || xv->clip_bottom != clip_bottom
       || xv->clip_top != clip_top || xv->clip_left != clip_left)
     {
+#ifdef USE_GTK
       gtk_widget_set_size_request (xv->widgetwindow, clip_right - clip_left,
                                    clip_bottom - clip_top);
       gtk_fixed_move (GTK_FIXED (xv->widgetwindow), xv->widget, -clip_left,
                       -clip_top);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_resize_view (xv, clip_right - clip_left,
+                             clip_bottom - clip_top);
+      nsxwidget_move_widget_in_view (xv, -clip_left, -clip_top);
+#endif
 
       xv->clip_right = clip_right;
       xv->clip_bottom = clip_bottom;
@@ -680,16 +756,30 @@ x_draw_xwidget_glyph_string (struct glyph_string *s)
      xwidgets background.  It's just a visual glitch though.  */
   if (!xwidget_hidden (xv))
     {
+#ifdef USE_GTK
       gtk_widget_queue_draw (xv->widgetwindow);
       gtk_widget_queue_draw (xv->widget);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_set_needsdisplay (xv);
+#endif
     }
 }
 
-/* Macro that checks WEBKIT_IS_WEB_VIEW (xw->widget_osr) first.  */
+static bool
+xwidget_is_web_view (struct xwidget *xw)
+{
+#ifdef USE_GTK
+  return xw->widget_osr != NULL && WEBKIT_IS_WEB_VIEW (xw->widget_osr);
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_is_web_view (xw);
+#endif
+}
+
+/* Macro that checks xwidget hold webkit web view first.  */
 #define WEBKIT_FN_INIT()						\
   CHECK_XWIDGET (xwidget);						\
   struct xwidget *xw = XXWIDGET (xwidget);				\
-  if (!xw->widget_osr || !WEBKIT_IS_WEB_VIEW (xw->widget_osr))		\
+  if (!xwidget_is_web_view (xw))					\
     {									\
       fputs ("ERROR xw->widget_osr does not hold a webkit instance\n",	\
 	     stdout);							\
@@ -705,7 +795,11 @@ DEFUN ("xwidget-webkit-goto-uri",
   WEBKIT_FN_INIT ();
   CHECK_STRING (uri);
   uri = ENCODE_FILE (uri);
+#ifdef USE_GTK
   webkit_web_view_load_uri (WEBKIT_WEB_VIEW (xw->widget_osr), SSDATA (uri));
+#elif defined NS_IMPL_COCOA
+  nsxwidget_webkit_goto_uri (xw, SSDATA (uri));
+#endif
   return Qnil;
 }
 
@@ -719,14 +813,19 @@ DEFUN ("xwidget-webkit-zoom",
   if (FLOATP (factor))
     {
       double zoom_change = XFLOAT_DATA (factor);
+#ifdef USE_GTK
       webkit_web_view_set_zoom_level
         (WEBKIT_WEB_VIEW (xw->widget_osr),
          webkit_web_view_get_zoom_level
          (WEBKIT_WEB_VIEW (xw->widget_osr)) + zoom_change);
+#elif defined NS_IMPL_COCOA
+      nsxwidget_webkit_zoom (xw, zoom_change);
+#endif
     }
   return Qnil;
 }
 
+#ifdef USE_GTK
 /* Save script and fun in the script/callback save vector and return
    its index.  */
 static ptrdiff_t
@@ -748,6 +847,7 @@ save_script_callback (struct xwidget *xw, Lisp_Object script, Lisp_Object fun)
   ASET (cbs, idx, Fcons (make_mint_ptr (xlispstrdup (script)), fun));
   return idx;
 }
+#endif
 
 DEFUN ("xwidget-webkit-execute-script",
        Fxwidget_webkit_execute_script, Sxwidget_webkit_execute_script,
@@ -764,6 +864,7 @@ DEFUN ("xwidget-webkit-execute-script",
 
   script = ENCODE_SYSTEM (script);
 
+#ifdef USE_GTK
   /* Protect script and fun during GC.  */
   intptr_t idx = save_script_callback (xw, script, fun);
 
@@ -777,6 +878,9 @@ DEFUN ("xwidget-webkit-execute-script",
                                   NULL, /* cancelable */
                                   webkit_javascript_finished_cb,
 				  (gpointer) idx);
+#elif defined NS_IMPL_COCOA
+  nsxwidget_webkit_execute_script (xw, SSDATA (script), fun);
+#endif
   return Qnil;
 }
 
@@ -795,6 +899,7 @@ DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
   xw->height = h;
 
   /* If there is an offscreen widget resize it first.  */
+#ifdef USE_GTK
   if (xw->widget_osr)
     {
       gtk_window_resize (GTK_WINDOW (xw->widgetwindow_osr), xw->width,
@@ -803,6 +908,9 @@ DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
       gtk_widget_set_size_request (GTK_WIDGET (xw->widget_osr), xw->width,
                                    xw->height);
     }
+#elif defined NS_IMPL_COCOA
+  nsxwidget_resize (xw);
+#endif
 
   for (Lisp_Object tail = Vxwidget_view_list; CONSP (tail); tail = XCDR (tail))
     {
@@ -810,8 +918,14 @@ DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
         {
           struct xwidget_view *xv = XXWIDGET_VIEW (XCAR (tail));
           if (XXWIDGET (xv->model) == xw)
+            {
+#ifdef USE_GTK
               gtk_widget_set_size_request (GTK_WIDGET (xv->widget), xw->width,
                                            xw->height);
+#elif defined NS_IMPL_COCOA
+              nsxwidget_resize_view(xv, xw->width, xw->height);
+#endif
+            }
         }
     }
 
@@ -830,9 +944,13 @@ DEFUN ("xwidget-size-request",
   (Lisp_Object xwidget)
 {
   CHECK_XWIDGET (xwidget);
+#ifdef USE_GTK
   GtkRequisition requisition;
   gtk_widget_size_request (XXWIDGET (xwidget)->widget_osr, &requisition);
   return list2i (requisition.width, requisition.height);
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_get_size (XXWIDGET (xwidget));
+#endif
 }
 
 DEFUN ("xwidgetp",
@@ -909,14 +1027,19 @@ DEFUN ("delete-xwidget-view",
 {
   CHECK_XWIDGET_VIEW (xwidget_view);
   struct xwidget_view *xv = XXWIDGET_VIEW (xwidget_view);
+#ifdef USE_GTK
   gtk_widget_destroy (xv->widgetwindow);
-  Vxwidget_view_list = Fdelq (xwidget_view, Vxwidget_view_list);
   /* xv->model still has signals pointing to the view.  There can be
      several views.  Find the matching signals and delete them all.  */
   g_signal_handlers_disconnect_matched  (XXWIDGET (xv->model)->widgetwindow_osr,
                                          G_SIGNAL_MATCH_DATA,
                                          0, 0, 0, 0,
                                          xv->widget);
+#elif defined NS_IMPL_COCOA
+  nsxwidget_delete_view (xv);
+#endif
+
+  Vxwidget_view_list = Fdelq (xwidget_view, Vxwidget_view_list);
   return Qnil;
 }
 
@@ -1193,11 +1316,19 @@ xwidget_end_redisplay (struct window *w, struct glyph_matrix *matrix)
 		     xwidget_end_redisplay (w->current_matrix);  */
 		  struct xwidget_view *xv
 		    = xwidget_view_lookup (glyph->u.xwidget, w);
+#ifdef USE_GTK
 		  /* FIXME: Is it safe to assume xwidget_view_lookup
 		     always succeeds here?  If so, this comment can be removed.
 		     If not, the code probably needs fixing.  */
 		  eassume (xv);
 		  xwidget_touch (xv);
+#elif defined NS_IMPL_COCOA
+                  /* In NS xwidget, xv can be NULL for the second or
+                     later views for a model, the result of 1 to 1
+                     model view relation enforcement.  */
+                  if (xv)
+                    xwidget_touch (xv);
+#endif
 		}
 	  }
     }
@@ -1214,9 +1345,21 @@ xwidget_end_redisplay (struct window *w, struct glyph_matrix *matrix)
           if (XWINDOW (xv->w) == w)
             {
               if (xwidget_touched (xv))
-                xwidget_show_view (xv);
+                {
+#ifdef USE_GTK
+                  xwidget_show_view (xv);
+#elif defined NS_IMPL_COCOA
+                  nsxwidget_show_view (xv);
+#endif
+                }
               else
-                xwidget_hide_view (xv);
+                {
+#ifdef USE_GTK
+                  xwidget_hide_view (xv);
+#elif defined NS_IMPL_COCOA
+                  nsxwidget_hide_view (xv);
+#endif
+                }
             }
         }
     }
@@ -1235,6 +1378,7 @@ kill_buffer_xwidgets (Lisp_Object buffer)
       {
         CHECK_XWIDGET (xwidget);
         struct xwidget *xw = XXWIDGET (xwidget);
+#ifdef USE_GTK
         if (xw->widget_osr && xw->widgetwindow_osr)
           {
             gtk_widget_destroy (xw->widget_osr);
@@ -1248,6 +1392,9 @@ kill_buffer_xwidgets (Lisp_Object buffer)
 		xfree (xmint_pointer (XCAR (cb)));
 	      ASET (xw->script_callbacks, idx, Qnil);
 	    }
+#elif defined NS_IMPL_COCOA
+        nsxwidget_kill (xw);
+#endif
       }
     }
 }
diff --git a/src/xwidget.h b/src/xwidget.h
index 1b6368daab..73d8bbd540 100644
--- a/src/xwidget.h
+++ b/src/xwidget.h
@@ -29,7 +29,13 @@ #define XWIDGET_H_INCLUDED
 struct window;
 
 #ifdef HAVE_XWIDGETS
-# include <gtk/gtk.h>
+
+#if defined (USE_GTK)
+#include <gtk/gtk.h>
+#elif defined (NS_IMPL_COCOA) && defined (__OBJC__)
+#import <AppKit/NSView.h>
+#import "nsxwidget.h"
+#endif
 
 struct xwidget
 {
@@ -54,9 +60,25 @@ #define XWIDGET_H_INCLUDED
   int height;
   int width;
 
+#if defined (USE_GTK)
   /* For offscreen widgets, unused if not osr.  */
   GtkWidget *widget_osr;
   GtkWidget *widgetwindow_osr;
+#elif defined (NS_IMPL_COCOA)
+# ifdef __OBJC__
+  /* For offscreen widgets, unused if not osr.  */
+  NSView *xwWidget;
+  XwWindow *xwWindow;
+
+  /* Used only for xwidget types (such as webkit2) enforcing 1 to 1
+     relationship between model and view.  */
+  struct xwidget_view *xv;
+# else
+  void *xwWidget;
+  void *xwWindow;
+  struct xwidget_view *xv;
+# endif
+#endif
 
   /* Kill silently if Emacs is exited.  */
   bool_bf kill_without_query : 1;
@@ -75,9 +97,20 @@ #define XWIDGET_H_INCLUDED
   /* The "live" instance isn't drawn.  */
   bool hidden;
 
+#if defined (USE_GTK)
   GtkWidget *widget;
   GtkWidget *widgetwindow;
   GtkWidget *emacswindow;
+#elif defined (NS_IMPL_COCOA)
+# ifdef __OBJC__
+  XvWindow *xvWindow;
+  NSView *emacswindow;
+# else
+  void *xvWindow;
+  void *emacswindow;
+# endif
+#endif
+
   int x;
   int y;
   int clip_right;
@@ -116,6 +149,16 @@ #define XG_XWIDGET_VIEW "emacs_xwidget_view"
 struct xwidget *lookup_xwidget (Lisp_Object spec);
 void xwidget_end_redisplay (struct window *, struct glyph_matrix *);
 void kill_buffer_xwidgets (Lisp_Object);
+#ifdef NS_IMPL_COCOA
+/* Defined in 'xwidget.c'.  */
+void store_xwidget_event_string (struct xwidget *xw,
+                                 const char *eventname,
+                                 const char *eventstr);
+
+void store_xwidget_js_callback_event (struct xwidget *xw,
+                                      Lisp_Object proc,
+                                      Lisp_Object argument);
+#endif
 #else
 INLINE_HEADER_BEGIN
 INLINE void syms_of_xwidget (void) {}
-- 
2.17.2 (Apple Git-113)


[-- Attachment #3: 0002-Various-small-enhancements-in-xwidget-webkit.patch --]
[-- Type: application/octet-stream, Size: 24032 bytes --]

From 78af5a869493a797764c3e847c1c3ccbf641d891 Mon Sep 17 00:00:00 2001
From: Sungbin Jo <pcr910303@icloud.com>
Date: Fri, 26 Jul 2019 02:51:55 +0900
Subject: [PATCH 2/3] Various small enhancements in xwidget-webkit

Co-authored-by: Jaesup Kwak <veshboo@gmail.com>

* etc/NEWS: Announce new functions and options.
* lisp/xwidget.el (xwidget): New defgroup.
(xwidget-webkit-mode-map): Add new keybindings.
(xwidget-webkit-scroll-up, xwidget-webkit-scroll-down)
(xwidget-webkit-scroll-forward, xwidget-webkit-scroll-backward):
Add optional argument to specify specific amounts to scroll down.
(xwidget-webkit-scroll-up-line, xwidget-webkit-scroll-down-line): New
functions.
(xwidget-webkit-scroll-bottom): Fix function to scroll to the bottom
of the document.
(xwidget-webkit-callback): Use new function to update buffer title
even when Javascript is disabled.
(xwidget-webkit-bookmark-jump-new-session): New variable.
(xwidget-webkit-bookmark-make-record): Modify to use xwidget-webkit to
open bookmark that is created in xwidget-webkit.
(xwidget-webkit-insert-string): Fix Javascript snippet to not throw
Javsscript exceptions.
(xwidget-webkit-inside-pixel-width)
(xwidget-window-inside-pixel-height): New functions.
(xwidget-webkit-adjust-size-to-window): Use new functions.
(xwidget-webkit-new-session): Insert invisible URL instead of an empty
string to achieve better default behavior.
(xwidget-webkit-back, xwidget-webkit-forward, xwidget-webkit-reload)
(xwidget-webkit-current-url): Use new functions to enable scrolling
even when Javascript is disabled.
(xwidget-webkit-copy-selection-as-kill): Remove unnecessary lambda.
* src/nsxwidget.h src/nsxwidget.m (nsxwidget_webkit_uri)
(nsxwidget_webkit_title, nsxwidget_webkit_goto_history): Add new
functions.
* src/xwidget.c (Fxwidget_webkit_uri, Fxwidget_webkit_title)
(Fxwidget_webkit_goto_history): Add new functions.
(syms_of_xwidget): Define new functions.
---
 etc/NEWS        |  18 +++++
 lisp/xwidget.el | 206 ++++++++++++++++++++++++++++++++----------------
 src/nsxwidget.h |   3 +
 src/nsxwidget.m |  26 ++++++
 src/xwidget.c   |  54 +++++++++++++
 5 files changed, 238 insertions(+), 69 deletions(-)

diff --git a/etc/NEWS b/etc/NEWS
index 52b49bab75..f9a42f73be 100644
--- a/etc/NEWS
+++ b/etc/NEWS
@@ -1735,6 +1735,24 @@ particular when the end of the buffer is visible in the window.
 Use 'mouse-wheel-mode' instead.  Note that 'mouse-wheel-mode' is
 already enabled by default on most graphical displays.
 
+** xwidget-webkit mode
+
+*** New functions 'xwidget-webkit-uri', 'xwidget-webkit-title',
+and 'xwidget-webkit-goto-history'.
+
+*** Functions 'xwidget-webkit-scroll-up', 'xwidget-webkit-scroll-down'
+now supports scrolling arbitrary pixel values.  It now treats the
+optional 2nd argument as the pixel values to scroll.
+
+*** New functions 'xwidget-webkit-scroll-up-line',
+'xwidget-webkit-scroll-down-line', 'xwidget-webkit-scroll-forward',
+'xwidget-webkit-scroll-backward'.
+Use them to scroll webkit by the height of lines or width of chars.
+
+*** New user option 'xwidget-webkit-bookmark-jump-new-session'.
+When non-nil, use a new xwidget webkit session after bookmark jump.
+Otherwise, it will use 'xwidget-webkit-last-session'.
+
 \f
 * New Modes and Packages in Emacs 27.1
 
diff --git a/lisp/xwidget.el b/lisp/xwidget.el
index f01822c792..584a894148 100644
--- a/lisp/xwidget.el
+++ b/lisp/xwidget.el
@@ -41,7 +41,10 @@
 (declare-function xwidget-resize "xwidget.c" (xwidget new-width new-height))
 (declare-function xwidget-webkit-execute-script "xwidget.c"
                   (xwidget script &optional callback))
+(declare-function xwidget-webkit-uri "xwidget.c" (xwidget))
+(declare-function xwidget-webkit-title "xwidget.c" (xwidget))
 (declare-function xwidget-webkit-goto-uri "xwidget.c" (xwidget uri))
+(declare-function xwidget-webkit-goto-history "xwidget.c" (xwidget rel-pos))
 (declare-function xwidget-webkit-zoom "xwidget.c" (xwidget factor))
 (declare-function xwidget-plist "xwidget.c" (xwidget))
 (declare-function set-xwidget-plist "xwidget.c" (xwidget plist))
@@ -51,6 +54,10 @@
 (declare-function get-buffer-xwidgets "xwidget.c" (buffer))
 (declare-function xwidget-query-on-exit-flag "xwidget.c" (xwidget))
 
+(defgroup xwidget nil
+  "Displaying native widgets in Emacs buffers."
+  :group 'widgets)
+
 (defun xwidget-insert (pos type title width height &optional args)
   "Insert an xwidget at position POS.
 Supply the xwidget's TYPE, TITLE, WIDTH, and HEIGHT.
@@ -78,6 +85,8 @@ xwidget-at
 ;;; webkit support
 (require 'browse-url)
 (require 'image-mode);;for some image-mode alike functionality
+(require 'seq)
+(require 'url-handlers)
 
 ;;;###autoload
 (defun xwidget-webkit-browse-url (url &optional new-session)
@@ -121,6 +130,7 @@ xwidget-webkit-mode-map
     (define-key map "g" 'xwidget-webkit-browse-url)
     (define-key map "a" 'xwidget-webkit-adjust-size-dispatch)
     (define-key map "b" 'xwidget-webkit-back)
+    (define-key map "f" 'xwidget-webkit-forward)
     (define-key map "r" 'xwidget-webkit-reload)
     (define-key map "t" (lambda () (interactive) (message "o"))) ;FIXME: ?!?
     (define-key map "\C-m" 'xwidget-webkit-insert-string)
@@ -130,20 +140,21 @@ xwidget-webkit-mode-map
 
     ;;similar to image mode bindings
     (define-key map (kbd "SPC")                 'xwidget-webkit-scroll-up)
+    (define-key map (kbd "S-SPC")               'xwidget-webkit-scroll-down)
     (define-key map (kbd "DEL")                 'xwidget-webkit-scroll-down)
 
-    (define-key map [remap scroll-up]           'xwidget-webkit-scroll-up)
+    (define-key map [remap scroll-up]           'xwidget-webkit-scroll-up-line)
     (define-key map [remap scroll-up-command]   'xwidget-webkit-scroll-up)
 
-    (define-key map [remap scroll-down]         'xwidget-webkit-scroll-down)
+    (define-key map [remap scroll-down]         'xwidget-webkit-scroll-down-line)
     (define-key map [remap scroll-down-command] 'xwidget-webkit-scroll-down)
 
     (define-key map [remap forward-char]        'xwidget-webkit-scroll-forward)
     (define-key map [remap backward-char]       'xwidget-webkit-scroll-backward)
     (define-key map [remap right-char]          'xwidget-webkit-scroll-forward)
     (define-key map [remap left-char]           'xwidget-webkit-scroll-backward)
-    (define-key map [remap previous-line]       'xwidget-webkit-scroll-down)
-    (define-key map [remap next-line]           'xwidget-webkit-scroll-up)
+    (define-key map [remap previous-line]       'xwidget-webkit-scroll-down-line)
+    (define-key map [remap next-line]           'xwidget-webkit-scroll-up-line)
 
     ;; (define-key map [remap move-beginning-of-line] 'image-bol)
     ;; (define-key map [remap move-end-of-line]       'image-eol)
@@ -162,33 +173,63 @@ xwidget-webkit-zoom-out
   (interactive)
   (xwidget-webkit-zoom (xwidget-webkit-current-session) -0.1))
 
-(defun xwidget-webkit-scroll-up ()
-  "Scroll webkit up."
-  (interactive)
+(defun xwidget-webkit-scroll-up (&optional arg)
+  "Scroll webkit up by ARG pixels; or full window height if no ARG.
+Stop if bottom of page is reached.
+Interactively, ARG is the prefix numeric argument.
+Negative ARG scrolls down."
+  (interactive "P")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(0, 50);"))
-
-(defun xwidget-webkit-scroll-down ()
-  "Scroll webkit down."
-  (interactive)
+   (format "window.scrollBy(0, %d);"
+           (or arg (xwidget-window-inside-pixel-height (selected-window))))))
+
+(defun xwidget-webkit-scroll-down (&optional arg)
+  "Scroll webkit down by ARG pixels; or full window height if no ARG.
+Stop if top of page is reached.
+Interactively, ARG is the prefix numeric argument.
+Negative ARG scrolls up."
+  (interactive "P")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(0, -50);"))
-
-(defun xwidget-webkit-scroll-forward ()
-  "Scroll webkit forwards."
-  (interactive)
+   (format "window.scrollBy(0, -%d);"
+           (or arg (xwidget-window-inside-pixel-height (selected-window))))))
+
+(defun xwidget-webkit-scroll-up-line (&optional n)
+  "Scroll webkit up by N lines.
+The height of line is calculated with `window-font-height'.
+Stop if the bottom edge of the page is reached.
+If N is omitted or nil, scroll up by one line."
+  (interactive "p")
+  (xwidget-webkit-scroll-up (* n (window-font-height))))
+
+(defun xwidget-webkit-scroll-down-line (&optional n)
+  "Scroll webkit down by N lines.
+The height of line is calculated with `window-font-height'.
+Stop if the top edge of the page is reached.
+If N is omitted or nil, scroll down by one line."
+  (interactive "p")
+  (xwidget-webkit-scroll-down (* n (window-font-height))))
+
+(defun xwidget-webkit-scroll-forward (&optional n)
+  "Scroll webkit horizontally by N chars.
+The width of char is calculated with `window-font-width'.
+If N is ommited or nil, scroll forwards by one char."
+  (interactive "p")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(50, 0);"))
-
-(defun xwidget-webkit-scroll-backward ()
-  "Scroll webkit backwards."
-  (interactive)
+   (format "window.scrollBy(%d, 0);"
+           (* n (window-font-width)))))
+
+(defun xwidget-webkit-scroll-backward (&optional n)
+  "Scroll webkit back by N chars.
+The width of char is calculated with `window-font-width'.
+If N is ommited or nil, scroll backwards by one char."
+  (interactive "p")
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollBy(-50, 0);"))
+   (format "window.scrollBy(-%d, 0);"
+           (* n (window-font-width)))))
 
 (defun xwidget-webkit-scroll-top ()
   "Scroll webkit to the very top."
@@ -202,7 +243,7 @@ xwidget-webkit-scroll-bottom
   (interactive)
   (xwidget-webkit-execute-script
    (xwidget-webkit-current-session)
-   "window.scrollTo(pageXOffset, window.document.body.clientHeight);"))
+   "window.scrollTo(pageXOffset, window.document.body.scrollHeight);"))
 
 ;; The xwidget event needs to go into a higher level handler
 ;; since the xwidget can generate an event even if it's offscreen.
@@ -226,7 +267,6 @@ xwidget-event-handler
        ;;TODO stopped working for some reason
        )
     ;;(funcall  xwidget-callback xwidget xwidget-event-type)
-    (message "xw callback %s" xwidget)
     (funcall  'xwidget-webkit-callback xwidget xwidget-event-type)))
 
 (defun xwidget-webkit-callback (xwidget xwidget-event-type)
@@ -237,14 +277,11 @@ xwidget-webkit-callback
        "error: callback called for xwidget with dead buffer")
     (with-current-buffer (xwidget-buffer xwidget)
       (cond ((eq xwidget-event-type 'load-changed)
-             (xwidget-webkit-execute-script
-              xwidget "document.title"
-              (lambda (title)
-                (xwidget-log "webkit finished loading: '%s'" title)
-                ;; Do not adjust webkit size to window here, the selected window
-                ;; can be the mini-buffer window unwantedly.
-                (rename-buffer (format "*xwidget webkit: %s *" title))))
-             (pop-to-buffer (current-buffer)))
+             (let ((title (xwidget-webkit-title xwidget)))
+               (xwidget-log "webkit finished loading: %s" title)
+               ;; Do not adjust webkit size to window here, the selected window
+               ;; can be the mini-buffer window unwantedly.
+               (rename-buffer (format "*xwidget webkit: %s *" title) t)))
             ((eq xwidget-event-type 'decide-policy)
              (let ((strarg  (nth 3 last-input-event)))
                (if (string-match ".*#\\(.*\\)" strarg)
@@ -264,20 +301,34 @@ bookmark-make-record-function
 If non-nil, plugins are enabled.  Otherwise, disabled."))
 
 (define-derived-mode xwidget-webkit-mode
-    special-mode "xwidget-webkit" "Xwidget webkit view mode."
-    (setq buffer-read-only t)
-    (setq-local bookmark-make-record-function
-                #'xwidget-webkit-bookmark-make-record)
-    ;; Keep track of [vh]scroll when switching buffers
-    (image-mode-setup-winprops))
+  special-mode "xwidget-webkit" "Xwidget webkit view mode."
+  (setq buffer-read-only t)
+  (setq-local bookmark-make-record-function
+              #'xwidget-webkit-bookmark-make-record)
+  ;; Keep track of [vh]scroll when switching buffers
+  (image-mode-setup-winprops))
+
+;;; Bookmarks integration
+
+(defcustom xwidget-webkit-bookmark-jump-new-session nil
+  "Control bookmark jump to use new session or not.
+If non-nil, use a new xwidget webkit session after bookmark jump.
+Otherwise, it will use `xwidget-webkit-last-session'.
+When you set this variable to nil, consider further customization with
+`xwidget-webkit-last-session-buffer'."
+  :version "27.1"
+  :type 'boolean)
 
 (defun xwidget-webkit-bookmark-make-record ()
-  "Integrate Emacs bookmarks with the webkit xwidget."
+  "Create bookmark record in webkit xwidget."
   (nconc (bookmark-make-record-default t t)
-         `((page     . ,(xwidget-webkit-current-url))
-           (handler  . (lambda (bmk) (browse-url
-                                 (bookmark-prop-get bmk 'page)))))))
+         `((page . ,(xwidget-webkit-uri (xwidget-webkit-current-session)))
+           (handler  . (lambda (bmk)
+                         (xwidget-webkit-browse-url
+                          (bookmark-prop-get bmk 'page)
+                          xwidget-webkit-bookmark-jump-new-session))))))
 
+;;; xwidget webkit session
 
 (defvar xwidget-webkit-last-session-buffer nil)
 
@@ -325,7 +376,7 @@ xwidget-webkit-activeelement-js"
 
 "
 
-  "javascript that finds the active element."
+  "Javascript that finds the active element."
   ;; Yes it's ugly, because:
   ;; - there is apparently no way to find the active frame other than recursion
   ;; - the js "for each" construct misbehaved on the "frames" collection
@@ -335,19 +386,22 @@ xwidget-webkit-activeelement-js"
   )
 
 (defun xwidget-webkit-insert-string ()
-  "Prompt for a string and insert it in the active field in the
-current webkit widget."
+  "Insert string into the active field in the current webkit widget."
   ;; Read out the string in the field first and provide for edit.
   (interactive)
+  ;; As the prompt differs on JavaScript execution results,
+  ;; the function must handle the prompt itself.
   (let ((xww (xwidget-webkit-current-session)))
     (xwidget-webkit-execute-script
      xww
      (concat xwidget-webkit-activeelement-js "
 (function () {
   var res = findactiveelement(document);
-  return [res.value, res.type];
+  if (res)
+    return [res.value, res.type];
 })();")
      (lambda (field)
+       "Prompt a string for the FIELD and insert in the active input."
        (let ((str (pcase field
                     (`[,val "text"]
                      (read-string "Text: " val))
@@ -466,11 +520,23 @@ xwidget-webkit-adjust-size-dispatch
   (ignore-errors
     (recenter-top-bottom)))
 
+;; Utility functions
+
+(defun xwidget-window-inside-pixel-width (window)
+  "Return Emacs WINDOW body width in pixel."
+  (let ((edges (window-inside-pixel-edges window)))
+    (- (nth 2 edges) (nth 0 edges))))
+
+(defun xwidget-window-inside-pixel-height (window)
+  "Return Emacs WINDOW body height in pixel."
+  (let ((edges (window-inside-pixel-edges window)))
+    (- (nth 3 edges) (nth 1 edges))))
+
 (defun xwidget-webkit-adjust-size-to-window (xwidget &optional window)
   "Adjust the size of the webkit XWIDGET to fit the WINDOW."
   (xwidget-resize xwidget
-                  (window-pixel-width window)
-                  (window-pixel-height window)))
+                  (xwidget-window-inside-pixel-width window)
+                  (xwidget-window-inside-pixel-height window)))
 
 (defun xwidget-webkit-adjust-size (w h)
   "Manually set webkit size to width W, height H."
@@ -509,42 +575,45 @@ xwidget-webkit-new-session
                                               (get-buffer-create bufname)))
     ;; The xwidget id is stored in a text property, so we need to have
     ;; at least character in this buffer.
-    (insert " ")
-    (setq xw (xwidget-insert 1 'webkit bufname
-                             (window-pixel-width)
-                             (window-pixel-height)))
+    ;; Insert invisible url, good default for next `g' to browse url.
+    (let ((start (point)))
+      (insert url)
+      (put-text-property start (+ start (length url)) 'invisible t)
+      (setq xw (xwidget-insert start 'webkit bufname
+                               (xwidget-window-inside-pixel-width (selected-window))
+                               (xwidget-window-inside-pixel-height (selected-window)))))
     (xwidget-put xw 'callback 'xwidget-webkit-callback)
     (xwidget-webkit-mode)
     (xwidget-webkit-goto-uri (xwidget-webkit-last-session) url)))
 
 
 (defun xwidget-webkit-goto-url (url)
-  "Goto URL."
+  "Goto URL with xwidget webkit."
   (if (xwidget-webkit-current-session)
       (progn
         (xwidget-webkit-goto-uri (xwidget-webkit-current-session) url))
     (xwidget-webkit-new-session url)))
 
 (defun xwidget-webkit-back ()
-  "Go back in history."
+  "Go back to previous URL in xwidget webkit buffer."
+  (interactive)
+  (xwidget-webkit-goto-history (xwidget-webkit-current-session) -1))
+
+(defun xwidget-webkit-forward ()
+  "Go forward in history."
   (interactive)
-  (xwidget-webkit-execute-script (xwidget-webkit-current-session)
-                                 "history.go(-1);"))
+  (xwidget-webkit-goto-history (xwidget-webkit-current-session) 1))
 
 (defun xwidget-webkit-reload ()
-  "Reload current url."
+  "Reload current URL."
   (interactive)
-  (xwidget-webkit-execute-script (xwidget-webkit-current-session)
-                                 "history.go(0);"))
+  (xwidget-webkit-goto-history (xwidget-webkit-current-session) 0))
 
 (defun xwidget-webkit-current-url ()
-  "Get the webkit url and place it on the kill-ring."
+  "Display the current xwidget webkit URL and place it on the `kill-ring'."
   (interactive)
-  (xwidget-webkit-execute-script
-   (xwidget-webkit-current-session)
-   "document.URL" (lambda (rv)
-                    (let ((url (kill-new (or rv ""))))
-                      (message "url: %s" url)))))
+  (let ((url (xwidget-webkit-uri (xwidget-webkit-current-session))))
+    (message "URL: %s" (kill-new (or url "")))))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 (defun xwidget-webkit-get-selection (proc)
@@ -555,10 +624,9 @@ xwidget-webkit-get-selection
    proc))
 
 (defun xwidget-webkit-copy-selection-as-kill ()
-  "Get the webkit selection and put it on the kill-ring."
+  "Get the webkit selection and put it on the `kill-ring'."
   (interactive)
-  (xwidget-webkit-get-selection (lambda (selection) (kill-new selection))))
-
+  (xwidget-webkit-get-selection #'kill-new))
 
 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
 ;; Xwidget plist management (similar to the process plist functions)
diff --git a/src/nsxwidget.h b/src/nsxwidget.h
index 7e2a3e0c40..521601922f 100644
--- a/src/nsxwidget.h
+++ b/src/nsxwidget.h
@@ -32,7 +32,10 @@ #define NSXWIDGET_H_INCLUDED
 /* Functions for xwidget webkit.  */
 
 bool nsxwidget_is_web_view (struct xwidget *xw);
+Lisp_Object nsxwidget_webkit_uri (struct xwidget *xw);
+Lisp_Object nsxwidget_webkit_title (struct xwidget *xw);
 void nsxwidget_webkit_goto_uri (struct xwidget *xw, const char *uri);
+void nsxwidget_webkit_goto_history (struct xwidget *xw, int rel_pos);
 void nsxwidget_webkit_zoom (struct xwidget *xw, double zoom_change);
 void nsxwidget_webkit_execute_script (struct xwidget *xw, const char *script,
                                       Lisp_Object fun);
diff --git a/src/nsxwidget.m b/src/nsxwidget.m
index df6c06f59a..87a10e34e0 100644
--- a/src/nsxwidget.m
+++ b/src/nsxwidget.m
@@ -293,6 +293,21 @@ - (void)userContentController:(WKUserContentController *)userContentController
   return xw->xwWidget != NULL &&
     [xw->xwWidget isKindOfClass:WKWebView.class];
 }
+
+Lisp_Object
+nsxwidget_webkit_uri (struct xwidget *xw)
+{
+  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
+  return build_string_with_nsstr (xwWebView.URL.absoluteString);
+}
+
+Lisp_Object
+nsxwidget_webkit_title (struct xwidget *xw)
+{
+  XwWebView *xwWebView = (XwWebView *) xw->xwWidget;
+  return build_string_with_nsstr (xwWebView.title);
+}
+
 /* @Note ATS - Need application transport security in 'Info.plist' or
    remote pages will not loaded.  */
 void
@@ -305,6 +320,17 @@ - (void)userContentController:(WKUserContentController *)userContentController
   [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;
+  }
+}
+
 void
 nsxwidget_webkit_zoom (struct xwidget *xw, double zoom_change)
 {
diff --git a/src/xwidget.c b/src/xwidget.c
index b841516c9f..15d909f51c 100644
--- a/src/xwidget.c
+++ b/src/xwidget.c
@@ -786,6 +786,36 @@ #define WEBKIT_FN_INIT()						\
       return Qnil;							\
     }
 
+DEFUN ("xwidget-webkit-uri",
+       Fxwidget_webkit_uri, Sxwidget_webkit_uri,
+       1, 1, 0,
+       doc: /* Get the current URL of XWIDGET webkit.  */)
+  (Lisp_Object xwidget)
+{
+  WEBKIT_FN_INIT ();
+#ifdef USE_GTK
+  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
+  return build_string (webkit_web_view_get_uri (wkwv));
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_webkit_uri (xw);
+#endif
+}
+
+DEFUN ("xwidget-webkit-title",
+       Fxwidget_webkit_title, Sxwidget_webkit_title,
+       1, 1, 0,
+       doc: /* Get the current title of XWIDGET webkit.  */)
+  (Lisp_Object xwidget)
+{
+  WEBKIT_FN_INIT ();
+#ifdef USE_GTK
+  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
+  return build_string (webkit_web_view_get_title (wkwv));
+#elif defined NS_IMPL_COCOA
+  return nsxwidget_webkit_title (xw);
+#endif
+}
+
 DEFUN ("xwidget-webkit-goto-uri",
        Fxwidget_webkit_goto_uri, Sxwidget_webkit_goto_uri,
        2, 2, 0,
@@ -803,6 +833,27 @@ DEFUN ("xwidget-webkit-goto-uri",
   return Qnil;
 }
 
+DEFUN ("xwidget-webkit-goto-history",
+       Fxwidget_webkit_goto_history, Sxwidget_webkit_goto_history,
+       2, 2, 0,
+       doc: /* Make the XWIDGET webkit load REL-POS (-1, 0, 1) page in browse history.  */)
+  (Lisp_Object xwidget, Lisp_Object rel_pos)
+{
+  WEBKIT_FN_INIT ();
+  CHECK_RANGED_INTEGER (rel_pos, -1, 1); /* -1, 0, 1 */
+#ifdef USE_GTK
+  WebKitWebView *wkwv = WEBKIT_WEB_VIEW (xw->widget_osr);
+  switch (XFIXNAT (rel_pos)) {
+  case -1: webkit_web_view_go_back (wkwv); break;
+  case 0: webkit_web_view_reload (wkwv); break;
+  case 1: webkit_web_view_go_forward (wkwv); break;
+  }
+#elif defined NS_IMPL_COCOA
+  nsxwidget_webkit_goto_history (xw, XFIXNAT (rel_pos));
+#endif
+  return Qnil;
+}
+
 DEFUN ("xwidget-webkit-zoom",
        Fxwidget_webkit_zoom, Sxwidget_webkit_zoom,
        2, 2, 0,
@@ -1145,7 +1196,10 @@ syms_of_xwidget (void)
   defsubr (&Sxwidget_query_on_exit_flag);
   defsubr (&Sset_xwidget_query_on_exit_flag);
 
+  defsubr (&Sxwidget_webkit_uri);
+  defsubr (&Sxwidget_webkit_title);
   defsubr (&Sxwidget_webkit_goto_uri);
+  defsubr (&Sxwidget_webkit_goto_history);
   defsubr (&Sxwidget_webkit_zoom);
   defsubr (&Sxwidget_webkit_execute_script);
   DEFSYM (Qwebkit, "webkit");
-- 
2.17.2 (Apple Git-113)


[-- Attachment #4: 0003-Add-support-for-file-downloading-in-macOS-xwidget-we.patch --]
[-- Type: application/octet-stream, Size: 6459 bytes --]

From 7ea8c3184b5343ea177dc516d6fab0d98c9c57d9 Mon Sep 17 00:00:00 2001
From: Sungbin Jo <pcr910303@icloud.com>
Date: Fri, 26 Jul 2019 03:41:10 +0900
Subject: [PATCH 3/3] Add support for file downloading in macOS xwidget-webkit

Co-authored-by: Jaesup Kwak <veshboo@gmail.com>

* lisp/xwidget.el (xwidget-webkit-callback): Add case for
'response-callback' event.
(xwidget-webkit-download-dir): New variable.
(xwidget-webkit-save-as-file): New function.
* src/nsxwidget.m (XwWebView::decidePolicyForNavigationResponse):
Store download event.
* src/xwidget.c src/xwidget.h (store_xwidget_download_callback_event):
New function.
---
 etc/NEWS        |  4 ++++
 lisp/xwidget.el | 31 +++++++++++++++++++++++++++++++
 src/nsxwidget.m | 12 ++++++++++++
 src/xwidget.c   | 20 ++++++++++++++++++++
 src/xwidget.h   |  5 +++++
 5 files changed, 72 insertions(+)

diff --git a/etc/NEWS b/etc/NEWS
index f9a42f73be..c7f980f212 100644
--- a/etc/NEWS
+++ b/etc/NEWS
@@ -2469,6 +2469,10 @@ instances of xwidget webkit is not supported.
 
 *** New variable 'xwidget-webkit-enable-plugins'.
 
+** On macOS, downloading files from xwidget-webkit is supported.
+
+*** New variable 'xwidget-webkit-download-dir'.
+
 
 \f
 ----------------------------------------------------------------------
diff --git a/lisp/xwidget.el b/lisp/xwidget.el
index 584a894148..2e8bfa3a98 100644
--- a/lisp/xwidget.el
+++ b/lisp/xwidget.el
@@ -288,6 +288,12 @@ xwidget-webkit-callback
                    (xwidget-webkit-show-id-or-named-element
                     xwidget
                     (match-string 1 strarg)))))
+            ;; TODO: Response handling other than download.
+            ((eq xwidget-event-type 'download-callback)
+             (let ((url  (nth 3 last-input-event))
+                   (mime-type (nth 4 last-input-event))
+                   (file-name (nth 5 last-input-event)))
+               (xwidget-webkit-save-as-file url mime-type file-name)))
             ((eq xwidget-event-type 'javascript-callback)
              (let ((proc (nth 3 last-input-event))
                    (arg  (nth 4 last-input-event)))
@@ -308,6 +314,31 @@ xwidget-webkit-mode
   ;; Keep track of [vh]scroll when switching buffers
   (image-mode-setup-winprops))
 
+;;; Download, save as file.
+
+(defcustom xwidget-webkit-download-dir "~/Downloads/"
+  "Directory where download file saved."
+  :version "27.1"
+  :type 'file)
+
+(defun xwidget-webkit-save-as-file (url mime-type file-name)
+  "For XWIDGET webkit, save URL of MIME-TYPE to location specified by user.
+FILE-NAME combined with `xwidget-webkit-download-dir' is the default file name
+of the prompt when reading.  When the file name the user specified is a
+directory, URL is saved at the specified directory as FILE-NAME."
+  (let ((save-name (read-file-name
+                    (format "Save URL `%s' of type `%s' in file/directory: " url mime-type)
+                    xwidget-webkit-download-dir
+                    (when file-name
+                      (expand-file-name
+                       file-name
+                       xwidget-webkit-download-dir)))))
+    (if (file-directory-p save-name)
+        (setq save-name
+              (expand-file-name (file-name-nondirectory file-name) save-name)))
+    (setq xwidget-webkit-download-dir (file-name-directory save-name))
+    (url-copy-file url save-name t)))
+
 ;;; Bookmarks integration
 
 (defcustom xwidget-webkit-bookmark-jump-new-session nil
diff --git a/src/nsxwidget.m b/src/nsxwidget.m
index 87a10e34e0..8cac4b49ec 100644
--- a/src/nsxwidget.m
+++ b/src/nsxwidget.m
@@ -122,6 +122,18 @@ - (void)webView:(WKWebView *)webView
 decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
 decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
 {
+  if (!navigationResponse.canShowMIMEType)
+    {
+      NSString *url = navigationResponse.response.URL.absoluteString;
+      NSString *mimetype = navigationResponse.response.MIMEType;
+      NSString *filename = navigationResponse.response.suggestedFilename;
+      decisionHandler (WKNavigationResponsePolicyCancel);
+      store_xwidget_download_callback_event (self.xw,
+                                             url.UTF8String,
+                                             mimetype.UTF8String,
+                                             filename.UTF8String);
+      return;
+    }
   decisionHandler (WKNavigationResponsePolicyAllow);
 
   self.urlScriptBlocked[navigationResponse.response.URL] =
diff --git a/src/xwidget.c b/src/xwidget.c
index 15d909f51c..aa5470a419 100644
--- a/src/xwidget.c
+++ b/src/xwidget.c
@@ -268,6 +268,26 @@ store_xwidget_event_string (struct xwidget *xw, const char *eventname,
   kbd_buffer_store_event (&event);
 }
 
+void
+store_xwidget_download_callback_event (struct xwidget *xw,
+                                       const char *url,
+                                       const char *mimetype,
+                                       const char *filename)
+{
+  struct input_event event;
+  Lisp_Object xwl;
+  XSETXWIDGET (xwl, xw);
+  EVENT_INIT (event);
+  event.kind = XWIDGET_EVENT;
+  event.frame_or_window = Qnil;
+  event.arg = list5 (intern ("download-callback"),
+                     xwl,
+                     build_string (url),
+                     build_string (mimetype),
+                     build_string (filename));
+  kbd_buffer_store_event (&event);
+}
+
 void
 store_xwidget_js_callback_event (struct xwidget *xw,
                                  Lisp_Object proc,
diff --git a/src/xwidget.h b/src/xwidget.h
index 73d8bbd540..11260f98b1 100644
--- a/src/xwidget.h
+++ b/src/xwidget.h
@@ -155,6 +155,11 @@ #define XG_XWIDGET_VIEW "emacs_xwidget_view"
                                  const char *eventname,
                                  const char *eventstr);
 
+void store_xwidget_download_callback_event (struct xwidget *xw,
+                                            const char *url,
+                                            const char *mimetype,
+                                            const char *filename);
+
 void store_xwidget_js_callback_event (struct xwidget *xw,
                                       Lisp_Object proc,
                                       Lisp_Object argument);
-- 
2.17.2 (Apple Git-113)


^ permalink raw reply related	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-25 18:51       ` 조성빈
@ 2019-07-26  5:55         ` Eli Zaretskii
  2019-07-27  2:48           ` Richard Stallman
  2019-07-27 10:41         ` Eli Zaretskii
  2019-07-29 20:26         ` Alan Third
  2 siblings, 1 reply; 49+ messages in thread
From: Eli Zaretskii @ 2019-07-26  5:55 UTC (permalink / raw)
  To: 조성빈; +Cc: alan, emacs-devel

> From: 조성빈 <pcr910303@icloud.com>
> Date: Fri, 26 Jul 2019 03:51:11 +0900
> Cc: alan@idiocy.org,
>  emacs-devel@gnu.org
> 
> Hello, I have prepared three patches to apply on master.
> Can anyone review these?

They are in my queue, but please be a bit more patient, I don't always
have time to review such large patches immediately.

Thanks.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-26  5:55         ` Eli Zaretskii
@ 2019-07-27  2:48           ` Richard Stallman
  2019-07-27  8:38             ` Eli Zaretskii
  0 siblings, 1 reply; 49+ messages in thread
From: Richard Stallman @ 2019-07-27  2:48 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: alan, pcr910303, emacs-devel

[[[ To any NSA and FBI agents reading my email: please consider    ]]]
[[[ whether defending the US Constitution against all enemies,     ]]]
[[[ foreign or domestic, requires you to follow Snowden's example. ]]]

  > They are in my queue, but please be a bit more patient, I don't always
  > have time to review such large patches immediately.

This is why I wish another experienced developer would offer to be
co-maintainer.  Eli is doing a lot of work, and it would be good
for another to share it.

-- 
Dr Richard Stallman
President, Free Software Foundation (https://gnu.org, https://fsf.org)
Internet Hall-of-Famer (https://internethalloffame.org)





^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-27  2:48           ` Richard Stallman
@ 2019-07-27  8:38             ` Eli Zaretskii
  0 siblings, 0 replies; 49+ messages in thread
From: Eli Zaretskii @ 2019-07-27  8:38 UTC (permalink / raw)
  To: rms; +Cc: emacs-devel

> From: Richard Stallman <rms@gnu.org>
> Cc: pcr910303@icloud.com, alan@idiocy.org, emacs-devel@gnu.org
> Date: Fri, 26 Jul 2019 22:48:13 -0400
> 
>   > They are in my queue, but please be a bit more patient, I don't always
>   > have time to review such large patches immediately.
> 
> This is why I wish another experienced developer would offer to be
> co-maintainer.  Eli is doing a lot of work, and it would be good
> for another to share it.

It would be fine with me to have another co-maintainer, but people can
(and do) review patches even without that.  There are a few people who
do that routinely already, and I'm very grateful to all of them.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-25 18:51       ` 조성빈
  2019-07-26  5:55         ` Eli Zaretskii
@ 2019-07-27 10:41         ` Eli Zaretskii
  2019-07-27 12:35           ` 조성빈
  2019-07-29 20:26         ` Alan Third
  2 siblings, 1 reply; 49+ messages in thread
From: Eli Zaretskii @ 2019-07-27 10:41 UTC (permalink / raw)
  To: 조성빈; +Cc: alan, emacs-devel

> From: 조성빈 <pcr910303@icloud.com>
> Date: Fri, 26 Jul 2019 03:51:11 +0900
> Cc: alan@idiocy.org,
>  emacs-devel@gnu.org
> 
> Hello, I have prepared three patches to apply on master.

Thanks.  Alan, could you please review the NS specific parts?

> diff --git a/etc/NEWS b/etc/NEWS
> index 5313270411..52b49bab75 100644
> --- a/etc/NEWS
> +++ b/etc/NEWS
> @@ -2440,6 +2440,18 @@ was able to 'set' modifiers without the knowledge of the user.
>  ** On NS multicolor font display is enabled again since it is also
>  implemented in Emacs on free operating systems via Cairo drawing.
>  
> +** On macOS, Xwidget is now supported.
> +If Emacs was built with xwidget support, you can access the embedded
> +webkit browser with 'M-x xwidget-webkit-browse-url'.  Viewing two
> +instances of xwidget webkit is not supported.
> +
> +*** New functions for xwidget-webkit mode
> +'xwidget-webkit-clone-and-split-below',
> +'xwidget-webkit-clone-and-split-right'.
> +
> +*** New variable 'xwidget-webkit-enable-plugins'.

The last two entries are not specific to macOS, are they?  If so, they
should be in the general sections of NEWS.

> diff --git a/etc/TODO b/etc/TODO
> index a065763933..bda1cf8f9e 100644
> --- a/etc/TODO
> +++ b/etc/TODO
> @@ -640,15 +640,6 @@ from the emacsclient process.
>  
>  This sections contains features found in other official Emacs ports.
>  
> -**** Support for xwidgets
> -
> -Emacs 25 has support for xwidgets, a system to include operating
> -system components into an Emacs buffer.  The components range from
> -simple buttons to webkit (effectively, a web browser).
> -
> -Currently, xwidgets works only for the gtk+ framework but it is
> -designed to be compatible with multiple Emacs ports.

The MS-Windows and non-GTK builds of Emacs on X still don't support
xwidgets, so I think this entry should not be deleted in its entirety,
it should still say that some configurations don't support xwidgets.

> +(defun xwidget-webkit-clone-and-split-below ()
> +  "Clone current URL into a new widget place in new window below.
> +Get the URL of current session, then browse to the URL
> +in `split-window-below' with a new xwidget webkit session."

The second sentence should be reworded:

  Get the URL of current session, then browse that URL in another
  window after splitting the selected window horizontally.

> +(defun xwidget-webkit-clone-and-split-right ()
> +  "Clone current URL into a new widget place in new window right.
> +Get the URL of current session, then browse to the URL
> +in `split-window-right' with a new xwidget webkit session."

Same here (but use "vertically" instead of "horizontally").

>  (defvar bookmark-make-record-function)
> +(when (memq window-system '(mac ns))
> +  (defvar xwidget-webkit-enable-plugins nil
> +    "Enable plugins for xwidget webkit.
> +If non-nil, plugins are enabled.  Otherwise, disabled."))

It is better to have this defvar unconditionally, and tell in the doc
string that it only has effect on macOS.

> @@ -228,13 +247,14 @@ offscreen_damage_event (GtkWidget *widget, GdkEvent *event,
>    if (GTK_IS_WIDGET (xv_widget))
>      gtk_widget_queue_draw (GTK_WIDGET (xv_widget));
>    else
> -    printf ("Warning, offscreen_damage_event received invalid xv pointer:%p\n",
> -            xv_widget);
> +    message ("Warning, offscreen_damage_event received invalid xv pointer:%p\n",
> +             xv_widget);

Why replace printf by message?

> +#elif defined NS_IMPL_COCOA
> +              nsxwidget_resize_view(xv, xw->width, xw->height);
                                      ^
Space before the opening parenthesis is missing.

> +*** Functions 'xwidget-webkit-scroll-up', 'xwidget-webkit-scroll-down'
> +now supports scrolling arbitrary pixel values.  It now treats the
       ^^^^^^^^           ^^^^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^
"support" (plural) "by arbitrary pixel values".  "They now treat" (plural).

> +(defun xwidget-webkit-scroll-up-line (&optional n)
> +  "Scroll webkit up by N lines.
> +The height of line is calculated with `window-font-height'.
> +Stop if the bottom edge of the page is reached.
> +If N is omitted or nil, scroll up by one line."
> +  (interactive "p")
> +  (xwidget-webkit-scroll-up (* n (window-font-height))))
> +
> +(defun xwidget-webkit-scroll-down-line (&optional n)
> +  "Scroll webkit down by N lines.
> +The height of line is calculated with `window-font-height'.
> +Stop if the top edge of the page is reached.
> +If N is omitted or nil, scroll down by one line."
> +  (interactive "p")
> +  (xwidget-webkit-scroll-down (* n (window-font-height))))
> +
> +(defun xwidget-webkit-scroll-forward (&optional n)
> +  "Scroll webkit horizontally by N chars.
> +The width of char is calculated with `window-font-width'.
> +If N is ommited or nil, scroll forwards by one char."
> +  (interactive "p")
>    (xwidget-webkit-execute-script
>     (xwidget-webkit-current-session)
> -   "window.scrollBy(50, 0);"))
> -
> -(defun xwidget-webkit-scroll-backward ()
> -  "Scroll webkit backwards."
> -  (interactive)
> +   (format "window.scrollBy(%d, 0);"
> +           (* n (window-font-width)))))
> +
> +(defun xwidget-webkit-scroll-backward (&optional n)
> +  "Scroll webkit back by N chars.
> +The width of char is calculated with `window-font-width'.
> +If N is ommited or nil, scroll backwards by one char."
> +  (interactive "p")

These commands should say in their doc strings that interactively N is
the prefix numeric argument.

> diff --git a/etc/NEWS b/etc/NEWS
> index f9a42f73be..c7f980f212 100644
> --- a/etc/NEWS
> +++ b/etc/NEWS
> @@ -2469,6 +2469,10 @@ instances of xwidget webkit is not supported.
>  
>  *** New variable 'xwidget-webkit-enable-plugins'.
>  
> +** On macOS, downloading files from xwidget-webkit is supported.
> +
> +*** New variable 'xwidget-webkit-download-dir'.

The macOS-specific part of this should be in the non-free OS part of
NEWS.

> +(defun xwidget-webkit-save-as-file (url mime-type file-name)
> +  "For XWIDGET webkit, save URL of MIME-TYPE to location specified by user.
> +FILE-NAME combined with `xwidget-webkit-download-dir' is the default file name
> +of the prompt when reading.  When the file name the user specified is a
> +directory, URL is saved at the specified directory as FILE-NAME."

The last sentence is unclear: what will be the directory where the URL
will be saved, and what will be the name of the saved file in that
directory?



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-27 10:41         ` Eli Zaretskii
@ 2019-07-27 12:35           ` 조성빈
  2019-07-27 13:03             ` Eli Zaretskii
  0 siblings, 1 reply; 49+ messages in thread
From: 조성빈 @ 2019-07-27 12:35 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: alan, emacs-devel


2019. 7. 27. 오후 7:41, Eli Zaretskii <eliz@gnu.org> 작성:

>> From: 조성빈 <pcr910303@icloud.com>
>> Date: Fri, 26 Jul 2019 03:51:11 +0900
>> Cc: alan@idiocy.org,
>> emacs-devel@gnu.org
>> diff --git a/etc/NEWS b/etc/NEWS
>> index 5313270411..52b49bab75 100644
>> --- a/etc/NEWS
>> +++ b/etc/NEWS
>> @@ -2440,6 +2440,18 @@ was able to 'set' modifiers without the knowledge of the user.
>> ** On NS multicolor font display is enabled again since it is also
>> implemented in Emacs on free operating systems via Cairo drawing.
>> 
>> +** On macOS, Xwidget is now supported.
>> +If Emacs was built with xwidget support, you can access the embedded
>> +webkit browser with 'M-x xwidget-webkit-browse-url'.  Viewing two
>> +instances of xwidget webkit is not supported.
>> +
>> +*** New functions for xwidget-webkit mode
>> +'xwidget-webkit-clone-and-split-below',
>> +'xwidget-webkit-clone-and-split-right'.
>> +
>> +*** New variable 'xwidget-webkit-enable-plugins'.
> 
> The last two entries are not specific to macOS, are they?  If so, they
> should be in the general sections of NEWS.

Ok, will do.

>> diff --git a/etc/TODO b/etc/TODO
>> index a065763933..bda1cf8f9e 100644
>> --- a/etc/TODO
>> +++ b/etc/TODO
>> @@ -640,15 +640,6 @@ from the emacsclient process.
>> 
>> This sections contains features found in other official Emacs ports.
>> 
>> -**** Support for xwidgets
>> -
>> -Emacs 25 has support for xwidgets, a system to include operating
>> -system components into an Emacs buffer.  The components range from
>> -simple buttons to webkit (effectively, a web browser).
>> -
>> -Currently, xwidgets works only for the gtk+ framework but it is
>> -designed to be compatible with multiple Emacs ports.
> 
> The MS-Windows and non-GTK builds of Emacs on X still don't support
> xwidgets, so I think this entry should not be deleted in its entirety,
> it should still say that some configurations don't support xwidgets.

(I’m currently on my phone so I can’t really check but) I recall this part of the checklist was specific to the NS port? 

>> +(defun xwidget-webkit-clone-and-split-below ()
>> +  "Clone current URL into a new widget place in new window below.
>> +Get the URL of current session, then browse to the URL
>> +in `split-window-below' with a new xwidget webkit session."
> 
> The second sentence should be reworded:
> 
>  Get the URL of current session, then browse that URL in another
>  window after splitting the selected window horizontally.

Ok, will do.

>> +(defun xwidget-webkit-clone-and-split-right ()
>> +  "Clone current URL into a new widget place in new window right.
>> +Get the URL of current session, then browse to the URL
>> +in `split-window-right' with a new xwidget webkit session."
> 
> Same here (but use "vertically" instead of "horizontally").

Ok, will do.

>> (defvar bookmark-make-record-function)
>> +(when (memq window-system '(mac ns))
>> +  (defvar xwidget-webkit-enable-plugins nil
>> +    "Enable plugins for xwidget webkit.
>> +If non-nil, plugins are enabled.  Otherwise, disabled."))
> 
> It is better to have this defvar unconditionally, and tell in the doc
> string that it only has effect on macOS.

Ok, will do.

>> @@ -228,13 +247,14 @@ offscreen_damage_event (GtkWidget *widget, GdkEvent *event,
>>   if (GTK_IS_WIDGET (xv_widget))
>>     gtk_widget_queue_draw (GTK_WIDGET (xv_widget));
>>   else
>> -    printf ("Warning, offscreen_damage_event received invalid xv pointer:%p\n",
>> -            xv_widget);
>> +    message ("Warning, offscreen_damage_event received invalid xv pointer:%p\n",
>> +             xv_widget);
> 
> Why replace printf by message?

Well, there wasn’t a particular problem, but it looked like that message was more used for warnings or errors. Should I revert it? 

>> +#elif defined NS_IMPL_COCOA
>> +              nsxwidget_resize_view(xv, xw->width, xw->height);
>                                      ^
> Space before the opening parenthesis is missing.

Ok, will fix.

>> +*** Functions 'xwidget-webkit-scroll-up', 'xwidget-webkit-scroll-down'
>> +now supports scrolling arbitrary pixel values.  It now treats the
>       ^^^^^^^^           ^^^^^^^^^^^^^^^^^^^^^^   ^^^^^^^^^^^^^
> "support" (plural) "by arbitrary pixel values".  "They now treat" (plural).

Ok, will fix.

>> +(defun xwidget-webkit-scroll-up-line (&optional n)
>> +  "Scroll webkit up by N lines.
>> +The height of line is calculated with `window-font-height'.
>> +Stop if the bottom edge of the page is reached.
>> +If N is omitted or nil, scroll up by one line."
>> +  (interactive "p")
>> +  (xwidget-webkit-scroll-up (* n (window-font-height))))
>> +
>> +(defun xwidget-webkit-scroll-down-line (&optional n)
>> +  "Scroll webkit down by N lines.
>> +The height of line is calculated with `window-font-height'.
>> +Stop if the top edge of the page is reached.
>> +If N is omitted or nil, scroll down by one line."
>> +  (interactive "p")
>> +  (xwidget-webkit-scroll-down (* n (window-font-height))))
>> +
>> +(defun xwidget-webkit-scroll-forward (&optional n)
>> +  "Scroll webkit horizontally by N chars.
>> +The width of char is calculated with `window-font-width'.
>> +If N is ommited or nil, scroll forwards by one char."
>> +  (interactive "p")
>>   (xwidget-webkit-execute-script
>>    (xwidget-webkit-current-session)
>> -   "window.scrollBy(50, 0);"))
>> -
>> -(defun xwidget-webkit-scroll-backward ()
>> -  "Scroll webkit backwards."
>> -  (interactive)
>> +   (format "window.scrollBy(%d, 0);"
>> +           (* n (window-font-width)))))
>> +
>> +(defun xwidget-webkit-scroll-backward (&optional n)
>> +  "Scroll webkit back by N chars.
>> +The width of char is calculated with `window-font-width'.
>> +If N is ommited or nil, scroll backwards by one char."
>> +  (interactive "p")
> 
> These commands should say in their doc strings that interactively N is
> the prefix numeric argument.

Ok, will do.

>> diff --git a/etc/NEWS b/etc/NEWS
>> index f9a42f73be..c7f980f212 100644
>> --- a/etc/NEWS
>> +++ b/etc/NEWS
>> @@ -2469,6 +2469,10 @@ instances of xwidget webkit is not supported.
>> 
>> *** New variable 'xwidget-webkit-enable-plugins'.
>> 
>> +** On macOS, downloading files from xwidget-webkit is supported.
>> +
>> +*** New variable 'xwidget-webkit-download-dir'.
> 
> The macOS-specific part of this should be in the non-free OS part of
> NEWS.

Ok, will fix.

>> +(defun xwidget-webkit-save-as-file (url mime-type file-name)
>> +  "For XWIDGET webkit, save URL of MIME-TYPE to location specified by user.
>> +FILE-NAME combined with `xwidget-webkit-download-dir' is the default file name
>> +of the prompt when reading.  When the file name the user specified is a
>> +directory, URL is saved at the specified directory as FILE-NAME."
> 
> The last sentence is unclear: what will be the directory where the URL
> will be saved, and what will be the name of the saved file in that
> directory?

Well, it was meaning that the URL will be saved at the directory the user specified in the prompt with the name FILE-NAME.

I’m not sure how I should reword it due to my  poor English skills; can you give me some suggestions? 



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-27 12:35           ` 조성빈
@ 2019-07-27 13:03             ` Eli Zaretskii
  2019-07-29 17:08               ` 조성빈
  0 siblings, 1 reply; 49+ messages in thread
From: Eli Zaretskii @ 2019-07-27 13:03 UTC (permalink / raw)
  To: 조성빈; +Cc: alan, emacs-devel

> From: 조성빈 <pcr910303@icloud.com>
> Date: Sat, 27 Jul 2019 21:35:07 +0900
> Cc: alan@idiocy.org, emacs-devel@gnu.org
> 
> >> +(defun xwidget-webkit-save-as-file (url mime-type file-name)
> >> +  "For XWIDGET webkit, save URL of MIME-TYPE to location specified by user.
> >> +FILE-NAME combined with `xwidget-webkit-download-dir' is the default file name
> >> +of the prompt when reading.  When the file name the user specified is a
> >> +directory, URL is saved at the specified directory as FILE-NAME."
> > 
> > The last sentence is unclear: what will be the directory where the URL
> > will be saved, and what will be the name of the saved file in that
> > directory?
> 
> Well, it was meaning that the URL will be saved at the directory the user specified in the prompt with the name FILE-NAME.
> 
> I’m not sure how I should reword it due to my  poor English skills; can you give me some suggestions? 

If you show me an example of using this command, and the results -- in
what directory and under what base name will the URL be saved -- then
I will be able to suggest a better wording.

Thanks.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-27 13:03             ` Eli Zaretskii
@ 2019-07-29 17:08               ` 조성빈
  2019-08-03 10:03                 ` Eli Zaretskii
  0 siblings, 1 reply; 49+ messages in thread
From: 조성빈 @ 2019-07-29 17:08 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: alan, emacs-devel

> 2019. 7. 27. 오후 10:03, Eli Zaretskii <eliz@gnu.org> 작성:
> 
>> From: 조성빈 <pcr910303@icloud.com>
>> Date: Sat, 27 Jul 2019 21:35:07 +0900
>> Cc: alan@idiocy.org, emacs-devel@gnu.org
>> 
>>>> +(defun xwidget-webkit-save-as-file (url mime-type file-name)
>>>> +  "For XWIDGET webkit, save URL of MIME-TYPE to location specified by user.
>>>> +FILE-NAME combined with `xwidget-webkit-download-dir' is the default file name
>>>> +of the prompt when reading.  When the file name the user specified is a
>>>> +directory, URL is saved at the specified directory as FILE-NAME."
>>> 
>>> The last sentence is unclear: what will be the directory where the URL
>>> will be saved, and what will be the name of the saved file in that
>>> directory?
>> 
>> Well, it was meaning that the URL will be saved at the directory the user specified in the prompt with the name FILE-NAME.
>> 
>> I’m not sure how I should reword it due to my  poor English skills; can you give me some suggestions? 
> 
> If you show me an example of using this command, and the results -- in
> what directory and under what base name will the URL be saved -- then
> I will be able to suggest a better wording.

Sorry for the delay; I was busy for a few days that I couldn't open my mailbox.

Well, while I was trying to give examples, I think I wrote a clearer version of the docstring:
"Save URL of MIME-TYPE as file specified by user.
When the user specifies a directory, URL is saved with the name FILE-NAME in the
 specified directory.  The default file name when reading is FILE-NAME expanded
 with `xwidget-webkit-download-dir'."

May I ask if this is more clear than before?

> Thanks.





^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-25 18:51       ` 조성빈
  2019-07-26  5:55         ` Eli Zaretskii
  2019-07-27 10:41         ` Eli Zaretskii
@ 2019-07-29 20:26         ` Alan Third
  2019-07-29 21:02           ` Stefan Monnier
  2019-07-30 15:33           ` 조성빈
  2 siblings, 2 replies; 49+ messages in thread
From: Alan Third @ 2019-07-29 20:26 UTC (permalink / raw)
  To: 조성빈; +Cc: Eli Zaretskii, emacs-devel

On Fri, Jul 26, 2019 at 03:51:11AM +0900, 조성빈 wrote:
> Hello, I have prepared three patches to apply on master.
> Can anyone review these?

This error message is extremely annoying:

You can’t share an xwidget (webkit2) among windows. [47 times]
mwheel-scroll: Beginning of buffer
You can’t share an xwidget (webkit2) among windows. [87 times]
completing-read-default: Command attempted to use minibuffer while in minibuffer
You can’t share an xwidget (webkit2) among windows. [4 times]
Quit [4 times]
You can’t share an xwidget (webkit2) among windows. [121 times]

It blocks the minibuffer so it’s impossible to see what you’re typing
when you do M-x or C-x b and so on. Is it possible to limit it to only
when an actual xwidget buffer is selected?

Strange things also happen if you have the same xwidget buffer
displayed in two windows and then resize the one that doesn’t display
the xwidget. It looks as though the wrong window is being used to
calculate the xwidget’s size.

The big explanatory comment at the top of nsxwidget.m could do with
being rewritten. It’s got a few typos and I find hard to understand. I
think I get the gist of it, but I’m not 100% sure.

Is this something we’re going to have to update over time?

      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";

Anyway, the code contains two calls to
evaluateJavaScript:completionHandler: which is a problem as we’re
banned from using ObjC blocks, and the completion handler is an ObjC
block. Unless GCC supports them now, which I doubt.

I don’t see any alternatives in the Apple documentation.

-- 
Alan Third



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-29 20:26         ` Alan Third
@ 2019-07-29 21:02           ` Stefan Monnier
  2019-07-30 15:35             ` 조성빈
  2019-07-30 15:33           ` 조성빈
  1 sibling, 1 reply; 49+ messages in thread
From: Stefan Monnier @ 2019-07-29 21:02 UTC (permalink / raw)
  To: Alan Third; +Cc: Eli Zaretskii, 조성빈, emacs-devel

> This error message is extremely annoying:
> You can’t share an xwidget (webkit2) among windows. [47 times]

It shouldn't be a message in the echo-area.  Instead, it should be a
text displayed instead of the xwidget.


        Stefan




^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-29 20:26         ` Alan Third
  2019-07-29 21:02           ` Stefan Monnier
@ 2019-07-30 15:33           ` 조성빈
  2019-07-30 19:12             ` Juri Linkov
  2019-07-31 19:56             ` Alan Third
  1 sibling, 2 replies; 49+ messages in thread
From: 조성빈 @ 2019-07-30 15:33 UTC (permalink / raw)
  To: Alan Third; +Cc: Eli Zaretskii, emacs-devel

> 2019. 7. 30. 오전 5:26, Alan Third <alan@idiocy.org> 작성:
> 
> On Fri, Jul 26, 2019 at 03:51:11AM +0900, 조성빈 wrote:
>> Hello, I have prepared three patches to apply on master.
>> Can anyone review these?
> 
> This error message is extremely annoying:
> 
> You can’t share an xwidget (webkit2) among windows. [47 times]
> mwheel-scroll: Beginning of buffer
> You can’t share an xwidget (webkit2) among windows. [87 times]
> completing-read-default: Command attempted to use minibuffer while in minibuffer
> You can’t share an xwidget (webkit2) among windows. [4 times]
> Quit [4 times]
> You can’t share an xwidget (webkit2) among windows. [121 times]
> 
> It blocks the minibuffer so it’s impossible to see what you’re typing
> when you do M-x or C-x b and so on. Is it possible to limit it to only
> when an actual xwidget buffer is selected?

Wow, I found I just got used to that before I started to maintain the patch and never even thought to fix that. I remember this was annoying to hell to me too :-(. I'll try to find a solution.

> Strange things also happen if you have the same xwidget buffer
> displayed in two windows and then resize the one that doesn’t display
> the xwidget. It looks as though the wrong window is being used to
> calculate the xwidget’s size.

Hmm, maybe this is because the portion of xwidget in the window isn't redrawn? I'm not sure how I should tackle the issue though. :-(

> The big explanatory comment at the top of nsxwidget.m could do with
> being rewritten. It’s got a few typos and I find hard to understand. I
> think I get the gist of it, but I’m not 100% sure.

Ok, I'll try to clarify it.

> Is this something we’re going to have to update over time?
> 
>      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";

I removed this part.

> Anyway, the code contains two calls to
> evaluateJavaScript:completionHandler: which is a problem as we’re
> banned from using ObjC blocks, and the completion handler is an ObjC
> block. Unless GCC supports them now, which I doubt.

Does that mean this patch can never get merged until gcc supports blocks?

> I don’t see any alternatives in the Apple documentation.






^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-29 21:02           ` Stefan Monnier
@ 2019-07-30 15:35             ` 조성빈
  2019-07-30 19:25               ` Stefan Monnier
  0 siblings, 1 reply; 49+ messages in thread
From: 조성빈 @ 2019-07-30 15:35 UTC (permalink / raw)
  To: Stefan Monnier; +Cc: Alan Third, Eli Zaretskii, emacs-devel

> 2019. 7. 30. 오전 6:02, Stefan Monnier <monnier@iro.umontreal.ca> 작성:
> 
>> This error message is extremely annoying:
>> You can’t share an xwidget (webkit2) among windows. [47 times]
> 
> It shouldn't be a message in the echo-area.  Instead, it should be a
> text displayed instead of the xwidget.

Hmm, how can that be possible? Is it possible to display text in the same buffer excluding a specific window?

>        Stefan
> 
> 





^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-30 15:33           ` 조성빈
@ 2019-07-30 19:12             ` Juri Linkov
  2019-07-31 15:55               ` 조성빈
  2019-07-31 19:56             ` Alan Third
  1 sibling, 1 reply; 49+ messages in thread
From: Juri Linkov @ 2019-07-30 19:12 UTC (permalink / raw)
  To: 조성빈; +Cc: Alan Third, Eli Zaretskii, emacs-devel

>> Is this something we’re going to have to update over time?
>>
>>      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";
>
> I removed this part.

The User-Agent string should be automatically constructed
from variables containing the current Emacs version,
and package version like for example is constructed for eww,
so server software can collect statistics about browsers
to see what versions of eww or xwidgets were used to access pages.
The first part beginning with "Mozilla/5.0 (compatible; ..."
could be retained to request compatible Web pages.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-30 15:35             ` 조성빈
@ 2019-07-30 19:25               ` Stefan Monnier
  2019-07-31 15:52                 ` 조성빈
  0 siblings, 1 reply; 49+ messages in thread
From: Stefan Monnier @ 2019-07-30 19:25 UTC (permalink / raw)
  To: 조성빈; +Cc: Alan Third, Eli Zaretskii, emacs-devel

> Hmm, how can that be possible? Is it possible to display text in the same
> buffer excluding a specific window?

I don't know enough about the redisplay engine to give a precise
solution, but I'd expect that you can make the code insert appropriate
glyphs into the glyph matrix.  In the worst case, instead of text (which
requires several glyphs) it could insert a single "glyph" consisting in
an XPM image (which would indicate the error).


        Stefan




^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-30 19:25               ` Stefan Monnier
@ 2019-07-31 15:52                 ` 조성빈
  0 siblings, 0 replies; 49+ messages in thread
From: 조성빈 @ 2019-07-31 15:52 UTC (permalink / raw)
  To: Stefan Monnier; +Cc: Alan Third, Eli Zaretskii, emacs-devel

> 2019. 7. 31. 오전 4:25, Stefan Monnier <monnier@iro.umontreal.ca> 작성:
> 
>> Hmm, how can that be possible? Is it possible to display text in the same buffer excluding a specific window?
> 
> I don't know enough about the redisplay engine to give a precise solution

As me... :-( I really should be reading the display code.

> but I'd expect that you can make the code insert appropriate glyphs into the glyph matrix.

Hmm, I'll try (but I would appreciate some pointers to start).

>  In the worst case, instead of text (which requires several glyphs) it could insert a single "glyph" consisting in an XPM image (which would indicate the error).
> 
>        Stefan
> 




^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-30 19:12             ` Juri Linkov
@ 2019-07-31 15:55               ` 조성빈
  0 siblings, 0 replies; 49+ messages in thread
From: 조성빈 @ 2019-07-31 15:55 UTC (permalink / raw)
  To: Juri Linkov; +Cc: Alan Third, Eli Zaretskii, emacs-devel

> 2019. 7. 31. 오전 4:12, Juri Linkov <juri@linkov.net> 작성:
> 
>>> Is this something we’re going to have to update over time?
>>> 
>>>     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";
>> 
>> I removed this part.
> 
> The User-Agent string should be automatically constructed
> from variables containing the current Emacs version,
> and package version like for example is constructed for eww,
> so server software can collect statistics about browsers
> to see what versions of eww or xwidgets were used to access pages.
> The first part beginning with "Mozilla/5.0 (compatible; ..."
> could be retained to request compatible Web pages.

I remember the User-Agent string behaving strange some time ago, but I believe removing will work fine, as the current User-Agent accurately describes the Webkit version compiled with Emacs. I'm not sure if constructing another User-Agent specially for Emacs is a good choice, compatibility with the web will be an issue (as that will be the main reason using xwidget-webkit)


^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-30 15:33           ` 조성빈
  2019-07-30 19:12             ` Juri Linkov
@ 2019-07-31 19:56             ` Alan Third
  2019-08-01  2:35               ` Eli Zaretskii
  1 sibling, 1 reply; 49+ messages in thread
From: Alan Third @ 2019-07-31 19:56 UTC (permalink / raw)
  To: 조성빈; +Cc: Eli Zaretskii, emacs-devel

On Wed, Jul 31, 2019 at 12:33:36AM +0900, 조성빈 wrote:
> > 2019. 7. 30. 오전 5:26, Alan Third <alan@idiocy.org> 작성:
> >
> > Anyway, the code contains two calls to
> > evaluateJavaScript:completionHandler: which is a problem as we’re
> > banned from using ObjC blocks, and the completion handler is an ObjC
> > block. Unless GCC supports them now, which I doubt.
> 
> Does that mean this patch can never get merged until gcc supports blocks?

We’ve had to remove blocks from Emacs code before because gcc doesn’t
support them, however Emacs can’t be built with gcc on recent (like,
the last decade or something) versions of macOS anyway. I don’t really
understand the logic, but it’s not my project.

I think it’s really up to Eli and/or RMS.
-- 
Alan Third



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-31 19:56             ` Alan Third
@ 2019-08-01  2:35               ` Eli Zaretskii
  2019-08-01  4:00                 ` 조성빈
  2019-08-01 21:39                 ` macOS/GCC support policy (was: [PATCH v5] Enable xwidgets on macOS) Alan Third
  0 siblings, 2 replies; 49+ messages in thread
From: Eli Zaretskii @ 2019-08-01  2:35 UTC (permalink / raw)
  To: Alan Third; +Cc: pcr910303, emacs-devel

> Date: Wed, 31 Jul 2019 20:56:33 +0100
> From: Alan Third <alan@idiocy.org>
> Cc: Eli Zaretskii <eliz@gnu.org>, emacs-devel@gnu.org
> 
> On Wed, Jul 31, 2019 at 12:33:36AM +0900, 조성빈 wrote:
> > > 2019. 7. 30. 오전 5:26, Alan Third <alan@idiocy.org> 작성:
> > >
> > > Anyway, the code contains two calls to
> > > evaluateJavaScript:completionHandler: which is a problem as we’re
> > > banned from using ObjC blocks, and the completion handler is an ObjC
> > > block. Unless GCC supports them now, which I doubt.
> > 
> > Does that mean this patch can never get merged until gcc supports blocks?
> 
> We’ve had to remove blocks from Emacs code before because gcc doesn’t
> support them, however Emacs can’t be built with gcc on recent (like,
> the last decade or something) versions of macOS anyway. I don’t really
> understand the logic, but it’s not my project.
> 
> I think it’s really up to Eli and/or RMS.

I don't think I understand the issue well enough to say anything
intelligent.  What are "ObjC blocks", and why this patch cannot do
without them?



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-08-01  2:35               ` Eli Zaretskii
@ 2019-08-01  4:00                 ` 조성빈
  2019-08-02  0:47                   ` Richard Stallman
  2019-08-01 21:39                 ` macOS/GCC support policy (was: [PATCH v5] Enable xwidgets on macOS) Alan Third
  1 sibling, 1 reply; 49+ messages in thread
From: 조성빈 @ 2019-08-01  4:00 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: Alan Third, emacs-devel

> 2019. 8. 1. 오전 11:35, Eli Zaretskii <eliz@gnu.org> 작성:
> 
>> Date: Wed, 31 Jul 2019 20:56:33 +0100
>> From: Alan Third <alan@idiocy.org>
>> Cc: Eli Zaretskii <eliz@gnu.org>, emacs-devel@gnu.org
>> 
>> On Wed, Jul 31, 2019 at 12:33:36AM +0900, 조성빈 wrote:
>>>> 2019. 7. 30. 오전 5:26, Alan Third <alan@idiocy.org> 작성:
>>>> 
>>>> Anyway, the code contains two calls to
>>>> evaluateJavaScript:completionHandler: which is a problem as we’re
>>>> banned from using ObjC blocks, and the completion handler is an ObjC
>>>> block. Unless GCC supports them now, which I doubt.
>>> 
>>> Does that mean this patch can never get merged until gcc supports blocks?
>> 
>> We’ve had to remove blocks from Emacs code before because gcc doesn’t
>> support them, however Emacs can’t be built with gcc on recent (like,
>> the last decade or something) versions of macOS anyway. I don’t really
>> understand the logic, but it’s not my project.
>> 
>> I think it’s really up to Eli and/or RMS.
> 
> I don't think I understand the issue well enough to say anything
> intelligent.  What are "ObjC blocks",

"ObjC blocks" are anonymous functions that are used to pass arbitrary code between methods or to execute code as a callback within a method. It captures the surrounding state (it's a closure).

> and why this patch cannot do
> without them?

The WebKit API(evaluateJavaScript:completionHandler:) to execute arbitrary JS (and get the value) mandates the use of blocks.


^ permalink raw reply	[flat|nested] 49+ messages in thread

* macOS/GCC support policy (was: [PATCH v5] Enable xwidgets on macOS)
  2019-08-01  2:35               ` Eli Zaretskii
  2019-08-01  4:00                 ` 조성빈
@ 2019-08-01 21:39                 ` Alan Third
  2019-08-02  2:22                   ` Noam Postavsky
  2019-08-02  6:56                   ` macOS/GCC support policy Eli Zaretskii
  1 sibling, 2 replies; 49+ messages in thread
From: Alan Third @ 2019-08-01 21:39 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: pcr910303, emacs-devel

On Thu, Aug 01, 2019 at 05:35:33AM +0300, Eli Zaretskii wrote:
> > Date: Wed, 31 Jul 2019 20:56:33 +0100
> > From: Alan Third <alan@idiocy.org>
> > Cc: Eli Zaretskii <eliz@gnu.org>, emacs-devel@gnu.org
> > 
> > On Wed, Jul 31, 2019 at 12:33:36AM +0900, 조성빈 wrote:
> > > > 2019. 7. 30. 오전 5:26, Alan Third <alan@idiocy.org> 작성:
> > > >
> > > > Anyway, the code contains two calls to
> > > > evaluateJavaScript:completionHandler: which is a problem as we’re
> > > > banned from using ObjC blocks, and the completion handler is an ObjC
> > > > block. Unless GCC supports them now, which I doubt.
> > > 
> > > Does that mean this patch can never get merged until gcc supports blocks?
> > 
> > We’ve had to remove blocks from Emacs code before because gcc doesn’t
> > support them, however Emacs can’t be built with gcc on recent (like,
> > the last decade or something) versions of macOS anyway. I don’t really
> > understand the logic, but it’s not my project.
> > 
> > I think it’s really up to Eli and/or RMS.
> 
> I don't think I understand the issue well enough to say anything
> intelligent.  What are "ObjC blocks", and why this patch cannot do
> without them?

I found the previous thread about removing them from macfont.m:

    https://lists.gnu.org/archive/html/bug-gnu-emacs/2017-12/msg00301.html

-- 
Alan Third



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-08-01  4:00                 ` 조성빈
@ 2019-08-02  0:47                   ` Richard Stallman
  2019-08-02  7:02                     ` Eli Zaretskii
  0 siblings, 1 reply; 49+ messages in thread
From: Richard Stallman @ 2019-08-02  0:47 UTC (permalink / raw)
  To: 조성빈
  Cc: eliz, alan, emacs-devel

[[[ To any NSA and FBI agents reading my email: please consider    ]]]
[[[ whether defending the US Constitution against all enemies,     ]]]
[[[ foreign or domestic, requires you to follow Snowden's example. ]]]

  > "ObjC blocks" are anonymous functions that are used to pass
  > arbitrary code between methods or to execute code as a callback
  > within a method. It captures the surrounding state (it's a
  > closure).

In GNU C, I implemented nested functions, with names.
Anonymous nested functions should not take much extra work.

-- 
Dr Richard Stallman
President, Free Software Foundation (https://gnu.org, https://fsf.org)
Internet Hall-of-Famer (https://internethalloffame.org)





^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy (was: [PATCH v5] Enable xwidgets on macOS)
  2019-08-01 21:39                 ` macOS/GCC support policy (was: [PATCH v5] Enable xwidgets on macOS) Alan Third
@ 2019-08-02  2:22                   ` Noam Postavsky
  2019-08-02  6:56                   ` macOS/GCC support policy Eli Zaretskii
  1 sibling, 0 replies; 49+ messages in thread
From: Noam Postavsky @ 2019-08-02  2:22 UTC (permalink / raw)
  To: Alan Third; +Cc: Eli Zaretskii, 조성빈, Emacs developers

On Thu, 1 Aug 2019 at 17:40, Alan Third <alan@idiocy.org> wrote:

> > > > > Anyway, the code contains two calls to
> > > > > evaluateJavaScript:completionHandler: which is a problem as we’re
> > > > > banned from using ObjC blocks, and the completion handler is an ObjC
> > > > > block. Unless GCC supports them now, which I doubt.

> I found the previous thread about removing them from macfont.m:
>
>     https://lists.gnu.org/archive/html/bug-gnu-emacs/2017-12/msg00301.html

If the API requires blocks, I guess they have some stable ABI. Is it
not possible to construct a block at runtime, as a plain C struct?



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-01 21:39                 ` macOS/GCC support policy (was: [PATCH v5] Enable xwidgets on macOS) Alan Third
  2019-08-02  2:22                   ` Noam Postavsky
@ 2019-08-02  6:56                   ` Eli Zaretskii
  2019-08-02 10:08                     ` Philipp Stephani
  1 sibling, 1 reply; 49+ messages in thread
From: Eli Zaretskii @ 2019-08-02  6:56 UTC (permalink / raw)
  To: Alan Third; +Cc: pcr910303, emacs-devel

> Date: Thu, 1 Aug 2019 22:39:58 +0100
> From: Alan Third <alan@idiocy.org>
> Cc: pcr910303@icloud.com, emacs-devel@gnu.org
> 
> > > We’ve had to remove blocks from Emacs code before because gcc doesn’t
> > > support them, however Emacs can’t be built with gcc on recent (like,
> > > the last decade or something) versions of macOS anyway. I don’t really
> > > understand the logic, but it’s not my project.
> > > 
> > > I think it’s really up to Eli and/or RMS.
> > 
> > I don't think I understand the issue well enough to say anything
> > intelligent.  What are "ObjC blocks", and why this patch cannot do
> > without them?
> 
> I found the previous thread about removing them from macfont.m:
> 
>     https://lists.gnu.org/archive/html/bug-gnu-emacs/2017-12/msg00301.html

Thanks.

What exactly prevents building with GCC on macOS?



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-08-02  0:47                   ` Richard Stallman
@ 2019-08-02  7:02                     ` Eli Zaretskii
  2019-08-03  2:23                       ` Richard Stallman
  0 siblings, 1 reply; 49+ messages in thread
From: Eli Zaretskii @ 2019-08-02  7:02 UTC (permalink / raw)
  To: rms; +Cc: alan, pcr910303, emacs-devel

> From: Richard Stallman <rms@gnu.org>
> Cc: eliz@gnu.org, alan@idiocy.org, emacs-devel@gnu.org
> Date: Thu, 01 Aug 2019 20:47:07 -0400
> 
>   > "ObjC blocks" are anonymous functions that are used to pass
>   > arbitrary code between methods or to execute code as a callback
>   > within a method. It captures the surrounding state (it's a
>   > closure).
> 
> In GNU C, I implemented nested functions, with names.
> Anonymous nested functions should not take much extra work.

But if Emacs cannot be built on macOS using GCC, this is a moot point,
right?



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-02  6:56                   ` macOS/GCC support policy Eli Zaretskii
@ 2019-08-02 10:08                     ` Philipp Stephani
  2019-08-02 11:51                       ` Eli Zaretskii
  0 siblings, 1 reply; 49+ messages in thread
From: Philipp Stephani @ 2019-08-02 10:08 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: Alan Third, pcr910303, Emacs developers

Am Fr., 2. Aug. 2019 um 08:57 Uhr schrieb Eli Zaretskii <eliz@gnu.org>:
>
> > Date: Thu, 1 Aug 2019 22:39:58 +0100
> > From: Alan Third <alan@idiocy.org>
> > Cc: pcr910303@icloud.com, emacs-devel@gnu.org
> >
> > > > We’ve had to remove blocks from Emacs code before because gcc doesn’t
> > > > support them, however Emacs can’t be built with gcc on recent (like,
> > > > the last decade or something) versions of macOS anyway. I don’t really
> > > > understand the logic, but it’s not my project.
> > > >
> > > > I think it’s really up to Eli and/or RMS.
> > >
> > > I don't think I understand the issue well enough to say anything
> > > intelligent.  What are "ObjC blocks", and why this patch cannot do
> > > without them?
> >
> > I found the previous thread about removing them from macfont.m:
> >
> >     https://lists.gnu.org/archive/html/bug-gnu-emacs/2017-12/msg00301.html
>
> Thanks.
>
> What exactly prevents building with GCC on macOS?
>

I haven't investigated in detail, but when I try to run configure with
GCC 9 from Homebrew, I get the error message

checking AppKit/AppKit.h usability... no
checking AppKit/AppKit.h presence... yes
configure: WARNING: AppKit/AppKit.h: present but cannot be compiled
configure: WARNING: AppKit/AppKit.h:     check for missing prerequisite headers?
configure: WARNING: AppKit/AppKit.h: see the Autoconf documentation
configure: WARNING: AppKit/AppKit.h:     section "Present But Cannot
Be Compiled"
configure: WARNING: AppKit/AppKit.h: proceeding with the compiler's result
configure: WARNING:     ## ------------------------------------ ##
configure: WARNING:     ## Report this to bug-gnu-emacs@gnu.org ##
configure: WARNING:     ## ------------------------------------ ##
checking for AppKit/AppKit.h... no
configure: error: The include files (AppKit/AppKit.h etc) that
are required for a Nextstep build are missing or cannot be compiled.
Either fix this, or re-configure with the option '--without-ns'.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-02 10:08                     ` Philipp Stephani
@ 2019-08-02 11:51                       ` Eli Zaretskii
  2019-08-02 14:55                         ` Philipp Stephani
  0 siblings, 1 reply; 49+ messages in thread
From: Eli Zaretskii @ 2019-08-02 11:51 UTC (permalink / raw)
  To: Philipp Stephani; +Cc: alan, pcr910303, emacs-devel

> From: Philipp Stephani <p.stephani2@gmail.com>
> Date: Fri, 2 Aug 2019 12:08:35 +0200
> Cc: Alan Third <alan@idiocy.org>, pcr910303@icloud.com, 
> 	Emacs developers <emacs-devel@gnu.org>
> 
> > What exactly prevents building with GCC on macOS?
> >
> 
> I haven't investigated in detail, but when I try to run configure with
> GCC 9 from Homebrew, I get the error message
> 
> checking AppKit/AppKit.h usability... no
> checking AppKit/AppKit.h presence... yes
> configure: WARNING: AppKit/AppKit.h: present but cannot be compiled
> configure: WARNING: AppKit/AppKit.h:     check for missing prerequisite headers?
> configure: WARNING: AppKit/AppKit.h: see the Autoconf documentation
> configure: WARNING: AppKit/AppKit.h:     section "Present But Cannot
> Be Compiled"
> configure: WARNING: AppKit/AppKit.h: proceeding with the compiler's result
> configure: WARNING:     ## ------------------------------------ ##
> configure: WARNING:     ## Report this to bug-gnu-emacs@gnu.org ##
> configure: WARNING:     ## ------------------------------------ ##
> checking for AppKit/AppKit.h... no
> configure: error: The include files (AppKit/AppKit.h etc) that
> are required for a Nextstep build are missing or cannot be compiled.
> Either fix this, or re-configure with the option '--without-ns'.

Thanks.  It would be good if someone could investigate what is the
problem here (and any other problems, if there are any).



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-02 11:51                       ` Eli Zaretskii
@ 2019-08-02 14:55                         ` Philipp Stephani
  2019-08-02 14:59                           ` Philipp Stephani
  2019-08-02 15:05                           ` Eli Zaretskii
  0 siblings, 2 replies; 49+ messages in thread
From: Philipp Stephani @ 2019-08-02 14:55 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: Alan Third, pcr910303, Emacs developers

Am Fr., 2. Aug. 2019 um 13:51 Uhr schrieb Eli Zaretskii <eliz@gnu.org>:
>
> > From: Philipp Stephani <p.stephani2@gmail.com>
> > Date: Fri, 2 Aug 2019 12:08:35 +0200
> > Cc: Alan Third <alan@idiocy.org>, pcr910303@icloud.com,
> >       Emacs developers <emacs-devel@gnu.org>
> >
> > > What exactly prevents building with GCC on macOS?
> > >
> >
> > I haven't investigated in detail, but when I try to run configure with
> > GCC 9 from Homebrew, I get the error message
> >
> > checking AppKit/AppKit.h usability... no
> > checking AppKit/AppKit.h presence... yes
> > configure: WARNING: AppKit/AppKit.h: present but cannot be compiled
> > configure: WARNING: AppKit/AppKit.h:     check for missing prerequisite headers?
> > configure: WARNING: AppKit/AppKit.h: see the Autoconf documentation
> > configure: WARNING: AppKit/AppKit.h:     section "Present But Cannot
> > Be Compiled"
> > configure: WARNING: AppKit/AppKit.h: proceeding with the compiler's result
> > configure: WARNING:     ## ------------------------------------ ##
> > configure: WARNING:     ## Report this to bug-gnu-emacs@gnu.org ##
> > configure: WARNING:     ## ------------------------------------ ##
> > checking for AppKit/AppKit.h... no
> > configure: error: The include files (AppKit/AppKit.h etc) that
> > are required for a Nextstep build are missing or cannot be compiled.
> > Either fix this, or re-configure with the option '--without-ns'.
>
> Thanks.  It would be good if someone could investigate what is the
> problem here (and any other problems, if there are any).

Excerpt from config.log:

configure:10941: checking AppKit/AppKit.h usability
configure:10941: gcc-9 -c -g3 -O1 -fsanitize=address
-fsanitize=undefined -fno-omit-frame-pointer -x objective-c     -x
objective-c  conftest.c >&5
In file included from
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/os/object.h:101,
                 from
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/dispatch/dispatch.h:48,
                 from
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFStream.h:20,
                 from
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFPropertyList.h:17,
                 from
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:60,
                 from
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:6,
                 from
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/AppKit.framework/Headers/AppKit.h:10,
                 from conftest.c:142:
/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/objc/NSObject.h:22:4:
error: unknown type name 'instancetype'
   22 | - (instancetype)self;
      |    ^~~~~~~~~~~~

(lots of similar errors follow)

This indicates that GCC treats the header as C instead of Objective C.
Which is interesting because -x objective-c is given explicitly. Does
GCC need some other flag to force compilation as Objective C?



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-02 14:55                         ` Philipp Stephani
@ 2019-08-02 14:59                           ` Philipp Stephani
  2019-08-02 15:06                             ` Philipp Stephani
  2019-08-02 15:05                           ` Eli Zaretskii
  1 sibling, 1 reply; 49+ messages in thread
From: Philipp Stephani @ 2019-08-02 14:59 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: Alan Third, pcr910303, Emacs developers

Am Fr., 2. Aug. 2019 um 16:55 Uhr schrieb Philipp Stephani
<p.stephani2@gmail.com>:
>
> Am Fr., 2. Aug. 2019 um 13:51 Uhr schrieb Eli Zaretskii <eliz@gnu.org>:
> >
> > > From: Philipp Stephani <p.stephani2@gmail.com>
> > > Date: Fri, 2 Aug 2019 12:08:35 +0200
> > > Cc: Alan Third <alan@idiocy.org>, pcr910303@icloud.com,
> > >       Emacs developers <emacs-devel@gnu.org>
> > >
> > > > What exactly prevents building with GCC on macOS?
> > > >
> > >
> > > I haven't investigated in detail, but when I try to run configure with
> > > GCC 9 from Homebrew, I get the error message
> > >
> > > checking AppKit/AppKit.h usability... no
> > > checking AppKit/AppKit.h presence... yes
> > > configure: WARNING: AppKit/AppKit.h: present but cannot be compiled
> > > configure: WARNING: AppKit/AppKit.h:     check for missing prerequisite headers?
> > > configure: WARNING: AppKit/AppKit.h: see the Autoconf documentation
> > > configure: WARNING: AppKit/AppKit.h:     section "Present But Cannot
> > > Be Compiled"
> > > configure: WARNING: AppKit/AppKit.h: proceeding with the compiler's result
> > > configure: WARNING:     ## ------------------------------------ ##
> > > configure: WARNING:     ## Report this to bug-gnu-emacs@gnu.org ##
> > > configure: WARNING:     ## ------------------------------------ ##
> > > checking for AppKit/AppKit.h... no
> > > configure: error: The include files (AppKit/AppKit.h etc) that
> > > are required for a Nextstep build are missing or cannot be compiled.
> > > Either fix this, or re-configure with the option '--without-ns'.
> >
> > Thanks.  It would be good if someone could investigate what is the
> > problem here (and any other problems, if there are any).
>
> Excerpt from config.log:
>
> configure:10941: checking AppKit/AppKit.h usability
> configure:10941: gcc-9 -c -g3 -O1 -fsanitize=address
> -fsanitize=undefined -fno-omit-frame-pointer -x objective-c     -x
> objective-c  conftest.c >&5
> In file included from
> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/os/object.h:101,
>                  from
> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/dispatch/dispatch.h:48,
>                  from
> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFStream.h:20,
>                  from
> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFPropertyList.h:17,
>                  from
> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:60,
>                  from
> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:6,
>                  from
> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/AppKit.framework/Headers/AppKit.h:10,
>                  from conftest.c:142:
> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/objc/NSObject.h:22:4:
> error: unknown type name 'instancetype'
>    22 | - (instancetype)self;
>       |    ^~~~~~~~~~~~
>
> (lots of similar errors follow)
>
> This indicates that GCC treats the header as C instead of Objective C.
> Which is interesting because -x objective-c is given explicitly. Does
> GCC need some other flag to force compilation as Objective C?

The behavior difference is indeed trivial to reproduce:

p@p:/tmp$ cat appkit.c
#include <AppKit/AppKit.h>
p@p:/tmp$ clang -c -x objective-c appkit.c 2> /dev/null ; echo $?
0
p@p:/tmp$ gcc-9 -c -x objective-c appkit.c 2> /dev/null ; echo $?
1

Without the redirection GCC prints tons of similar errors.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-02 14:55                         ` Philipp Stephani
  2019-08-02 14:59                           ` Philipp Stephani
@ 2019-08-02 15:05                           ` Eli Zaretskii
  2019-08-03 11:02                             ` Alan Third
  1 sibling, 1 reply; 49+ messages in thread
From: Eli Zaretskii @ 2019-08-02 15:05 UTC (permalink / raw)
  To: Philipp Stephani; +Cc: alan, pcr910303, emacs-devel

> From: Philipp Stephani <p.stephani2@gmail.com>
> Date: Fri, 2 Aug 2019 16:55:02 +0200
> Cc: Alan Third <alan@idiocy.org>, pcr910303@icloud.com, 
> 	Emacs developers <emacs-devel@gnu.org>
> 
> /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/objc/NSObject.h:22:4:
> error: unknown type name 'instancetype'
>    22 | - (instancetype)self;
>       |    ^~~~~~~~~~~~
> 
> (lots of similar errors follow)
> 
> This indicates that GCC treats the header as C instead of Objective C.
> Which is interesting because -x objective-c is given explicitly. Does
> GCC need some other flag to force compilation as Objective C?

Searching the Internet for this error seems to suggest that this SDK's
header files are supposed to be compiled only by clang, i.e. their GCC
compilation is deliberately broken by Apple.

Why does Emacs need AppKit/AppKit.h?  If this is for some important
functionality, and if we cannot find a compatible replacement, I guess
the conclusion is that we cannot build Emacs on macOS with GCC due to
the Apple system headers.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-02 14:59                           ` Philipp Stephani
@ 2019-08-02 15:06                             ` Philipp Stephani
  0 siblings, 0 replies; 49+ messages in thread
From: Philipp Stephani @ 2019-08-02 15:06 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: Alan Third, pcr910303, Emacs developers

Am Fr., 2. Aug. 2019 um 16:59 Uhr schrieb Philipp Stephani
<p.stephani2@gmail.com>:
>
> Am Fr., 2. Aug. 2019 um 16:55 Uhr schrieb Philipp Stephani
> <p.stephani2@gmail.com>:
> >
> > Am Fr., 2. Aug. 2019 um 13:51 Uhr schrieb Eli Zaretskii <eliz@gnu.org>:
> > >
> > > > From: Philipp Stephani <p.stephani2@gmail.com>
> > > > Date: Fri, 2 Aug 2019 12:08:35 +0200
> > > > Cc: Alan Third <alan@idiocy.org>, pcr910303@icloud.com,
> > > >       Emacs developers <emacs-devel@gnu.org>
> > > >
> > > > > What exactly prevents building with GCC on macOS?
> > > > >
> > > >
> > > > I haven't investigated in detail, but when I try to run configure with
> > > > GCC 9 from Homebrew, I get the error message
> > > >
> > > > checking AppKit/AppKit.h usability... no
> > > > checking AppKit/AppKit.h presence... yes
> > > > configure: WARNING: AppKit/AppKit.h: present but cannot be compiled
> > > > configure: WARNING: AppKit/AppKit.h:     check for missing prerequisite headers?
> > > > configure: WARNING: AppKit/AppKit.h: see the Autoconf documentation
> > > > configure: WARNING: AppKit/AppKit.h:     section "Present But Cannot
> > > > Be Compiled"
> > > > configure: WARNING: AppKit/AppKit.h: proceeding with the compiler's result
> > > > configure: WARNING:     ## ------------------------------------ ##
> > > > configure: WARNING:     ## Report this to bug-gnu-emacs@gnu.org ##
> > > > configure: WARNING:     ## ------------------------------------ ##
> > > > checking for AppKit/AppKit.h... no
> > > > configure: error: The include files (AppKit/AppKit.h etc) that
> > > > are required for a Nextstep build are missing or cannot be compiled.
> > > > Either fix this, or re-configure with the option '--without-ns'.
> > >
> > > Thanks.  It would be good if someone could investigate what is the
> > > problem here (and any other problems, if there are any).
> >
> > Excerpt from config.log:
> >
> > configure:10941: checking AppKit/AppKit.h usability
> > configure:10941: gcc-9 -c -g3 -O1 -fsanitize=address
> > -fsanitize=undefined -fno-omit-frame-pointer -x objective-c     -x
> > objective-c  conftest.c >&5
> > In file included from
> > /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/os/object.h:101,
> >                  from
> > /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/dispatch/dispatch.h:48,
> >                  from
> > /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFStream.h:20,
> >                  from
> > /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CFPropertyList.h:17,
> >                  from
> > /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h:60,
> >                  from
> > /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h:6,
> >                  from
> > /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks/AppKit.framework/Headers/AppKit.h:10,
> >                  from conftest.c:142:
> > /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include/objc/NSObject.h:22:4:
> > error: unknown type name 'instancetype'
> >    22 | - (instancetype)self;
> >       |    ^~~~~~~~~~~~
> >
> > (lots of similar errors follow)
> >
> > This indicates that GCC treats the header as C instead of Objective C.
> > Which is interesting because -x objective-c is given explicitly. Does
> > GCC need some other flag to force compilation as Objective C?
>
> The behavior difference is indeed trivial to reproduce:
>
> p@p:/tmp$ cat appkit.c
> #include <AppKit/AppKit.h>
> p@p:/tmp$ clang -c -x objective-c appkit.c 2> /dev/null ; echo $?
> 0
> p@p:/tmp$ gcc-9 -c -x objective-c appkit.c 2> /dev/null ; echo $?
> 1
>
> Without the redirection GCC prints tons of similar errors.

OK, I guess this is a red herring and the problem has nothing to do
with -x. The Objective C dialect supported by GCC is simply different
from the Objective C dialect used by Apple, and until GCC supports the
Apple dialect it can't be used to build any macOS app.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-08-02  7:02                     ` Eli Zaretskii
@ 2019-08-03  2:23                       ` Richard Stallman
  2019-08-03  6:58                         ` Eli Zaretskii
  0 siblings, 1 reply; 49+ messages in thread
From: Richard Stallman @ 2019-08-03  2:23 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: alan, pcr910303, emacs-devel

[[[ To any NSA and FBI agents reading my email: please consider    ]]]
[[[ whether defending the US Constitution against all enemies,     ]]]
[[[ foreign or domestic, requires you to follow Snowden's example. ]]]

  > > In GNU C, I implemented nested functions, with names.
  > > Anonymous nested functions should not take much extra work.

  > But if Emacs cannot be built on macOS using GCC, this is a moot point,
  > right?

Not entirely.  It means that GCC could implement the ObjC blocks feature.

-- 
Dr Richard Stallman
President, Free Software Foundation (https://gnu.org, https://fsf.org)
Internet Hall-of-Famer (https://internethalloffame.org)





^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-08-03  2:23                       ` Richard Stallman
@ 2019-08-03  6:58                         ` Eli Zaretskii
  0 siblings, 0 replies; 49+ messages in thread
From: Eli Zaretskii @ 2019-08-03  6:58 UTC (permalink / raw)
  To: rms; +Cc: alan, pcr910303, emacs-devel

> From: Richard Stallman <rms@gnu.org>
> Cc: alan@idiocy.org, pcr910303@icloud.com, emacs-devel@gnu.org
> Date: Fri, 02 Aug 2019 22:23:20 -0400
> 
>   > > In GNU C, I implemented nested functions, with names.
>   > > Anonymous nested functions should not take much extra work.
> 
>   > But if Emacs cannot be built on macOS using GCC, this is a moot point,
>   > right?
> 
> Not entirely.  It means that GCC could implement the ObjC blocks feature.

I think we are miscommunicating.  Emacs cannot currently be built with
GCC for reasons that are unrelated to the ObjC blocks feature, see
this discussion:

  https://lists.gnu.org/archive/html/emacs-devel/2019-08/msg00039.html

So even if the GCC folks implement the blocks feature, the main
obstacle for using GCC on macOS will still stand, and will prevent us
from supporting a GCC build of Emacs on macOS.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-07-29 17:08               ` 조성빈
@ 2019-08-03 10:03                 ` Eli Zaretskii
  2019-08-03 10:52                   ` 조성빈
  0 siblings, 1 reply; 49+ messages in thread
From: Eli Zaretskii @ 2019-08-03 10:03 UTC (permalink / raw)
  To: 조성빈; +Cc: alan, emacs-devel

> From: 조성빈 <pcr910303@icloud.com>
> Date: Tue, 30 Jul 2019 02:08:40 +0900
> Cc: alan@idiocy.org,
>  emacs-devel@gnu.org
> 
> >>>> +(defun xwidget-webkit-save-as-file (url mime-type file-name)
> >>>> +  "For XWIDGET webkit, save URL of MIME-TYPE to location specified by user.
> >>>> +FILE-NAME combined with `xwidget-webkit-download-dir' is the default file name
> >>>> +of the prompt when reading.  When the file name the user specified is a
> >>>> +directory, URL is saved at the specified directory as FILE-NAME."
> >>> 
> >>> The last sentence is unclear: what will be the directory where the URL
> >>> will be saved, and what will be the name of the saved file in that
> >>> directory?
> >> 
> >> Well, it was meaning that the URL will be saved at the directory the user specified in the prompt with the name FILE-NAME.
> >> 
> >> I’m not sure how I should reword it due to my  poor English skills; can you give me some suggestions? 
> > 
> > If you show me an example of using this command, and the results -- in
> > what directory and under what base name will the URL be saved -- then
> > I will be able to suggest a better wording.
> 
> Sorry for the delay; I was busy for a few days that I couldn't open my mailbox.
> 
> Well, while I was trying to give examples, I think I wrote a clearer version of the docstring:
> "Save URL of MIME-TYPE as file specified by user.
> When the user specifies a directory, URL is saved with the name FILE-NAME in the
>  specified directory.  The default file name when reading is FILE-NAME expanded
>  with `xwidget-webkit-download-dir'."
> 
> May I ask if this is more clear than before?

I don't think I understand what happens well enough yet.  The command
asks for FILE-NAME, right?  So when the FILE-NAME provided by the user
is actually a directory, the URL will be saved in the directory named
FILE-NAME, but under what basename?



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: [PATCH v5] Enable xwidgets on macOS
  2019-08-03 10:03                 ` Eli Zaretskii
@ 2019-08-03 10:52                   ` 조성빈
  0 siblings, 0 replies; 49+ messages in thread
From: 조성빈 @ 2019-08-03 10:52 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: alan, emacs-devel



2019. 8. 3. 오후 7:03, Eli Zaretskii <eliz@gnu.org> 작성:

>> From: 조성빈 <pcr910303@icloud.com>
>> Date: Tue, 30 Jul 2019 02:08:40 +0900
>> Cc: alan@idiocy.org,
>> emacs-devel@gnu.org
>> 
>>>>>> +(defun xwidget-webkit-save-as-file (url mime-type file-name)
>>>>>> +  "For XWIDGET webkit, save URL of MIME-TYPE to location specified by user.
>>>>>> +FILE-NAME combined with `xwidget-webkit-download-dir' is the default file name
>>>>>> +of the prompt when reading.  When the file name the user specified is a
>>>>>> +directory, URL is saved at the specified directory as FILE-NAME."
>>>>> 
>>>>> The last sentence is unclear: what will be the directory where the URL
>>>>> will be saved, and what will be the name of the saved file in that
>>>>> directory?
>>>> 
>>>> Well, it was meaning that the URL will be saved at the directory the user specified in the prompt with the name FILE-NAME.
>>>> 
>>>> I’m not sure how I should reword it due to my  poor English skills; can you give me some suggestions? 
>>> 
>>> If you show me an example of using this command, and the results -- in
>>> what directory and under what base name will the URL be saved -- then
>>> I will be able to suggest a better wording.
>> 
>> Sorry for the delay; I was busy for a few days that I couldn't open my mailbox.
>> 
>> Well, while I was trying to give examples, I think I wrote a clearer version of the docstring:
>> "Save URL of MIME-TYPE as file specified by user.
>> When the user specifies a directory, URL is saved with the name FILE-NAME in the
>> specified directory.  The default file name when reading is FILE-NAME expanded
>> with `xwidget-webkit-download-dir'."
>> 
>> May I ask if this is more clear than before?
> 
> I don't think I understand what happens well enough yet.  The command
> asks for FILE-NAME, right?

It’s not an interactive command, more of an helper function.
FILE-NAME isn’t provided by the user; it’s provided by the internal callsite. Maybe embedding the logic instead of making a separate function (which the original patch did) might be better?

>  So when the FILE-NAME provided by the user
> is actually a directory, the URL will be saved in the directory named
> FILE-NAME, but under what basename?

If the user provided directory (which has no relationship with FILE-NAME and is read by the `read-file-name' call inside the function) is a directory, the basename becomes FILE-NAME. The function assumes FILE-NAME provided by the callsite is not a directory.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-02 15:05                           ` Eli Zaretskii
@ 2019-08-03 11:02                             ` Alan Third
  2019-08-03 11:10                               ` Eli Zaretskii
  0 siblings, 1 reply; 49+ messages in thread
From: Alan Third @ 2019-08-03 11:02 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: Philipp Stephani, pcr910303, emacs-devel

On Fri, Aug 02, 2019 at 06:05:20PM +0300, Eli Zaretskii wrote:
> 
> Why does Emacs need AppKit/AppKit.h?  If this is for some important
> functionality, and if we cannot find a compatible replacement, I guess
> the conclusion is that we cannot build Emacs on macOS with GCC due to
> the Apple system headers.

Appkit is, basically, the NextStep GUI toolkit, so we need it.

-- 
Alan Third



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-03 11:02                             ` Alan Third
@ 2019-08-03 11:10                               ` Eli Zaretskii
  2019-08-03 11:18                                 ` Alan Third
  0 siblings, 1 reply; 49+ messages in thread
From: Eli Zaretskii @ 2019-08-03 11:10 UTC (permalink / raw)
  To: Alan Third; +Cc: p.stephani2, pcr910303, emacs-devel

> Date: Sat, 3 Aug 2019 12:02:56 +0100
> From: Alan Third <alan@idiocy.org>
> Cc: Philipp Stephani <p.stephani2@gmail.com>, pcr910303@icloud.com,
> 	emacs-devel@gnu.org
> 
> On Fri, Aug 02, 2019 at 06:05:20PM +0300, Eli Zaretskii wrote:
> > 
> > Why does Emacs need AppKit/AppKit.h?  If this is for some important
> > functionality, and if we cannot find a compatible replacement, I guess
> > the conclusion is that we cannot build Emacs on macOS with GCC due to
> > the Apple system headers.
> 
> Appkit is, basically, the NextStep GUI toolkit, so we need it.

So basically, this means GCC cannot be currently used to compile any
non-trivial NS GUI application, is that right?

Is there any ETA on GCC support for the current NS GUI?  Is anyone
working on that, to the best of your knowledge?



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-03 11:10                               ` Eli Zaretskii
@ 2019-08-03 11:18                                 ` Alan Third
  2019-08-03 11:43                                   ` Eli Zaretskii
  2019-08-04  2:56                                   ` Richard Stallman
  0 siblings, 2 replies; 49+ messages in thread
From: Alan Third @ 2019-08-03 11:18 UTC (permalink / raw)
  To: Eli Zaretskii; +Cc: p.stephani2, pcr910303, emacs-devel

On Sat, Aug 03, 2019 at 02:10:45PM +0300, Eli Zaretskii wrote:
> > Date: Sat, 3 Aug 2019 12:02:56 +0100
> > From: Alan Third <alan@idiocy.org>
> > Cc: Philipp Stephani <p.stephani2@gmail.com>, pcr910303@icloud.com,
> > 	emacs-devel@gnu.org
> > 
> > On Fri, Aug 02, 2019 at 06:05:20PM +0300, Eli Zaretskii wrote:
> > > 
> > > Why does Emacs need AppKit/AppKit.h?  If this is for some important
> > > functionality, and if we cannot find a compatible replacement, I guess
> > > the conclusion is that we cannot build Emacs on macOS with GCC due to
> > > the Apple system headers.
> > 
> > Appkit is, basically, the NextStep GUI toolkit, so we need it.
> 
> So basically, this means GCC cannot be currently used to compile any
> non-trivial NS GUI application, is that right?

Yes. As Philippe demonstrated GCC errors when it sees the header
files.

> Is there any ETA on GCC support for the current NS GUI?  Is anyone
> working on that, to the best of your knowledge?

As far as I’m aware nobody is working on it. Features like blocks have
been part of Apple’s Objective C spec for at least a decade now and I
don’t believe there has been any attempt to update GCC.

GNUstep doesn’t use these updated features, but it does mean they
can’t match the current Apple APIs. Although I don’t know if they want
to, I know very little about the project.
-- 
Alan Third



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-03 11:18                                 ` Alan Third
@ 2019-08-03 11:43                                   ` Eli Zaretskii
  2019-08-04  2:56                                   ` Richard Stallman
  1 sibling, 0 replies; 49+ messages in thread
From: Eli Zaretskii @ 2019-08-03 11:43 UTC (permalink / raw)
  To: Alan Third; +Cc: p.stephani2, pcr910303, emacs-devel

> Date: Sat, 3 Aug 2019 12:18:02 +0100
> From: Alan Third <alan@idiocy.org>
> Cc: p.stephani2@gmail.com, pcr910303@icloud.com, emacs-devel@gnu.org
> 
> > Is there any ETA on GCC support for the current NS GUI?  Is anyone
> > working on that, to the best of your knowledge?
> 
> As far as I’m aware nobody is working on it. Features like blocks have
> been part of Apple’s Objective C spec for at least a decade now and I
> don’t believe there has been any attempt to update GCC.

It seems like https://gcc.gnu.org/bugzilla/show_bug.cgi?id=90709 is
the GCC bug to follow.  It sounds like it's being worked on, so maybe
the prospects of having GCC support of NS back are not as bleak as
they might look.



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-03 11:18                                 ` Alan Third
  2019-08-03 11:43                                   ` Eli Zaretskii
@ 2019-08-04  2:56                                   ` Richard Stallman
  2019-08-10  9:56                                     ` 조성빈
  1 sibling, 1 reply; 49+ messages in thread
From: Richard Stallman @ 2019-08-04  2:56 UTC (permalink / raw)
  To: Alan Third; +Cc: eliz, p.stephani2, pcr910303, emacs-devel

[[[ To any NSA and FBI agents reading my email: please consider    ]]]
[[[ whether defending the US Constitution against all enemies,     ]]]
[[[ foreign or domestic, requires you to follow Snowden's example. ]]]

  > Date: Sat, 3 Aug 2019 12:18:02 +0100
  > From: Alan Third <alan@idiocy.org>
  > To: Eli Zaretskii <eliz@gnu.org>
  > Subject: Re: macOS/GCC support policy
  > Message-ID: <20190803111802.GB31224@breton.holly.idiocy.org>
  > Content-Type: text/plain; charset=utf-8
  > Content-Disposition: inline
  > In-Reply-To: <83k1buec7e.fsf@gnu.org>
  > Cc: p.stephani2@gmail.com, pcr910303@icloud.com, emacs-devel@gnu.org

  > On Sat, Aug 03, 2019 at 02:10:45PM +0300, Eli Zaretskii wrote:
  > > > Date: Sat, 3 Aug 2019 12:02:56 +0100
  > > > From: Alan Third <alan@idiocy.org>
  > > > Cc: Philipp Stephani <p.stephani2@gmail.com>, pcr910303@icloud.com,
  > > > 	emacs-devel@gnu.org
  > > > 
  > > > On Fri, Aug 02, 2019 at 06:05:20PM +0300, Eli Zaretskii wrote:
  > > > > 
  > > > > Why does Emacs need AppKit/AppKit.h?  If this is for some important
  > > > > functionality, and if we cannot find a compatible replacement, I guess
  > > > > the conclusion is that we cannot build Emacs on macOS with GCC due to
  > > > > the Apple system headers.
  > > > 
  > > > Appkit is, basically, the NextStep GUI toolkit, so we need it.
  > > 
  > > So basically, this means GCC cannot be currently used to compile any
  > > non-trivial NS GUI application, is that right?

  > Yes. As Philippe demonstrated GCC errors when it sees the header
  > files.

  > > Is there any ETA on GCC support for the current NS GUI?  Is anyone
  > > working on that, to the best of your knowledge?

  > As far as I’m aware nobody is working on it. Features like blocks have
  > been part of Apple’s Objective C spec for at least a decade now and I
  > don’t believe there has been any attempt to update GCC.

The basic purpose of every GNU package is to add to what the GNU
system can do.  Making a GNU program run on some other system is not a
central goal, but we encourage people to implement that if they wish.

It would be beneficial to make GCC support MacOS if it would lead
to more adoption of GCC.  Otherwise, we don't especially care.

If extensions to Objective C make that language better, it would be
good to implement them.  GNUtep doesn't use them now, but maybe it
would use them if they were available.


-- 
Dr Richard Stallman
President, Free Software Foundation (https://gnu.org, https://fsf.org)
Internet Hall-of-Famer (https://internethalloffame.org)





^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-04  2:56                                   ` Richard Stallman
@ 2019-08-10  9:56                                     ` 조성빈
  2019-08-18 15:43                                       ` Alan Third
  0 siblings, 1 reply; 49+ messages in thread
From: 조성빈 @ 2019-08-10  9:56 UTC (permalink / raw)
  To: rms; +Cc: p.stephani2, Alan Third, eliz, emacs-devel


2019. 8. 4. 오전 11:56, Richard Stallman <rms@gnu.org> 작성:

> [[[ To any NSA and FBI agents reading my email: please consider    ]]]
> [[[ whether defending the US Constitution against all enemies,     ]]]
> [[[ foreign or domestic, requires you to follow Snowden's example. ]]]
> 
>> Date: Sat, 3 Aug 2019 12:18:02 +0100
>> From: Alan Third <alan@idiocy.org>
>> To: Eli Zaretskii <eliz@gnu.org>
>> Subject: Re: macOS/GCC support policy
>> Message-ID: <20190803111802.GB31224@breton.holly.idiocy.org>
>> Content-Type: text/plain; charset=utf-8
>> Content-Disposition: inline
>> In-Reply-To: <83k1buec7e.fsf@gnu.org>
>> Cc: p.stephani2@gmail.com, pcr910303@icloud.com, emacs-devel@gnu.org
> 
>> On Sat, Aug 03, 2019 at 02:10:45PM +0300, Eli Zaretskii wrote:
>>>> Date: Sat, 3 Aug 2019 12:02:56 +0100
>>>> From: Alan Third <alan@idiocy.org>
>>>> Cc: Philipp Stephani <p.stephani2@gmail.com>, pcr910303@icloud.com,
>>>>    emacs-devel@gnu.org
>>>> 
>>>>> On Fri, Aug 02, 2019 at 06:05:20PM +0300, Eli Zaretskii wrote:
>>>>> 
>>>>> Why does Emacs need AppKit/AppKit.h?  If this is for some important
>>>>> functionality, and if we cannot find a compatible replacement, I guess
>>>>> the conclusion is that we cannot build Emacs on macOS with GCC due to
>>>>> the Apple system headers.
>>>> 
>>>> Appkit is, basically, the NextStep GUI toolkit, so we need it.
>>> 
>>> So basically, this means GCC cannot be currently used to compile any
>>> non-trivial NS GUI application, is that right?
> 
>> Yes. As Philippe demonstrated GCC errors when it sees the header
>> files.
> 
>>> Is there any ETA on GCC support for the current NS GUI?  Is anyone
>>> working on that, to the best of your knowledge?
> 
>> As far as I’m aware nobody is working on it. Features like blocks have
>> been part of Apple’s Objective C spec for at least a decade now and I
>> don’t believe there has been any attempt to update GCC.
> 
> The basic purpose of every GNU package is to add to what the GNU
> system can do.  Making a GNU program run on some other system is not a
> central goal, but we encourage people to implement that if they wish.
> 
> It would be beneficial to make GCC support MacOS if it would lead
> to more adoption of GCC.  Otherwise, we don't especially care.

Does that mean we can use Obj-C blocks in Emacs? (IOW, should I keep developing the patch?)

> If extensions to Objective C make that language better, it would be
> good to implement them.  GNUtep doesn't use them now, but maybe it
> would use them if they were available.
> 
> 
> -- 
> Dr Richard Stallman
> President, Free Software Foundation (https://gnu.org, https://fsf.org)
> Internet Hall-of-Famer (https://internethalloffame.org)
> 
> 
> 




^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-10  9:56                                     ` 조성빈
@ 2019-08-18 15:43                                       ` Alan Third
  2019-08-18 16:40                                         ` Eli Zaretskii
  2019-08-18 23:42                                         ` Richard Stallman
  0 siblings, 2 replies; 49+ messages in thread
From: Alan Third @ 2019-08-18 15:43 UTC (permalink / raw)
  To: 조성빈; +Cc: p.stephani2, eliz, rms, emacs-devel

On Sat, Aug 10, 2019 at 06:56:13PM +0900, 조성빈 wrote:
> 
> 2019. 8. 4. 오전 11:56, Richard Stallman <rms@gnu.org> 작성:
> > The basic purpose of every GNU package is to add to what the GNU
> > system can do.  Making a GNU program run on some other system is not a
> > central goal, but we encourage people to implement that if they wish.
> > 
> > It would be beneficial to make GCC support MacOS if it would lead
> > to more adoption of GCC.  Otherwise, we don't especially care.
> 
> Does that mean we can use Obj-C blocks in Emacs? (IOW, should I keep developing the patch?)
> 
> > If extensions to Objective C make that language better, it would be
> > good to implement them.  GNUtep doesn't use them now, but maybe it
> > would use them if they were available.

At the very least I imagine the platform independent part should go
ahead. I’m not sure what the policy is here, it looks to me like
nobody feels very strongly about this, but I’m probably misreading the
situation.

Can Richard or Eli clarify, please?
-- 
Alan Third



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-18 15:43                                       ` Alan Third
@ 2019-08-18 16:40                                         ` Eli Zaretskii
  2019-08-18 23:42                                         ` Richard Stallman
  1 sibling, 0 replies; 49+ messages in thread
From: Eli Zaretskii @ 2019-08-18 16:40 UTC (permalink / raw)
  To: Alan Third; +Cc: p.stephani2, rms, pcr910303, emacs-devel

> Date: Sun, 18 Aug 2019 16:43:15 +0100
> From: Alan Third <alan@idiocy.org>
> Cc: rms@gnu.org, eliz@gnu.org, p.stephani2@gmail.com, emacs-devel@gnu.org
> 
> At the very least I imagine the platform independent part should go
> ahead. I’m not sure what the policy is here, it looks to me like
> nobody feels very strongly about this, but I’m probably misreading the
> situation.
> 
> Can Richard or Eli clarify, please?

What is the "platform independent part"?



^ permalink raw reply	[flat|nested] 49+ messages in thread

* Re: macOS/GCC support policy
  2019-08-18 15:43                                       ` Alan Third
  2019-08-18 16:40                                         ` Eli Zaretskii
@ 2019-08-18 23:42                                         ` Richard Stallman
  1 sibling, 0 replies; 49+ messages in thread
From: Richard Stallman @ 2019-08-18 23:42 UTC (permalink / raw)
  To: Alan Third; +Cc: p.stephani2, eliz, pcr910303, emacs-devel

[[[ To any NSA and FBI agents reading my email: please consider    ]]]
[[[ whether defending the US Constitution against all enemies,     ]]]
[[[ foreign or domestic, requires you to follow Snowden's example. ]]]

  > > > If extensions to Objective C make that language better, it would be
  > > > good to implement them.  GNUtep doesn't use them now, but maybe it
  > > > would use them if they were available.

  > At the very least I imagine the platform independent part should go
  > ahead. I’m not sure what the policy is here, it looks to me like
  > nobody feels very strongly about this, but I’m probably misreading the
  > situation.

I hope someone will implement that, but it depends on finding a volunteer
who wants to.

I don't see how this is a question of "policy".

-- 
Dr Richard Stallman
President, Free Software Foundation (https://gnu.org, https://fsf.org)
Internet Hall-of-Famer (https://internethalloffame.org)





^ permalink raw reply	[flat|nested] 49+ messages in thread

end of thread, other threads:[~2019-08-18 23:42 UTC | newest]

Thread overview: 49+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2019-07-18 19:23 [PATCH v4] Enable xwidgets on macOS Sungbin Jo
2019-07-19  4:16 ` [PATCH v5] " Sungbin Jo
2019-07-19 19:17   ` Alan Third
2019-07-19 19:25     ` Savannah down (was: [PATCH v5] Enable xwidgets on macOS) Paul Eggert
2019-07-20  8:21   ` [PATCH v5] Enable xwidgets on macOS Eli Zaretskii
2019-07-23 18:36     ` 조성빈
2019-07-25 18:51       ` 조성빈
2019-07-26  5:55         ` Eli Zaretskii
2019-07-27  2:48           ` Richard Stallman
2019-07-27  8:38             ` Eli Zaretskii
2019-07-27 10:41         ` Eli Zaretskii
2019-07-27 12:35           ` 조성빈
2019-07-27 13:03             ` Eli Zaretskii
2019-07-29 17:08               ` 조성빈
2019-08-03 10:03                 ` Eli Zaretskii
2019-08-03 10:52                   ` 조성빈
2019-07-29 20:26         ` Alan Third
2019-07-29 21:02           ` Stefan Monnier
2019-07-30 15:35             ` 조성빈
2019-07-30 19:25               ` Stefan Monnier
2019-07-31 15:52                 ` 조성빈
2019-07-30 15:33           ` 조성빈
2019-07-30 19:12             ` Juri Linkov
2019-07-31 15:55               ` 조성빈
2019-07-31 19:56             ` Alan Third
2019-08-01  2:35               ` Eli Zaretskii
2019-08-01  4:00                 ` 조성빈
2019-08-02  0:47                   ` Richard Stallman
2019-08-02  7:02                     ` Eli Zaretskii
2019-08-03  2:23                       ` Richard Stallman
2019-08-03  6:58                         ` Eli Zaretskii
2019-08-01 21:39                 ` macOS/GCC support policy (was: [PATCH v5] Enable xwidgets on macOS) Alan Third
2019-08-02  2:22                   ` Noam Postavsky
2019-08-02  6:56                   ` macOS/GCC support policy Eli Zaretskii
2019-08-02 10:08                     ` Philipp Stephani
2019-08-02 11:51                       ` Eli Zaretskii
2019-08-02 14:55                         ` Philipp Stephani
2019-08-02 14:59                           ` Philipp Stephani
2019-08-02 15:06                             ` Philipp Stephani
2019-08-02 15:05                           ` Eli Zaretskii
2019-08-03 11:02                             ` Alan Third
2019-08-03 11:10                               ` Eli Zaretskii
2019-08-03 11:18                                 ` Alan Third
2019-08-03 11:43                                   ` Eli Zaretskii
2019-08-04  2:56                                   ` Richard Stallman
2019-08-10  9:56                                     ` 조성빈
2019-08-18 15:43                                       ` Alan Third
2019-08-18 16:40                                         ` Eli Zaretskii
2019-08-18 23:42                                         ` Richard Stallman

Code repositories for project(s) associated with this public inbox

	https://git.savannah.gnu.org/cgit/emacs.git

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).