xwidget.c 38.7 KB
Newer Older
1 2
/* Support for embedding graphical components in a buffer.

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 2011-2019 Free Software Foundation, Inc.
4 5 6 7 8

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
9 10
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
11 12 13 14 15 16 17

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
18
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */
19 20 21

#include <config.h>

Paul Eggert's avatar
Paul Eggert committed
22
#include "xwidget.h"
23 24 25 26 27 28 29

#include "lisp.h"
#include "blockinput.h"
#include "frame.h"
#include "keyboard.h"
#include "gtkutil.h"

Ricardo Wurmus's avatar
Ricardo Wurmus committed
30
#include <webkit2/webkit2.h>
31
#include <JavaScriptCore/JavaScript.h>
32

33 34 35 36 37 38 39 40
/* 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.  */
#if WEBKIT_CHECK_VERSION (2, 21, 1) && GNUC_PREREQ (4, 2, 0)
# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#endif

41 42 43
static struct xwidget *
allocate_xwidget (void)
{
44
  return ALLOCATE_PSEUDOVECTOR (struct xwidget, script_callbacks, PVEC_XWIDGET);
45 46 47 48 49
}

static struct xwidget_view *
allocate_xwidget_view (void)
{
50
  return ALLOCATE_PSEUDOVECTOR (struct xwidget_view, w, PVEC_XWIDGET_VIEW);
51 52
}

Paul Eggert's avatar
Paul Eggert committed
53 54
#define XSETXWIDGET(a, b) XSETPSEUDOVECTOR (a, b, PVEC_XWIDGET)
#define XSETXWIDGET_VIEW(a, b) XSETPSEUDOVECTOR (a, b, PVEC_XWIDGET_VIEW)
55

56 57
static struct xwidget_view *xwidget_view_lookup (struct xwidget *,
						 struct window *);
Ricardo Wurmus's avatar
Ricardo Wurmus committed
58 59 60
static void webkit_view_load_changed_cb (WebKitWebView *,
                                         WebKitLoadEvent,
                                         gpointer);
61 62 63
static void webkit_javascript_finished_cb (GObject *,
                                           GAsyncResult *,
                                           gpointer);
Ricardo Wurmus's avatar
Ricardo Wurmus committed
64
static gboolean webkit_download_cb (WebKitWebContext *, WebKitDownload *, gpointer);
65

66
static gboolean
Ricardo Wurmus's avatar
Ricardo Wurmus committed
67 68 69 70
webkit_decide_policy_cb (WebKitWebView *,
                         WebKitPolicyDecision *,
                         WebKitPolicyDecisionType,
                         gpointer);
71 72 73 74


DEFUN ("make-xwidget",
       Fmake_xwidget, Smake_xwidget,
75 76
       5, 6, 0,
       doc: /* Make an xwidget of TYPE.
Glenn Morris's avatar
Glenn Morris committed
77 78 79
If BUFFER is nil, use the current buffer.
If BUFFER is a string and no such buffer exists, create it.
TYPE is a symbol which can take one of the following values:
80

81
- webkit
82

Glenn Morris's avatar
Glenn Morris committed
83
Returns the newly constructed xwidget, or nil if construction fails.  */)
84
  (Lisp_Object type,
Paul Eggert's avatar
Paul Eggert committed
85 86
   Lisp_Object title, Lisp_Object width, Lisp_Object height,
   Lisp_Object arguments, Lisp_Object buffer)
87
{
88 89
  if (!xg_gtk_initialized)
    error ("make-xwidget: GTK has not been initialized");
Paul Eggert's avatar
Paul Eggert committed
90
  CHECK_SYMBOL (type);
91 92
  CHECK_FIXNAT (width);
  CHECK_FIXNAT (height);
93

94 95 96 97
  struct xwidget *xw = allocate_xwidget ();
  Lisp_Object val;
  xw->type = type;
  xw->title = title;
Paul Eggert's avatar
Paul Eggert committed
98
  xw->buffer = NILP (buffer) ? Fcurrent_buffer () : Fget_buffer_create (buffer);
Tom Tromey's avatar
Tom Tromey committed
99 100
  xw->height = XFIXNAT (height);
  xw->width = XFIXNAT (width);
Paul Eggert's avatar
Paul Eggert committed
101 102
  xw->kill_without_query = false;
  XSETXWIDGET (val, xw);
103 104 105 106 107
  Vxwidget_list = Fcons (val, Vxwidget_list);
  xw->widgetwindow_osr = NULL;
  xw->widget_osr = NULL;
  xw->plist = Qnil;

Paul Eggert's avatar
Paul Eggert committed
108
  if (EQ (xw->type, Qwebkit))
109 110 111 112 113
    {
      block_input ();
      xw->widgetwindow_osr = gtk_offscreen_window_new ();
      gtk_window_resize (GTK_WINDOW (xw->widgetwindow_osr), xw->width,
                         xw->height);
Paul Eggert's avatar
Paul Eggert committed
114

Paul Eggert's avatar
Paul Eggert committed
115
      if (EQ (xw->type, Qwebkit))
116 117 118 119 120 121 122
        {
          xw->widget_osr = webkit_web_view_new ();
        }

      gtk_widget_set_size_request (GTK_WIDGET (xw->widget_osr), xw->width,
                                   xw->height);

Paul Eggert's avatar
Paul Eggert committed
123
      if (EQ (xw->type, Qwebkit))
124 125
        {
          gtk_container_add (GTK_CONTAINER (xw->widgetwindow_osr),
126
                             GTK_WIDGET (WEBKIT_WEB_VIEW (xw->widget_osr)));
127 128 129 130 131 132 133 134 135 136
        }
      else
        {
          gtk_container_add (GTK_CONTAINER (xw->widgetwindow_osr),
                             xw->widget_osr);
        }

      gtk_widget_show (xw->widget_osr);
      gtk_widget_show (xw->widgetwindow_osr);

Paul Eggert's avatar
Paul Eggert committed
137
      /* Store some xwidget data in the gtk widgets for convenient
Glenn Morris's avatar
Glenn Morris committed
138
         retrieval in the event handlers.  */
Paul Eggert's avatar
Paul Eggert committed
139 140
      g_object_set_data (G_OBJECT (xw->widget_osr), XG_XWIDGET, xw);
      g_object_set_data (G_OBJECT (xw->widgetwindow_osr), XG_XWIDGET, xw);
141 142

      /* signals */
Paul Eggert's avatar
Paul Eggert committed
143
      if (EQ (xw->type, Qwebkit))
144 145
        {
          g_signal_connect (G_OBJECT (xw->widget_osr),
Ricardo Wurmus's avatar
Ricardo Wurmus committed
146 147
                            "load-changed",
                            G_CALLBACK (webkit_view_load_changed_cb), xw);
148

Ricardo Wurmus's avatar
Ricardo Wurmus committed
149 150
          g_signal_connect (G_OBJECT (webkit_web_context_get_default ()),
                            "download-started",
151 152 153
                            G_CALLBACK (webkit_download_cb), xw);

          g_signal_connect (G_OBJECT (xw->widget_osr),
Ricardo Wurmus's avatar
Ricardo Wurmus committed
154
                            "decide-policy",
155
                            G_CALLBACK
Ricardo Wurmus's avatar
Ricardo Wurmus committed
156
                            (webkit_decide_policy_cb),
157 158 159 160 161 162 163 164 165 166 167 168
                            xw);
        }

      unblock_input ();
    }

  return val;
}

DEFUN ("get-buffer-xwidgets", Fget_buffer_xwidgets, Sget_buffer_xwidgets,
       1, 1, 0,
       doc: /* Return a list of xwidgets associated with BUFFER.
Glenn Morris's avatar
Glenn Morris committed
169
BUFFER may be a buffer or the name of one.  */)
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  (Lisp_Object buffer)
{
  Lisp_Object xw, tail, xw_list;

  if (NILP (buffer))
    return Qnil;
  buffer = Fget_buffer (buffer);
  if (NILP (buffer))
    return Qnil;

  xw_list = Qnil;

  for (tail = Vxwidget_list; CONSP (tail); tail = XCDR (tail))
    {
      xw = XCAR (tail);
      if (XWIDGETP (xw) && EQ (Fxwidget_buffer (xw), buffer))
        xw_list = Fcons (xw, xw_list);
    }
  return xw_list;
}

Paul Eggert's avatar
Paul Eggert committed
191
static bool
192 193 194 195 196 197 198 199
xwidget_hidden (struct xwidget_view *xv)
{
  return xv->hidden;
}

static void
xwidget_show_view (struct xwidget_view *xv)
{
Paul Eggert's avatar
Paul Eggert committed
200
  xv->hidden = false;
201 202 203 204 205 206 207
  gtk_widget_show (xv->widgetwindow);
  gtk_fixed_move (GTK_FIXED (xv->emacswindow),
                  xv->widgetwindow,
                  xv->x + xv->clip_left,
                  xv->y + xv->clip_top);
}

Paul Eggert's avatar
Paul Eggert committed
208
/* Hide an xwidget view.  */
209 210 211
static void
xwidget_hide_view (struct xwidget_view *xv)
{
Paul Eggert's avatar
Paul Eggert committed
212
  xv->hidden = true;
213 214 215 216 217 218
  gtk_fixed_move (GTK_FIXED (xv->emacswindow), xv->widgetwindow,
                  10000, 10000);
}

/* When the off-screen webkit master view changes this signal is called.
   It copies the bitmap from the off-screen instance.  */
219
static gboolean
Paul Eggert's avatar
Paul Eggert committed
220
offscreen_damage_event (GtkWidget *widget, GdkEvent *event,
221 222
                        gpointer xv_widget)
{
Paul Eggert's avatar
Paul Eggert committed
223 224 225 226
  /* Queue a redraw of onscreen widget.
     There is a guard against receiving an invalid widget,
     which should only happen if we failed to remove the
     specific signal handler for the damage event.  */
227 228 229 230
  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",
Paul Eggert's avatar
Paul Eggert committed
231
            xv_widget);
232 233 234 235 236 237 238 239 240 241 242 243 244 245

  return FALSE;
}

static void
store_xwidget_event_string (struct xwidget *xw, const char *eventname,
                            const char *eventstr)
{
  struct input_event event;
  Lisp_Object xwl;
  XSETXWIDGET (xwl, xw);
  EVENT_INIT (event);
  event.kind = XWIDGET_EVENT;
  event.frame_or_window = Qnil;
Paul Eggert's avatar
Paul Eggert committed
246
  event.arg = list3 (intern (eventname), xwl, build_string (eventstr));
247 248 249
  kbd_buffer_store_event (&event);
}

250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
static void
store_xwidget_js_callback_event (struct xwidget *xw,
                                 Lisp_Object proc,
                                 Lisp_Object argument)
{
  struct input_event event;
  Lisp_Object xwl;
  XSETXWIDGET (xwl, xw);
  EVENT_INIT (event);
  event.kind = XWIDGET_EVENT;
  event.frame_or_window = Qnil;
  event.arg = list4 (intern ("javascript-callback"), xwl, proc, argument);
  kbd_buffer_store_event (&event);
}


266
void
Ricardo Wurmus's avatar
Ricardo Wurmus committed
267 268 269
webkit_view_load_changed_cb (WebKitWebView *webkitwebview,
                             WebKitLoadEvent load_event,
                             gpointer data)
270
{
Ricardo Wurmus's avatar
Ricardo Wurmus committed
271 272 273 274 275 276 277 278 279 280 281
  switch (load_event) {
  case WEBKIT_LOAD_FINISHED:
    {
      struct xwidget *xw = g_object_get_data (G_OBJECT (webkitwebview),
                                              XG_XWIDGET);
      store_xwidget_event_string (xw, "load-changed", "");
      break;
    }
  default:
    break;
  }
282 283
}

284
/* Recursively convert a JavaScript value to a Lisp value. */
285
static Lisp_Object
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
webkit_js_to_lisp (JSContextRef context, JSValueRef value)
{
  switch (JSValueGetType (context, value))
    {
    case kJSTypeString:
      {
        JSStringRef js_str_value;
        gchar *str_value;
        gsize str_length;

        js_str_value = JSValueToStringCopy (context, value, NULL);
        str_length = JSStringGetMaximumUTF8CStringSize (js_str_value);
        str_value = (gchar *)g_malloc (str_length);
        JSStringGetUTF8CString (js_str_value, str_value, str_length);
        JSStringRelease (js_str_value);
        return build_string (str_value);
      }
    case kJSTypeBoolean:
      return (JSValueToBoolean (context, value)) ? Qt : Qnil;
    case kJSTypeNumber:
306
      return make_fixnum (JSValueToNumber (context, value, NULL));
307 308 309 310 311
    case kJSTypeObject:
      {
        if (JSValueIsArray (context, value))
          {
            JSStringRef pname = JSStringCreateWithUTF8CString("length");
312 313 314
	    JSValueRef len = JSObjectGetProperty (context, (JSObjectRef) value,
						  pname, NULL);
	    double dlen = JSValueToNumber (context, len, NULL);
315 316 317
            JSStringRelease(pname);

            Lisp_Object obj;
318 319 320
	    if (! (0 <= dlen && dlen < PTRDIFF_MAX + 1.0))
	      memory_full (SIZE_MAX);
	    ptrdiff_t n = dlen;
321 322
            struct Lisp_Vector *p = allocate_vector (n);

323
            for (ptrdiff_t i = 0; i < n; ++i)
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
              {
                p->contents[i] =
                  webkit_js_to_lisp (context,
                                     JSObjectGetPropertyAtIndex (context,
                                                                 (JSObjectRef) value,
                                                                 i, NULL));
              }
            XSETVECTOR (obj, p);
            return obj;
          }
        else
          {
            JSPropertyNameArrayRef properties =
              JSObjectCopyPropertyNames (context, (JSObjectRef) value);

339
	    size_t n = JSPropertyNameArrayGetCount (properties);
340 341
            Lisp_Object obj;

342
            /* TODO: can we use a regular list here?  */
343 344
	    if (PTRDIFF_MAX < n)
	      memory_full (n);
345 346
            struct Lisp_Vector *p = allocate_vector (n);

347
            for (ptrdiff_t i = 0; i < n; ++i)
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379
              {
                JSStringRef name = JSPropertyNameArrayGetNameAtIndex (properties, i);
                JSValueRef property = JSObjectGetProperty (context,
                                                           (JSObjectRef) value,
                                                           name, NULL);
                gchar *str_name;
                gsize str_length;
                str_length = JSStringGetMaximumUTF8CStringSize (name);
                str_name = (gchar *)g_malloc (str_length);
                JSStringGetUTF8CString (name, str_name, str_length);
                JSStringRelease (name);

                p->contents[i] =
                  Fcons (build_string (str_name),
                         webkit_js_to_lisp (context, property));
              }

            JSPropertyNameArrayRelease (properties);
            XSETVECTOR (obj, p);
            return obj;
          }
      }
    case kJSTypeUndefined:
    case kJSTypeNull:
    default:
      return Qnil;
    }
}

static void
webkit_javascript_finished_cb (GObject      *webview,
                               GAsyncResult *result,
380
                               gpointer      arg)
381 382 383 384 385 386 387
{
    WebKitJavascriptResult *js_result;
    JSValueRef value;
    JSGlobalContextRef context;
    GError *error = NULL;
    struct xwidget *xw = g_object_get_data (G_OBJECT (webview),
                                            XG_XWIDGET);
388
    ptrdiff_t script_idx = (intptr_t) arg;
389 390 391
    Lisp_Object script_callback = AREF (xw->script_callbacks, script_idx);
    ASET (xw->script_callbacks, script_idx, Qnil);
    if (!NILP (script_callback))
392
      xfree (xmint_pointer (XCAR (script_callback)));
393 394 395 396 397 398 399 400 401 402 403

    js_result = webkit_web_view_run_javascript_finish
      (WEBKIT_WEB_VIEW (webview), result, &error);

    if (!js_result)
      {
        g_warning ("Error running javascript: %s", error->message);
        g_error_free (error);
        return;
      }

404 405 406 407 408 409 410 411 412 413 414
    if (!NILP (script_callback) && !NILP (XCDR (script_callback)))
      {
	context = webkit_javascript_result_get_global_context (js_result);
	value = webkit_javascript_result_get_value (js_result);
	Lisp_Object lisp_value = webkit_js_to_lisp (context, value);

	/* Register an xwidget event here, which then runs the callback.
	   This ensures that the callback runs in sync with the Emacs
	   event loop.  */
	store_xwidget_js_callback_event (xw, XCDR (script_callback), lisp_value);
      }
415

416
    webkit_javascript_result_unref (js_result);
417 418 419
}


420
gboolean
Ricardo Wurmus's avatar
Ricardo Wurmus committed
421
webkit_download_cb (WebKitWebContext *webkitwebcontext,
Paul Eggert's avatar
Paul Eggert committed
422
                    WebKitDownload *arg1,
423 424
                    gpointer data)
{
Ricardo Wurmus's avatar
Ricardo Wurmus committed
425 426 427
  WebKitWebView *view = webkit_download_get_web_view(arg1);
  WebKitURIRequest *request = webkit_download_get_request(arg1);
  struct xwidget *xw = g_object_get_data (G_OBJECT (view),
428
                                          XG_XWIDGET);
Ricardo Wurmus's avatar
Ricardo Wurmus committed
429 430 431

  store_xwidget_event_string (xw, "download-started",
                              webkit_uri_request_get_uri(request));
432 433 434
  return FALSE;
}

435
static gboolean
Ricardo Wurmus's avatar
Ricardo Wurmus committed
436 437 438 439
webkit_decide_policy_cb (WebKitWebView *webView,
                         WebKitPolicyDecision *decision,
                         WebKitPolicyDecisionType type,
                         gpointer user_data)
440
{
Ricardo Wurmus's avatar
Ricardo Wurmus committed
441 442 443 444 445
  switch (type) {
  case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
    /* This function makes webkit send a download signal for all unknown
       mime types.  TODO: Defer the decision to Lisp, so that it's
       possible to make Emacs handle mime text for instance.  */
446
    {
Ricardo Wurmus's avatar
Ricardo Wurmus committed
447 448 449 450 451 452 453 454 455 456
      WebKitResponsePolicyDecision *response =
        WEBKIT_RESPONSE_POLICY_DECISION (decision);
      if (!webkit_response_policy_decision_is_mime_type_supported (response))
        {
          webkit_policy_decision_download (decision);
          return TRUE;
        }
      else
        return FALSE;
      break;
457
    }
Ricardo Wurmus's avatar
Ricardo Wurmus committed
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
  case WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION:
  case WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION:
    {
      WebKitNavigationPolicyDecision *navigation_decision =
        WEBKIT_NAVIGATION_POLICY_DECISION (decision);
      WebKitNavigationAction *navigation_action =
        webkit_navigation_policy_decision_get_navigation_action (navigation_decision);
      WebKitURIRequest *request =
        webkit_navigation_action_get_request (navigation_action);

      struct xwidget *xw = g_object_get_data (G_OBJECT (webView), XG_XWIDGET);
      store_xwidget_event_string (xw, "decide-policy",
                                  webkit_uri_request_get_uri (request));
      return FALSE;
      break;
    }
  default:
Paul Eggert's avatar
Paul Eggert committed
475
    return FALSE;
Ricardo Wurmus's avatar
Ricardo Wurmus committed
476
  }
477 478 479
}


Paul Eggert's avatar
Paul Eggert committed
480
/* For gtk3 offscreen rendered widgets.  */
481
static gboolean
Paul Eggert's avatar
Paul Eggert committed
482
xwidget_osr_draw_cb (GtkWidget *widget, cairo_t *cr, gpointer data)
483
{
Paul Eggert's avatar
Paul Eggert committed
484 485
  struct xwidget *xw = g_object_get_data (G_OBJECT (widget), XG_XWIDGET);
  struct xwidget_view *xv = g_object_get_data (G_OBJECT (widget),
486 487 488 489 490
                                               XG_XWIDGET_VIEW);

  cairo_rectangle (cr, 0, 0, xv->clip_right, xv->clip_bottom);
  cairo_clip (cr);

491
  gtk_widget_draw (xw->widget_osr, cr);
492 493 494 495
  return FALSE;
}

static gboolean
Paul Eggert's avatar
Paul Eggert committed
496 497
xwidget_osr_event_forward (GtkWidget *widget, GdkEvent *event,
			   gpointer user_data)
498
{
Glenn Morris's avatar
Glenn Morris committed
499
  /* Copy events that arrive at the outer widget to the offscreen widget.  */
Paul Eggert's avatar
Paul Eggert committed
500
  struct xwidget *xw = g_object_get_data (G_OBJECT (widget), XG_XWIDGET);
501 502 503
  GdkEvent *eventcopy = gdk_event_copy (event);
  eventcopy->any.window = gtk_widget_get_window (xw->widget_osr);

Paul Eggert's avatar
Paul Eggert committed
504 505
  /* TODO: This might leak events.  They should be deallocated later,
     perhaps in xwgir_event_cb.  */
506 507
  gtk_main_do_event (eventcopy);

Paul Eggert's avatar
Paul Eggert committed
508 509 510
  /* Don't propagate this event further.  */
  return TRUE;
}
511 512

static gboolean
Paul Eggert's avatar
Paul Eggert committed
513 514
xwidget_osr_event_set_embedder (GtkWidget *widget, GdkEvent *event,
				gpointer data)
515
{
Paul Eggert's avatar
Paul Eggert committed
516
  struct xwidget_view *xv = data;
517 518
  struct xwidget *xww = XXWIDGET (xv->model);
  gdk_offscreen_window_set_embedder (gtk_widget_get_window
Paul Eggert's avatar
Paul Eggert committed
519
				     (xww->widgetwindow_osr),
520 521 522 523 524
                                     gtk_widget_get_window (xv->widget));
  return FALSE;
}


Glenn Morris's avatar
Glenn Morris committed
525
/* Initializes and does initial placement of an xwidget view on screen.  */
526 527 528 529 530
static struct xwidget_view *
xwidget_init_view (struct xwidget *xww,
                   struct glyph_string *s,
                   int x, int y)
{
531 532 533 534

  if (!xg_gtk_initialized)
    error ("xwidget_init_view: GTK has not been initialized");

535 536 537 538 539 540 541 542 543
  struct xwidget_view *xv = allocate_xwidget_view ();
  Lisp_Object val;

  XSETXWIDGET_VIEW (val, xv);
  Vxwidget_view_list = Fcons (val, Vxwidget_view_list);

  XSETWINDOW (xv->w, s->w);
  XSETXWIDGET (xv->model, xww);

Paul Eggert's avatar
Paul Eggert committed
544
  if (EQ (xww->type, Qwebkit))
545 546
    {
      xv->widget = gtk_drawing_area_new ();
Paul Eggert's avatar
Paul Eggert committed
547
      /* Expose event handling.  */
548 549 550
      gtk_widget_set_app_paintable (xv->widget, TRUE);
      gtk_widget_add_events (xv->widget, GDK_ALL_EVENTS_MASK);

Paul Eggert's avatar
Paul Eggert committed
551
      /* Draw the view on damage-event.  */
552 553 554
      g_signal_connect (G_OBJECT (xww->widgetwindow_osr), "damage-event",
                        G_CALLBACK (offscreen_damage_event), xv->widget);

Paul Eggert's avatar
Paul Eggert committed
555
      if (EQ (xww->type, Qwebkit))
556 557 558 559 560 561 562 563 564 565
        {
          g_signal_connect (G_OBJECT (xv->widget), "button-press-event",
                            G_CALLBACK (xwidget_osr_event_forward), NULL);
          g_signal_connect (G_OBJECT (xv->widget), "button-release-event",
                            G_CALLBACK (xwidget_osr_event_forward), NULL);
          g_signal_connect (G_OBJECT (xv->widget), "motion-notify-event",
                            G_CALLBACK (xwidget_osr_event_forward), NULL);
        }
      else
        {
Paul Eggert's avatar
Paul Eggert committed
566
          /* xwgir debug, orthogonal to forwarding.  */
567 568 569 570 571 572 573
          g_signal_connect (G_OBJECT (xv->widget), "enter-notify-event",
                            G_CALLBACK (xwidget_osr_event_set_embedder), xv);
        }
      g_signal_connect (G_OBJECT (xv->widget), "draw",
                        G_CALLBACK (xwidget_osr_draw_cb), NULL);
    }

Paul Eggert's avatar
Paul Eggert committed
574 575 576 577 578 579
  /* Widget realization.

     Make container widget first, and put the actual widget inside the
     container later.  Drawing should crop container window if necessary
     to handle case where xwidget is partially obscured by other Emacs
     windows.  Other containers than gtk_fixed where explored, but
580
     gtk_fixed had the most predictable behavior so far.  */
Paul Eggert's avatar
Paul Eggert committed
581

582 583 584 585 586
  xv->emacswindow = FRAME_GTK_WIDGET (s->f);
  xv->widgetwindow = gtk_fixed_new ();
  gtk_widget_set_has_window (xv->widgetwindow, TRUE);
  gtk_container_add (GTK_CONTAINER (xv->widgetwindow), xv->widget);

Paul Eggert's avatar
Paul Eggert committed
587 588 589 590 591 592
  /* Store some xwidget data in the gtk widgets.  */
  g_object_set_data (G_OBJECT (xv->widget), XG_FRAME_DATA, s->f);
  g_object_set_data (G_OBJECT (xv->widget), XG_XWIDGET, xww);
  g_object_set_data (G_OBJECT (xv->widget), XG_XWIDGET_VIEW, xv);
  g_object_set_data (G_OBJECT (xv->widgetwindow), XG_XWIDGET, xww);
  g_object_set_data (G_OBJECT (xv->widgetwindow), XG_XWIDGET_VIEW, xv);
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609

  gtk_widget_set_size_request (GTK_WIDGET (xv->widget), xww->width,
                               xww->height);
  gtk_widget_set_size_request (xv->widgetwindow, xww->width, xww->height);
  gtk_fixed_put (GTK_FIXED (FRAME_GTK_WIDGET (s->f)), xv->widgetwindow, x, y);
  xv->x = x;
  xv->y = y;
  gtk_widget_show_all (xv->widgetwindow);

  return xv;
}

void
x_draw_xwidget_glyph_string (struct glyph_string *s)
{
  /* This method is called by the redisplay engine and places the
     xwidget on screen.  Moving and clipping is done here.  Also view
Paul Eggert's avatar
Paul Eggert committed
610
     initialization.  */
611
  struct xwidget *xww = s->xwidget;
612
  struct xwidget_view *xv = xwidget_view_lookup (xww, s->w);
613 614 615 616 617 618 619 620
  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);

Paul Eggert's avatar
Paul Eggert committed
621
  /* Do initialization here in the display loop because there is no
622 623 624 625
     other time to know things like window placement etc.  Do not
     create a new view if we have found one that is usable.  */
  if (!xv)
    xv = xwidget_init_view (xww, s, x, y);
626

Joakim Verona's avatar
Joakim Verona committed
627 628
  int text_area_x, text_area_y, text_area_width, text_area_height;

629 630 631 632 633 634 635 636
  window_box (s->w, TEXT_AREA, &text_area_x, &text_area_y,
              &text_area_width, &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));
  clip_top = max (0, text_area_y - y);
  clip_bottom = max (clip_top,
		     min (xww->height, text_area_y + text_area_height - y));
637

Paul Eggert's avatar
Paul Eggert committed
638
  /* We are concerned with movement of the onscreen area.  The area
Paul Eggert's avatar
Paul Eggert committed
639 640 641 642 643 644 645 646 647
     might sit still when the widget actually moves.  This happens
     when an Emacs window border moves across a widget window.  So, if
     any corner of the outer widget clipping window moves, that counts
     as movement here, even if it looks like no movement happens
     because the widget sits still inside the clipping area.  The
     widget can also move inside the clipping area, which happens
     later.  */
  bool moved = (xv->x + xv->clip_left != x + clip_left
		|| xv->y + xv->clip_top != y + clip_top);
648 649
  xv->x = x;
  xv->y = y;
Paul Eggert's avatar
Paul Eggert committed
650 651 652 653 654 655 656 657 658

  /* Has it moved?  */
  if (moved)
    gtk_fixed_move (GTK_FIXED (FRAME_GTK_WIDGET (s->f)),
		    xv->widgetwindow, x + clip_left, y + clip_top);

  /* Clip the widget window if some parts happen to be outside
     drawable area.  An Emacs window is not a gtk window.  A gtk window
     covers the entire frame.  Clipping might have changed even if we
Paul Eggert's avatar
Paul Eggert committed
659
     haven't actually moved; try to figure out when we need to reclip
Paul Eggert's avatar
Paul Eggert committed
660 661 662 663
     for real.  */
  if (xv->clip_right != clip_right
      || xv->clip_bottom != clip_bottom
      || xv->clip_top != clip_top || xv->clip_left != clip_left)
664
    {
665 666
      gtk_widget_set_size_request (xv->widgetwindow, clip_right - clip_left,
                                   clip_bottom - clip_top);
667 668 669 670 671 672 673 674
      gtk_fixed_move (GTK_FIXED (xv->widgetwindow), xv->widget, -clip_left,
                      -clip_top);

      xv->clip_right = clip_right;
      xv->clip_bottom = clip_bottom;
      xv->clip_top = clip_top;
      xv->clip_left = clip_left;
    }
Paul Eggert's avatar
Paul Eggert committed
675 676 677 678 679

  /* If emacs wants to repaint the area where the widget lives, queue
     a redraw.  It seems its possible to get out of sync with emacs
     redraws so emacs background sometimes shows up instead of the
     xwidgets background.  It's just a visual glitch though.  */
680 681 682 683 684 685 686
  if (!xwidget_hidden (xv))
    {
      gtk_widget_queue_draw (xv->widgetwindow);
      gtk_widget_queue_draw (xv->widget);
    }
}

Paul Eggert's avatar
Paul Eggert committed
687 688 689 690 691 692 693 694 695
/* Macro that checks WEBKIT_IS_WEB_VIEW (xw->widget_osr) first.  */
#define WEBKIT_FN_INIT()						\
  CHECK_XWIDGET (xwidget);						\
  struct xwidget *xw = XXWIDGET (xwidget);				\
  if (!xw->widget_osr || !WEBKIT_IS_WEB_VIEW (xw->widget_osr))		\
    {									\
      printf ("ERROR xw->widget_osr does not hold a webkit instance\n"); \
      return Qnil;							\
    }
696 697 698 699

DEFUN ("xwidget-webkit-goto-uri",
       Fxwidget_webkit_goto_uri, Sxwidget_webkit_goto_uri,
       2, 2, 0,
Glenn Morris's avatar
Glenn Morris committed
700
       doc: /* Make the xwidget webkit instance referenced by XWIDGET browse URI.  */)
701 702 703 704
  (Lisp_Object xwidget, Lisp_Object uri)
{
  WEBKIT_FN_INIT ();
  CHECK_STRING (uri);
705
  uri = ENCODE_FILE (uri);
706 707 708 709
  webkit_web_view_load_uri (WEBKIT_WEB_VIEW (xw->widget_osr), SSDATA (uri));
  return Qnil;
}

710 711 712
DEFUN ("xwidget-webkit-zoom",
       Fxwidget_webkit_zoom, Sxwidget_webkit_zoom,
       2, 2, 0,
713
       doc: /* Change the zoom factor of the xwidget webkit instance referenced by XWIDGET.  */)
714 715 716 717 718 719 720 721 722 723 724 725 726 727
  (Lisp_Object xwidget, Lisp_Object factor)
{
  WEBKIT_FN_INIT ();
  if (FLOATP (factor))
    {
      double zoom_change = XFLOAT_DATA (factor);
      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);
    }
  return Qnil;
}

728 729 730 731 732 733 734
/* Save script and fun in the script/callback save vector and return
   its index.  */
static ptrdiff_t
save_script_callback (struct xwidget *xw, Lisp_Object script, Lisp_Object fun)
{
  Lisp_Object cbs = xw->script_callbacks;
  if (NILP (cbs))
735
    xw->script_callbacks = cbs = make_nil_vector (32);
736 737

  /* Find first free index.  */
738 739 740 741 742 743 744 745
  ptrdiff_t idx;
  for (idx = 0; !NILP (AREF (cbs, idx)); idx++)
    if (idx + 1 == ASIZE (cbs))
      {
	xw->script_callbacks = cbs = larger_vector (cbs, 1, -1);
	break;
      }

746
  ASET (cbs, idx, Fcons (make_mint_ptr (xlispstrdup (script)), fun));
747 748
  return idx;
}
749 750 751

DEFUN ("xwidget-webkit-execute-script",
       Fxwidget_webkit_execute_script, Sxwidget_webkit_execute_script,
752
       2, 3, 0,
753 754
       doc: /* Make the Webkit XWIDGET execute JavaScript SCRIPT.
If FUN is provided, feed the JavaScript return value to the single
755 756
argument procedure FUN.*/)
  (Lisp_Object xwidget, Lisp_Object script, Lisp_Object fun)
757 758 759
{
  WEBKIT_FN_INIT ();
  CHECK_STRING (script);
760
  if (!NILP (fun) && !FUNCTIONP (fun))
761 762
    wrong_type_argument (Qinvalid_function, fun);

763
  script = ENCODE_SYSTEM (script);
764

765
  /* Protect script and fun during GC.  */
766
  intptr_t idx = save_script_callback (xw, script, fun);
767

768 769 770
  /* JavaScript execution happens asynchronously.  If an elisp
     callback function is provided we pass it to the C callback
     procedure that retrieves the return value.  */
Paul Eggert's avatar
Paul Eggert committed
771
  gchar *script_string
772
    = xmint_pointer (XCAR (AREF (xw->script_callbacks, idx)));
Ricardo Wurmus's avatar
Ricardo Wurmus committed
773
  webkit_web_view_run_javascript (WEBKIT_WEB_VIEW (xw->widget_osr),
Paul Eggert's avatar
Paul Eggert committed
774
				  script_string,
Paul Eggert's avatar
Paul Eggert committed
775
                                  NULL, /* cancelable */
776 777
                                  webkit_javascript_finished_cb,
				  (gpointer) idx);
778 779 780 781
  return Qnil;
}

DEFUN ("xwidget-resize", Fxwidget_resize, Sxwidget_resize, 3, 3, 0,
782
       doc: /* Resize XWIDGET to NEW_WIDTH, NEW_HEIGHT.  */ )
783 784 785
  (Lisp_Object xwidget, Lisp_Object new_width, Lisp_Object new_height)
{
  CHECK_XWIDGET (xwidget);
786 787
  CHECK_RANGED_INTEGER (new_width, 0, INT_MAX);
  CHECK_RANGED_INTEGER (new_height, 0, INT_MAX);
788
  struct xwidget *xw = XXWIDGET (xwidget);
Tom Tromey's avatar
Tom Tromey committed
789 790
  int w = XFIXNAT (new_width);
  int h = XFIXNAT (new_height);
791 792 793

  xw->width = w;
  xw->height = h;
Paul Eggert's avatar
Paul Eggert committed
794 795

  /* If there is an offscreen widget resize it first.  */
796 797 798 799 800
  if (xw->widget_osr)
    {
      gtk_window_resize (GTK_WINDOW (xw->widgetwindow_osr), xw->width,
                         xw->height);
      gtk_container_resize_children (GTK_CONTAINER (xw->widgetwindow_osr));
801 802
      gtk_widget_set_size_request (GTK_WIDGET (xw->widget_osr), xw->width,
                                   xw->height);
803 804 805 806 807 808
    }

  for (Lisp_Object tail = Vxwidget_view_list; CONSP (tail); tail = XCDR (tail))
    {
      if (XWIDGET_VIEW_P (XCAR (tail)))
        {
Paul Eggert's avatar
Paul Eggert committed
809
          struct xwidget_view *xv = XXWIDGET_VIEW (XCAR (tail));
810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832
          if (XXWIDGET (xv->model) == xw)
              gtk_widget_set_size_request (GTK_WIDGET (xv->widget), xw->width,
                                           xw->height);
        }
    }

  return Qnil;
}




DEFUN ("xwidget-size-request",
       Fxwidget_size_request, Sxwidget_size_request,
       1, 1, 0,
       doc: /* Return the desired size of the XWIDGET.
This can be used to read the xwidget desired size, and resizes the
Emacs allocated area accordingly.  */)
  (Lisp_Object xwidget)
{
  CHECK_XWIDGET (xwidget);
  GtkRequisition requisition;
  gtk_widget_size_request (XXWIDGET (xwidget)->widget_osr, &requisition);
Paul Eggert's avatar
Paul Eggert committed
833
  return list2i (requisition.width, requisition.height);
834 835 836 837 838
}

DEFUN ("xwidgetp",
       Fxwidgetp, Sxwidgetp,
       1, 1, 0,
Glenn Morris's avatar
Glenn Morris committed
839
       doc: /* Return t if OBJECT is an xwidget.  */)
840 841 842 843 844 845 846 847
  (Lisp_Object object)
{
  return XWIDGETP (object) ? Qt : Qnil;
}

DEFUN ("xwidget-view-p",
       Fxwidget_view_p, Sxwidget_view_p,
       1, 1, 0,
Glenn Morris's avatar
Glenn Morris committed
848
       doc: /* Return t if OBJECT is an xwidget-view.  */)
849 850 851 852 853 854 855 856
  (Lisp_Object object)
{
  return XWIDGET_VIEW_P (object) ? Qt : Qnil;
}

DEFUN ("xwidget-info",
       Fxwidget_info, Sxwidget_info,
       1, 1, 0,
Glenn Morris's avatar
Glenn Morris committed
857 858
       doc: /* Return XWIDGET properties in a vector.
Currently [TYPE TITLE WIDTH HEIGHT].  */)
859 860 861 862
  (Lisp_Object xwidget)
{
  CHECK_XWIDGET (xwidget);
  struct xwidget *xw = XXWIDGET (xwidget);
Paul Eggert's avatar
Paul Eggert committed
863
  return CALLN (Fvector, xw->type, xw->title,
864
		make_fixed_natnum (xw->width), make_fixed_natnum (xw->height));
865 866 867 868 869 870
}

DEFUN ("xwidget-view-info",
       Fxwidget_view_info, Sxwidget_view_info,
       1, 1, 0,
       doc: /* Return properties of XWIDGET-VIEW in a vector.
Glenn Morris's avatar
Glenn Morris committed
871
Currently [X Y CLIP_RIGHT CLIP_BOTTOM CLIP_TOP CLIP_LEFT].  */)
872 873 874 875
  (Lisp_Object xwidget_view)
{
  CHECK_XWIDGET_VIEW (xwidget_view);
  struct xwidget_view *xv = XXWIDGET_VIEW (xwidget_view);
876 877 878
  return CALLN (Fvector, make_fixnum (xv->x), make_fixnum (xv->y),
		make_fixnum (xv->clip_right), make_fixnum (xv->clip_bottom),
		make_fixnum (xv->clip_top), make_fixnum (xv->clip_left));
879 880 881 882 883
}

DEFUN ("xwidget-view-model",
       Fxwidget_view_model, Sxwidget_view_model,
       1, 1, 0,
Glenn Morris's avatar
Glenn Morris committed
884
       doc:  /* Return the model associated with XWIDGET-VIEW.  */)
885 886 887 888 889 890 891 892 893
  (Lisp_Object xwidget_view)
{
  CHECK_XWIDGET_VIEW (xwidget_view);
  return XXWIDGET_VIEW (xwidget_view)->model;
}

DEFUN ("xwidget-view-window",
       Fxwidget_view_window, Sxwidget_view_window,
       1, 1, 0,
Glenn Morris's avatar
Glenn Morris committed
894
       doc:  /* Return the window of XWIDGET-VIEW.  */)
895 896 897 898 899 900 901 902 903 904
  (Lisp_Object xwidget_view)
{
  CHECK_XWIDGET_VIEW (xwidget_view);
  return XXWIDGET_VIEW (xwidget_view)->w;
}


DEFUN ("delete-xwidget-view",
       Fdelete_xwidget_view, Sdelete_xwidget_view,
       1, 1, 0,
Glenn Morris's avatar
Glenn Morris committed
905
       doc:  /* Delete the XWIDGET-VIEW.  */)
906 907 908 909 910 911
  (Lisp_Object 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);
Paul Eggert's avatar
Paul Eggert committed
912 913
  /* xv->model still has signals pointing to the view.  There can be
     several views.  Find the matching signals and delete them all.  */
914 915 916 917 918 919 920 921 922 923
  g_signal_handlers_disconnect_matched  (XXWIDGET (xv->model)->widgetwindow_osr,
                                         G_SIGNAL_MATCH_DATA,
                                         0, 0, 0, 0,
                                         xv->widget);
  return Qnil;
}

DEFUN ("xwidget-view-lookup",
       Fxwidget_view_lookup, Sxwidget_view_lookup,
       1, 2, 0,
Glenn Morris's avatar
Glenn Morris committed
924 925 926
       doc: /* Return the xwidget-view associated with XWIDGET in WINDOW.
If WINDOW is unspecified or nil, use the selected window.
Return nil if no association is found.  */)
927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
  (Lisp_Object xwidget, Lisp_Object window)
{
  CHECK_XWIDGET (xwidget);

  if (NILP (window))
    window = Fselected_window ();
  CHECK_WINDOW (window);

  for (Lisp_Object tail = Vxwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      Lisp_Object xwidget_view = XCAR (tail);
      if (EQ (Fxwidget_view_model (xwidget_view), xwidget)
          && EQ (Fxwidget_view_window (xwidget_view), window))
        return xwidget_view;
    }

  return Qnil;
}

DEFUN ("xwidget-plist",
       Fxwidget_plist, Sxwidget_plist,
       1, 1, 0,
       doc: /* Return the plist of XWIDGET.  */)
Paul Eggert's avatar
Paul Eggert committed
951
  (Lisp_Object xwidget)
952 953 954 955 956 957 958 959 960
{
  CHECK_XWIDGET (xwidget);
  return XXWIDGET (xwidget)->plist;
}

DEFUN ("xwidget-buffer",
       Fxwidget_buffer, Sxwidget_buffer,
       1, 1, 0,
       doc: /* Return the buffer of XWIDGET.  */)
Paul Eggert's avatar
Paul Eggert committed
961
  (Lisp_Object xwidget)
962 963 964 965 966 967 968 969 970 971
{
  CHECK_XWIDGET (xwidget);
  return XXWIDGET (xwidget)->buffer;
}

DEFUN ("set-xwidget-plist",
       Fset_xwidget_plist, Sset_xwidget_plist,
       2, 2, 0,
       doc: /* Replace the plist of XWIDGET with PLIST.
Returns PLIST.  */)
Paul Eggert's avatar
Paul Eggert committed
972
  (Lisp_Object xwidget, Lisp_Object plist)
973 974 975 976 977 978 979 980 981 982 983
{
  CHECK_XWIDGET (xwidget);
  CHECK_LIST (plist);

  XXWIDGET (xwidget)->plist = plist;
  return plist;
}

DEFUN ("set-xwidget-query-on-exit-flag",
       Fset_xwidget_query_on_exit_flag, Sset_xwidget_query_on_exit_flag,
       2, 2, 0,
Glenn Morris's avatar
Glenn Morris committed
984 985 986 987
       doc: /* Specify if query is needed for XWIDGET when Emacs is exited.
If the second argument FLAG is non-nil, Emacs will query the user before
exiting or killing a buffer if XWIDGET is running.
This function returns FLAG.  */)
988 989 990 991 992 993 994 995 996 997
  (Lisp_Object xwidget, Lisp_Object flag)
{
  CHECK_XWIDGET (xwidget);
  XXWIDGET (xwidget)->kill_without_query = NILP (flag);
  return flag;
}

DEFUN ("xwidget-query-on-exit-flag",
       Fxwidget_query_on_exit_flag, Sxwidget_query_on_exit_flag,
       1, 1, 0,
Glenn Morris's avatar
Glenn Morris committed
998
       doc: /* Return the current value of the query-on-exit flag for XWIDGET.  */)
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
  (Lisp_Object xwidget)
{
  CHECK_XWIDGET (xwidget);
  return (XXWIDGET (xwidget)->kill_without_query ? Qnil : Qt);
}

void
syms_of_xwidget (void)
{
  defsubr (&Smake_xwidget);
  defsubr (&Sxwidgetp);
  DEFSYM (Qxwidgetp, "xwidgetp");
  defsubr (&Sxwidget_view_p);
  DEFSYM (Qxwidget_view_p, "xwidget-view-p");
  defsubr (&Sxwidget_info);
  defsubr (&Sxwidget_view_info);
  defsubr (&Sxwidget_resize);
  defsubr (&Sget_buffer_xwidgets);
  defsubr (&Sxwidget_view_model);
  defsubr (&Sxwidget_view_window);
  defsubr (&Sxwidget_view_lookup);
  defsubr (&Sxwidget_query_on_exit_flag);
  defsubr (&Sset_xwidget_query_on_exit_flag);

  defsubr (&Sxwidget_webkit_goto_uri);
1024
  defsubr (&Sxwidget_webkit_zoom);
1025
  defsubr (&Sxwidget_webkit_execute_script);
Paul Eggert's avatar
Paul Eggert committed
1026
  DEFSYM (Qwebkit, "webkit");
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038

  defsubr (&Sxwidget_size_request);
  defsubr (&Sdelete_xwidget_view);

  defsubr (&Sxwidget_plist);
  defsubr (&Sxwidget_buffer);
  defsubr (&Sset_xwidget_plist);

  DEFSYM (QCxwidget, ":xwidget");
  DEFSYM (QCtitle, ":title");

  /* Do not forget to update the docstring of make-xwidget if you add
Glenn Morris's avatar
Glenn Morris committed
1039
     new types.  */
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

  DEFSYM (Qvertical, "vertical");
  DEFSYM (Qhorizontal, "horizontal");

  DEFSYM (QCplist, ":plist");

  DEFVAR_LISP ("xwidget-list", Vxwidget_list,
               doc:	/* xwidgets list.  */);
  Vxwidget_list = Qnil;

  DEFVAR_LISP ("xwidget-view-list", Vxwidget_view_list,
             doc:	/* xwidget views list.  */);
  Vxwidget_view_list = Qnil;

  Fprovide (intern ("xwidget-internal"), Qnil);
}


/* Value is non-zero if OBJECT is a valid Lisp xwidget specification.  A
   valid xwidget specification is a list whose car is the symbol
   `xwidget', and whose rest is a property list.  The property list must
   contain a value for key `:type'.  That value must be the name of a
   supported xwidget type.  The rest of the property list depends on the
   xwidget type.  */

bool
valid_xwidget_spec_p (Lisp_Object object)
{
Paul Eggert's avatar
Paul Eggert committed
1068
  return CONSP (object) && EQ (XCAR (object), Qxwidget);
1069 1070 1071 1072
}


/* Find a value associated with key in spec.  */
1073
static Lisp_Object
Paul Eggert's avatar
Paul Eggert committed
1074
xwidget_spec_value (Lisp_Object spec, Lisp_Object key)
1075 1076 1077 1078 1079 1080 1081 1082 1083
{
  Lisp_Object tail;

  eassert (valid_xwidget_spec_p (spec));

  for (tail = XCDR (spec);
       CONSP (tail) && CONSP (XCDR (tail)); tail = XCDR (XCDR (tail)))
    {
      if (EQ (XCAR (tail), key))
Paul Eggert's avatar
Paul Eggert committed
1084
	return XCAR (XCDR (tail));
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
    }

  return Qnil;
}


void
xwidget_view_delete_all_in_window (struct window *w)
{
  struct xwidget_view *xv = NULL;
  for (Lisp_Object tail = Vxwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      if (XWIDGET_VIEW_P (XCAR (tail)))
        {
          xv = XXWIDGET_VIEW (XCAR (tail));
          if (XWINDOW (xv->w) == w)
            {
              Fdelete_xwidget_view (XCAR (tail));
            }
        }
    }
}

1109
static struct xwidget_view *
1110 1111 1112 1113 1114 1115 1116 1117
xwidget_view_lookup (struct xwidget *xw, struct window *w)
{
  Lisp_Object xwidget, window, ret;
  XSETXWIDGET (xwidget, xw);
  XSETWINDOW (window, w);

  ret = Fxwidget_view_lookup (xwidget, window);

Paul Eggert's avatar
Paul Eggert committed
1118
  return NILP (ret) ? NULL : XXWIDGET_VIEW (ret);
1119 1120 1121 1122 1123 1124 1125
}

struct xwidget *
lookup_xwidget (Lisp_Object spec)
{
  /* When a xwidget lisp spec is found initialize the C struct that is
     used in the C code.  This is done by redisplay so values change
Paul Eggert's avatar
Paul Eggert committed
1126
     if the spec changes.  So, take special care of one-shot events.  */
1127 1128 1129
  Lisp_Object value;
  struct xwidget *xw;

Paul Eggert's avatar
Paul Eggert committed
1130
  value = xwidget_spec_value (spec, QCxwidget);
1131 1132 1133 1134 1135
  xw = XXWIDGET (value);

  return xw;
}

Paul Eggert's avatar
Paul Eggert committed
1136
/* Set up detection of touched xwidget.  */
1137
static void
1138 1139 1140 1141 1142 1143
xwidget_start_redisplay (void)
{
  for (Lisp_Object tail = Vxwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      if (XWIDGET_VIEW_P (XCAR (tail)))
Paul Eggert's avatar
Paul Eggert committed
1144
        XXWIDGET_VIEW (XCAR (tail))->redisplayed = false;
1145 1146 1147 1148 1149
    }
}

/* The xwidget was touched during redisplay, so it isn't a candidate
   for hiding.  */
1150
static void
1151 1152
xwidget_touch (struct xwidget_view *xv)
{
Paul Eggert's avatar
Paul Eggert committed
1153
  xv->redisplayed = true;
1154 1155
}

Paul Eggert's avatar
Paul Eggert committed
1156
static bool
1157 1158 1159 1160 1161
xwidget_touched (struct xwidget_view *xv)
{
  return xv->redisplayed;
}

Paul Eggert's avatar
Paul Eggert committed
1162
/* Redisplay has ended, now we should hide untouched xwidgets.  */
1163 1164 1165 1166 1167 1168 1169
void
xwidget_end_redisplay (struct window *w, struct glyph_matrix *matrix)
{
  int i;
  int area;

  xwidget_start_redisplay ();
Paul Eggert's avatar
Paul Eggert committed
1170 1171
  /* Iterate desired glyph matrix of window here, hide gtk widgets
     not in the desired matrix.
1172

Paul Eggert's avatar
Paul Eggert committed
1173
     This only takes care of xwidgets in active windows.  If a window
Paul Eggert's avatar
Paul Eggert committed
1174
     goes away from the screen, xwidget views must be deleted.
1175

Paul Eggert's avatar
Paul Eggert committed
1176
     dump_glyph_matrix (matrix, 2);  */
1177 1178
  for (i = 0; i < matrix->nrows; ++i)
    {
Paul Eggert's avatar
Paul Eggert committed
1179
      /* dump_glyph_row (MATRIX_ROW (matrix, i), i, glyphs); */
1180 1181
      struct glyph_row *row;
      row = MATRIX_ROW (matrix, i);
Paul Eggert's avatar
Paul Eggert committed
1182 1183 1184 1185 1186 1187 1188 1189 1190 1191
      if (row->enabled_p)
	for (area = LEFT_MARGIN_AREA; area < LAST_AREA; ++area)
	  {
	    struct glyph *glyph = row->glyphs[area];
	    struct glyph *glyph_end = glyph + row->used[area];
	    for (; glyph < glyph_end; ++glyph)
	      if (glyph->type == XWIDGET_GLYPH)
		{
		  /* The only call to xwidget_end_redisplay is in dispnew.
		     xwidget_end_redisplay (w->current_matrix);  */
1192 1193 1194 1195 1196 1197 1198
		  struct xwidget_view *xv
		    = xwidget_view_lookup (glyph->u.xwidget, w);
		  /* 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);
Paul Eggert's avatar
Paul Eggert committed
1199 1200
		}
	  }
1201 1202 1203 1204 1205 1206 1207 1208 1209
    }

  for (Lisp_Object tail = Vxwidget_view_list; CONSP (tail);
       tail = XCDR (tail))
    {
      if (XWIDGET_VIEW_P (XCAR (tail)))
        {
          struct xwidget_view *xv = XXWIDGET_VIEW (XCAR (tail));

Paul Eggert's avatar
Paul Eggert committed
1210 1211
          /* "touched" is only meaningful for the current window, so
             disregard other views.  */
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222
          if (XWINDOW (xv->w) == w)
            {
              if (xwidget_touched (xv))
                xwidget_show_view (xv);
              else
                xwidget_hide_view (xv);
            }
        }
    }
}

Glenn Morris's avatar
Glenn Morris committed
1223
/* Kill all xwidget in BUFFER.  */
1224 1225 1226 1227 1228 1229 1230 1231
void
kill_buffer_xwidgets (Lisp_Object buffer)
{
  Lisp_Object tail, xwidget;
  for (tail = Fget_buffer_xwidgets (buffer); CONSP (tail); tail = XCDR (tail))
    {
      xwidget = XCAR (tail);
      Vxwidget_list = Fdelq (xwidget, Vxwidget_list);
Paul Eggert's avatar
Paul Eggert committed
1232
      /* TODO free the GTK things in xw.  */
1233 1234 1235 1236 1237 1238 1239 1240
      {
        CHECK_XWIDGET (xwidget);
        struct xwidget *xw = XXWIDGET (xwidget);
        if (xw->widget_osr && xw->widgetwindow_osr)
          {
            gtk_widget_destroy (xw->widget_osr);
            gtk_widget_destroy (xw->widgetwindow_osr);
          }
1241
	if (!NILP (xw->script_callbacks))
Paul Eggert's avatar
Paul Eggert committed
1242 1243 1244 1245
	  for (ptrdiff_t idx = 0; idx < ASIZE (xw->script_callbacks); idx++)
	    {
	      Lisp_Object cb = AREF (xw->script_callbacks, idx);
	      if (!NILP (cb))
1246
		xfree (xmint_pointer (XCAR (cb)));
Paul Eggert's avatar
Paul Eggert committed
1247 1248
	      ASET (xw->script_callbacks, idx, Qnil);
	    }
1249 1250 1251
      }
    }
}