webkitchatcontainer.cpp 28.5 KB
Newer Older
aviau's avatar
aviau committed
1
/*
2
 *  Copyright (C) 2016-2019 Savoir-faire Linux Inc.
aviau's avatar
aviau committed
3
 *  Author: Alexandre Viau <alexandre.viau@savoirfairelinux.com>
4
 *  Author: Sébastien Blin <sebastien.blin@savoirfairelinux.com>
5
 *  Author: Hugo Lefeuvre <hugo.lefeuvre@savoirfairelinux.com>
aviau's avatar
aviau committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
 *
 *  This program 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.
 *
 *  This program 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 this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.
 */

#include "webkitchatcontainer.h"

// GTK+ related
#include <webkit2/webkit2.h>

// Qt
28
#include <QtCore/QJsonArray>
aviau's avatar
aviau committed
29 30 31 32 33 34
#include <QtCore/QJsonValue>
#include <QtCore/QJsonObject>
#include <QtCore/QJsonDocument>

// LRC
#include <globalinstances.h>
35
#include <api/conversationmodel.h>
36
#include <api/account.h>
aviau's avatar
aviau committed
37

38
// Jami  Client
aviau's avatar
aviau committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
#include "native/pixbufmanipulator.h"

struct _WebKitChatContainer
{
    GtkBox parent;
};

struct _WebKitChatContainerClass
{
    GtkBoxClass parent_class;
};

typedef struct _WebKitChatContainerPrivate WebKitChatContainerPrivate;

struct _WebKitChatContainerPrivate
{
    GtkWidget* webview_chat;
56
    GtkWidget* box_webview_chat;
aviau's avatar
aviau committed
57 58

    bool       chatview_debug;
59
    gchar*     data_received;
aviau's avatar
aviau committed
60 61 62 63 64 65 66 67 68 69 70 71 72

    /* Array of javascript libraries to load. Used during initialization */
    GList*     js_libs_to_load;
    gboolean   js_libs_loaded;
};

G_DEFINE_TYPE_WITH_PRIVATE(WebKitChatContainer, webkit_chat_container, GTK_TYPE_BOX);

#define WEBKIT_CHAT_CONTAINER_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), WEBKIT_CHAT_CONTAINER_TYPE, WebKitChatContainerPrivate))

/* signals */
enum {
    READY,
73
    SCRIPT_DIALOG,
74
    DATA_DROPPED,
aviau's avatar
aviau committed
75 76 77 78 79
    LAST_SIGNAL
};

static guint webkit_chat_container_signals[LAST_SIGNAL] = { 0 };

80 81 82
/* functions */
static gboolean webview_crashed(WebKitChatContainer *self);

aviau's avatar
aviau committed
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
static void
webkit_chat_container_dispose(GObject *object)
{
    G_OBJECT_CLASS(webkit_chat_container_parent_class)->dispose(object);
}

static void
webkit_chat_container_init(WebKitChatContainer *view)
{
    gtk_widget_init_template(GTK_WIDGET(view));
}

static void
webkit_chat_container_class_init(WebKitChatContainerClass *klass)
{
    G_OBJECT_CLASS(klass)->dispose = webkit_chat_container_dispose;

    gtk_widget_class_set_template_from_resource(GTK_WIDGET_CLASS (klass),
101
                                                "/net/jami/JamiGnome/webkitchatcontainer.ui");
aviau's avatar
aviau committed
102

103
    gtk_widget_class_bind_template_child_private(GTK_WIDGET_CLASS (klass), WebKitChatContainer, box_webview_chat);
aviau's avatar
aviau committed
104 105 106 107 108 109 110 111 112 113

    /* add signals */
    webkit_chat_container_signals[READY] = g_signal_new("ready",
        G_TYPE_FROM_CLASS(klass),
        (GSignalFlags) (G_SIGNAL_RUN_FIRST | G_SIGNAL_ACTION),
        0,
        nullptr,
        nullptr,
        g_cclosure_marshal_VOID__VOID,
        G_TYPE_NONE, 0);
114

115
    webkit_chat_container_signals[SCRIPT_DIALOG] = g_signal_new("script-dialog",
116 117 118 119 120 121 122
        G_TYPE_FROM_CLASS(klass),
        (GSignalFlags) (G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED),
        0,
        nullptr,
        nullptr,
        g_cclosure_marshal_VOID__STRING,
        G_TYPE_NONE, 1, G_TYPE_STRING);
123 124 125 126 127 128 129 130 131

    webkit_chat_container_signals[DATA_DROPPED] = g_signal_new("data-dropped",
        G_TYPE_FROM_CLASS(klass),
        (GSignalFlags) (G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED),
        0,
        nullptr,
        nullptr,
        g_cclosure_marshal_VOID__STRING,
        G_TYPE_NONE, 1, G_TYPE_STRING);
aviau's avatar
aviau committed
132 133 134
}

static gboolean
135
webview_chat_context_menu(G_GNUC_UNUSED WebKitChatContainer *self,
136
                          WebKitContextMenu   *menu,
137 138 139
                          G_GNUC_UNUSED GdkEvent            *event,
                          G_GNUC_UNUSED WebKitHitTestResult *hit_test_result,
                          G_GNUC_UNUSED gpointer             user_data)
aviau's avatar
aviau committed
140
{
141 142 143 144 145 146 147 148 149 150 151 152 153 154
    GList *items, *nextList;
    for (items = webkit_context_menu_get_items(menu) ; items ; items = nextList) {
        WebKitContextMenuAction action;
        nextList = items->next;
        auto item = (WebKitContextMenuItem*)items->data;
        action = webkit_context_menu_item_get_stock_action(item);

        if (action == WEBKIT_CONTEXT_MENU_ACTION_RELOAD ||
        action == WEBKIT_CONTEXT_MENU_ACTION_GO_FORWARD ||
        action == WEBKIT_CONTEXT_MENU_ACTION_GO_BACK ||
        action == WEBKIT_CONTEXT_MENU_ACTION_STOP) {
            webkit_context_menu_remove(menu, item);
        }
    }
155

156 157
    // FALSE = custom menu, TRUE would mean no menu
    return FALSE;
aviau's avatar
aviau committed
158 159
}

160
static void
161
webkit_chat_container_execute_js(WebKitChatContainer *view, const gchar* function_call)
162 163 164 165 166 167 168 169 170 171 172
{
    WebKitChatContainerPrivate *priv = WEBKIT_CHAT_CONTAINER_GET_PRIVATE(view);
    webkit_web_view_run_javascript(
        WEBKIT_WEB_VIEW(priv->webview_chat),
        function_call,
        NULL,
        NULL,
        NULL
    );
}

173
QJsonObject
174 175 176
build_interaction_json(lrc::api::ConversationModel& conversation_model,
                       const uint64_t msgId,
                       const lrc::api::interaction::Info& interaction)
aviau's avatar
aviau committed
177
{
178
    auto sender = QString(interaction.authorUri.c_str());
179 180 181
    if (sender == "") {
        sender = QString(conversation_model.owner.profileInfo.uri.c_str());
    }
182 183 184 185 186 187 188 189 190 191
    auto timestamp = QString::number(interaction.timestamp);
    auto direction = lrc::api::interaction::isOutgoing(interaction) ? QString("out") : QString("in");

    QJsonObject interaction_object = QJsonObject();
    interaction_object.insert("text", QJsonValue(QString(interaction.body.c_str())));
    interaction_object.insert("id", QJsonValue(QString::number(msgId)));
    interaction_object.insert("sender", QJsonValue(sender));
    interaction_object.insert("sender_contact_method", QJsonValue(sender));
    interaction_object.insert("timestamp", QJsonValue(timestamp));
    interaction_object.insert("direction", QJsonValue(direction));
192

193
    switch (interaction.type)
194
    {
195 196 197 198 199 200 201 202 203
    case lrc::api::interaction::Type::TEXT:
        interaction_object.insert("type", QJsonValue("text"));
        break;
    case lrc::api::interaction::Type::CALL:
        interaction_object.insert("type", QJsonValue("call"));
        break;
    case lrc::api::interaction::Type::CONTACT:
        interaction_object.insert("type", QJsonValue("contact"));
        break;
204
    case lrc::api::interaction::Type::DATA_TRANSFER: {
205 206 207 208 209 210 211 212 213
        interaction_object.insert("type", QJsonValue("data_transfer"));
        lrc::api::datatransfer::Info info = {};
        conversation_model.getTransferInfo(msgId, info);
        if (info.status != lrc::api::datatransfer::Status::INVALID) {
            interaction_object.insert("totalSize", QJsonValue(qint64(info.totalSize)));
            interaction_object.insert("progress", QJsonValue(qint64(info.progress)));
        }
        break;
    }
214 215 216 217
    case lrc::api::interaction::Type::INVALID:
    default:
        interaction_object.insert("type", QJsonValue(""));
        break;
218
    }
219

220 221 222 223
    if (interaction.isRead) {
        interaction_object.insert("delivery_status", QJsonValue("read"));
    }

224
    switch (interaction.status)
225
    {
226
    case lrc::api::interaction::Status::SUCCESS:
227 228
        interaction_object.insert("delivery_status", QJsonValue("sent"));
        break;
229
    case lrc::api::interaction::Status::FAILURE:
230
    case lrc::api::interaction::Status::TRANSFER_ERROR:
231 232
        interaction_object.insert("delivery_status", QJsonValue("failure"));
        break;
233 234 235
    case lrc::api::interaction::Status::TRANSFER_UNJOINABLE_PEER:
        interaction_object.insert("delivery_status", QJsonValue("unjoinable peer"));
        break;
236 237 238
    case lrc::api::interaction::Status::SENDING:
        interaction_object.insert("delivery_status", QJsonValue("sending"));
        break;
239 240 241 242 243 244 245 246 247 248 249 250
    case lrc::api::interaction::Status::TRANSFER_CREATED:
        interaction_object.insert("delivery_status", QJsonValue("connecting"));
        break;
    case lrc::api::interaction::Status::TRANSFER_ACCEPTED:
        interaction_object.insert("delivery_status", QJsonValue("accepted"));
        break;
    case lrc::api::interaction::Status::TRANSFER_CANCELED:
        interaction_object.insert("delivery_status", QJsonValue("canceled"));
        break;
    case lrc::api::interaction::Status::TRANSFER_ONGOING:
        interaction_object.insert("delivery_status", QJsonValue("ongoing"));
        break;
251 252 253 254 255
    case lrc::api::interaction::Status::TRANSFER_AWAITING_PEER:
        interaction_object.insert("delivery_status", QJsonValue("awaiting peer"));
        break;
    case lrc::api::interaction::Status::TRANSFER_AWAITING_HOST:
        interaction_object.insert("delivery_status", QJsonValue("awaiting host"));
256
        break;
257 258 259
    case lrc::api::interaction::Status::TRANSFER_TIMEOUT_EXPIRED:
        interaction_object.insert("delivery_status", QJsonValue("awaiting peer timeout"));
        break;
260 261 262
    case lrc::api::interaction::Status::TRANSFER_FINISHED:
        interaction_object.insert("delivery_status", QJsonValue("finished"));
        break;
263 264 265 266 267
    case lrc::api::interaction::Status::INVALID:
    case lrc::api::interaction::Status::UNKNOWN:
    default:
        interaction_object.insert("delivery_status", QJsonValue("unknown"));
        break;
268
    }
269 270
    return interaction_object;
}
271

272
QString
273 274 275
interaction_to_json_interaction_object(lrc::api::ConversationModel& conversation_model,
                                       const uint64_t msgId,
                                       const lrc::api::interaction::Info& interaction)
276
{
277
    auto interaction_object = build_interaction_json(conversation_model, msgId, interaction);
278
    return QString(QJsonDocument(interaction_object).toJson(QJsonDocument::Compact));
aviau's avatar
aviau committed
279 280
}

281
QString
282 283
interactions_to_json_array_object(lrc::api::ConversationModel& conversation_model,
                                  const std::map<uint64_t, lrc::api::interaction::Info> interactions) {
284 285
    QJsonArray array;
    for (const auto& interaction: interactions)
286
        array.append(build_interaction_json(conversation_model, interaction.first, interaction.second));
287 288 289
    return QString(QJsonDocument(array).toJson(QJsonDocument::Compact));
}

290
#if WEBKIT_CHECK_VERSION(2, 6, 0)
aviau's avatar
aviau committed
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
static gboolean
webview_chat_decide_policy (G_GNUC_UNUSED WebKitWebView *web_view,
                            WebKitPolicyDecision *decision,
                            WebKitPolicyDecisionType type)
{
    switch (type)
    {
        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);
            WebKitNavigationType navigation_type = webkit_navigation_action_get_navigation_type(navigation_action);

            switch (navigation_type)
            {
                case WEBKIT_NAVIGATION_TYPE_FORM_SUBMITTED:
                case WEBKIT_NAVIGATION_TYPE_BACK_FORWARD:
                case WEBKIT_NAVIGATION_TYPE_RELOAD:
                case WEBKIT_NAVIGATION_TYPE_FORM_RESUBMITTED:
                case WEBKIT_NAVIGATION_TYPE_OTHER:
                {
                    /* make no decision */
                    return FALSE;

                }
                case WEBKIT_NAVIGATION_TYPE_LINK_CLICKED:
                {
                    webkit_policy_decision_ignore(decision);

                    WebKitURIRequest* uri_request = webkit_navigation_action_get_request(navigation_action);
                    const gchar* uri = webkit_uri_request_get_uri(uri_request);

                    gtk_show_uri(NULL, uri, GDK_CURRENT_TIME, NULL);
                }
            }

            webkit_policy_decision_ignore(decision);
            break;
        }
        case WEBKIT_POLICY_DECISION_TYPE_RESPONSE:
        {
            return FALSE;
        }
        default:
        {
            /* Making no decision results in webkit_policy_decision_use(). */
            return FALSE;
        }
    }
    return TRUE;
}
#endif

345
static gboolean
346 347 348
webview_script_dialog(WebKitWebView      *self,
                      WebKitScriptDialog *dialog,
                      G_GNUC_UNUSED gpointer user_data)
349
{
350 351
    auto interaction = webkit_script_dialog_get_message(dialog);
    g_signal_emit(G_OBJECT(self), webkit_chat_container_signals[SCRIPT_DIALOG], 0, interaction);
352 353 354
    return true;
}

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 380 381 382 383 384 385 386 387 388 389 390
static void
init_js_i18n(WebKitChatContainer *view)
{
    auto locales = g_get_language_names();
    gchar *function_call;
    GBytes *locale_data;

    int i = 0;
    while (locales[i] != NULL) {
        auto res = g_strdup_printf("/net/jami/JamiGnome/i18n/%s.json", locales[i]);
        locale_data = g_resources_lookup_data(res, G_RESOURCE_LOOKUP_FLAGS_NONE, NULL);

        if (locale_data)
            break;
        i++;
    }

    if (!locale_data) {
        /* no translation available for current locale, use default */
        function_call = g_strdup("init_i18n()");
    } else {
        gsize size;
        auto data = g_bytes_unref_to_data(locale_data, &size);
        auto nul_terminated = g_strndup((char*) data, size);

        function_call = g_strdup_printf("init_i18n(%s)", nul_terminated);

        g_free(nul_terminated);
        g_free(data);
    }

    webkit_chat_container_execute_js(view, function_call);

    g_free(function_call);
}

aviau's avatar
aviau committed
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
static void
javascript_library_loaded(WebKitWebView *webview_chat,
                          GAsyncResult *result,
                          WebKitChatContainer* self)
{
    g_return_if_fail(IS_WEBKIT_CHAT_CONTAINER(self));
    WebKitChatContainerPrivate *priv = WEBKIT_CHAT_CONTAINER_GET_PRIVATE(self);

    auto loaded_library = g_list_first(priv->js_libs_to_load);

    GError *error = NULL;
    WebKitJavascriptResult* js_result = webkit_web_view_run_javascript_from_gresource_finish(webview_chat, result, &error);
    if (!js_result) {
        g_warning("Error loading %s: %s", (const gchar*) loaded_library->data, error->message);
        g_error_free(error);
        g_object_unref(self);
        /* Stop loading view, most likely resulting in a blank page */
        return;
    }
    webkit_javascript_result_unref(js_result);

    priv->js_libs_to_load = g_list_remove(priv->js_libs_to_load, loaded_library->data);

    if(g_list_length(priv->js_libs_to_load) > 0)
    {
        /* keep loading... */
        webkit_web_view_run_javascript_from_gresource(
            webview_chat,
            (const gchar*) g_list_first(priv->js_libs_to_load)->data,
            NULL,
            (GAsyncReadyCallback) javascript_library_loaded,
            self
        );
    }
    else
    {
427 428 429
         /* load translations before anything else */
         init_js_i18n(self);

aviau's avatar
aviau committed
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
         priv->js_libs_loaded = TRUE;
         g_signal_emit(G_OBJECT(self), webkit_chat_container_signals[READY], 0);

         /* The view could now be deleted without causing a crash */
         g_object_unref(self);
    }
}

static void
load_javascript_libs(WebKitWebView *webview_chat,
                     WebKitChatContainer* self)
{
    WebKitChatContainerPrivate *priv = WEBKIT_CHAT_CONTAINER_GET_PRIVATE(self);

    /* Create the list of libraries to load */
445
    priv->js_libs_to_load = g_list_append(priv->js_libs_to_load, (gchar*) "/net/jami/JamiGnome/jed.js");
446
    priv->js_libs_to_load = g_list_append(priv->js_libs_to_load, (gchar*) "/net/jami/JamiGnome/linkify.js");
447
    priv->js_libs_to_load = g_list_append(priv->js_libs_to_load, (gchar*) "/net/jami/JamiGnome/chatview.js");
448 449
    priv->js_libs_to_load = g_list_append(priv->js_libs_to_load, (gchar*) "/net/jami/JamiGnome/linkify-string.js");
    priv->js_libs_to_load = g_list_append(priv->js_libs_to_load, (gchar*) "/net/jami/JamiGnome/linkify-html.js");
aviau's avatar
aviau committed
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489

    /* ref the chat view so that its not destroyed while we load
     * we will unref in javascript_library_loaded
     */
    g_object_ref(self);

   /* start loading */
    webkit_web_view_run_javascript_from_gresource(
        WEBKIT_WEB_VIEW(webview_chat),
        (const gchar*) g_list_first(priv->js_libs_to_load)->data,
        NULL,
        (GAsyncReadyCallback) javascript_library_loaded,
        self
    );
}

static void
webview_chat_load_changed(WebKitWebView  *webview_chat,
                          WebKitLoadEvent load_event,
                          WebKitChatContainer* self)
{
    switch (load_event) {
        case WEBKIT_LOAD_REDIRECTED:
        {
            g_warning("webview_chat load is being redirected, this should not happen");
        }
        case WEBKIT_LOAD_STARTED:
        case WEBKIT_LOAD_COMMITTED:
        {
            break;
        }
        case WEBKIT_LOAD_FINISHED:
        {
            load_javascript_libs(webview_chat, self);
            //TODO: disconnect? It shouldn't happen more than once
            break;
        }
    }
}

490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
static void
webview_chat_on_drag_data_received(GtkWidget*,
                                   GdkDragContext*,
                                   gint,
                                   gint,
                                   GtkSelectionData *data,
                                   guint,
                                   guint32,
                                   WebKitChatContainer* self)
{
    g_return_if_fail(IS_WEBKIT_CHAT_CONTAINER(self));
    WebKitChatContainerPrivate *priv = WEBKIT_CHAT_CONTAINER_GET_PRIVATE(self);
    auto* filename = (gchar*)(gtk_selection_data_get_data(data));
    if (filename) {
        priv->data_received = g_strdup_printf("%s", filename);
    }
}


static gboolean
webview_chat_on_drag_data(GtkWidget*,
                          GdkDragContext*,
                          gint,
                          gint,
                          guint,
                          WebKitChatContainer* self)
{
    g_return_val_if_fail(IS_WEBKIT_CHAT_CONTAINER(self), true);
    WebKitChatContainerPrivate *priv = WEBKIT_CHAT_CONTAINER_GET_PRIVATE(self);
    g_signal_emit(G_OBJECT(self), webkit_chat_container_signals[DATA_DROPPED], 0, priv->data_received);
    return true;
}

aviau's avatar
aviau committed
523 524 525 526 527 528 529
static void
build_view(WebKitChatContainer *view)
{
    g_return_if_fail(IS_WEBKIT_CHAT_CONTAINER(view));
    WebKitChatContainerPrivate *priv = WEBKIT_CHAT_CONTAINER_GET_PRIVATE(view);

    priv->chatview_debug = FALSE;
530 531
    auto chatview_debug = g_getenv("CHATVIEW_DEBUG");
    if (chatview_debug || g_strcmp0(chatview_debug, "true") == 0)
aviau's avatar
aviau committed
532 533 534 535
    {
        priv->chatview_debug = TRUE;
    }

536 537 538 539 540 541
    /* Prepare WebKitUserContentManager */
    WebKitUserContentManager* webkit_content_manager = webkit_user_content_manager_new();

    WebKitUserStyleSheet* chatview_style_sheet = webkit_user_style_sheet_new(
        (gchar*) g_bytes_get_data(
            g_resources_lookup_data(
542
                "/net/jami/JamiGnome/chatview.css",
543
                G_RESOURCE_LOOKUP_FLAGS_NONE,
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
                NULL
            ),
            NULL
        ),
        WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
        WEBKIT_USER_STYLE_LEVEL_USER,
        NULL,
        NULL
    );
    webkit_user_content_manager_add_style_sheet(webkit_content_manager, chatview_style_sheet);

    chatview_style_sheet = webkit_user_style_sheet_new(
        (gchar*) g_bytes_get_data(
            g_resources_lookup_data(
                "/net/jami/JamiGnome/chatview-gnome.css",
                G_RESOURCE_LOOKUP_FLAGS_NONE,
560 561 562 563 564 565 566 567 568 569 570 571
                NULL
            ),
            NULL
        ),
        WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES,
        WEBKIT_USER_STYLE_LEVEL_USER,
        NULL,
        NULL
    );
    webkit_user_content_manager_add_style_sheet(webkit_content_manager, chatview_style_sheet);

    /* Prepare WebKitSettings */
aviau's avatar
aviau committed
572 573 574 575 576 577 578 579 580
    WebKitSettings* webkit_settings = webkit_settings_new_with_settings(
        "enable-javascript", TRUE,
        "enable-developer-extras", priv->chatview_debug,
        "enable-java", FALSE,
        "enable-plugins", FALSE,
        "enable-site-specific-quirks", FALSE,
        "enable-smooth-scrolling", TRUE,
        NULL
    );
581 582 583 584 585 586 587 588 589 590 591 592 593 594

    /* Create the WebKitWebView */
    priv->webview_chat = GTK_WIDGET(
        webkit_web_view_new_with_user_content_manager(
            webkit_content_manager
        )
    );

    gtk_container_add(GTK_CONTAINER(priv->box_webview_chat), priv->webview_chat);
    gtk_widget_show(priv->webview_chat);
    gtk_widget_set_vexpand(GTK_WIDGET(priv->webview_chat), TRUE);
    gtk_widget_set_hexpand(GTK_WIDGET(priv->webview_chat), TRUE);

    /* Set the WebKitSettings */
aviau's avatar
aviau committed
595 596
    webkit_web_view_set_settings(WEBKIT_WEB_VIEW(priv->webview_chat), webkit_settings);

597 598
    g_signal_connect(priv->webview_chat, "drag-data-received", G_CALLBACK(webview_chat_on_drag_data_received), view);
    g_signal_connect(priv->webview_chat, "drag-drop", G_CALLBACK(webview_chat_on_drag_data), view);
aviau's avatar
aviau committed
599 600
    g_signal_connect(priv->webview_chat, "load-changed", G_CALLBACK(webview_chat_load_changed), view);
    g_signal_connect_swapped(priv->webview_chat, "context-menu", G_CALLBACK(webview_chat_context_menu), view);
601
    g_signal_connect_swapped(priv->webview_chat, "script-dialog", G_CALLBACK(webview_script_dialog), view);
602
#if WEBKIT_CHECK_VERSION(2, 6, 0)
aviau's avatar
aviau committed
603 604 605 606
    g_signal_connect(priv->webview_chat, "decide-policy", G_CALLBACK(webview_chat_decide_policy), view);
#endif

    GBytes* chatview_bytes = g_resources_lookup_data(
607
        "/net/jami/JamiGnome/chatview.html",
aviau's avatar
aviau committed
608 609 610 611
        G_RESOURCE_LOOKUP_FLAGS_NONE,
        NULL
    );

612
    // file:// allow the webview to load local files
aviau's avatar
aviau committed
613 614 615
    webkit_web_view_load_html(
        WEBKIT_WEB_VIEW(priv->webview_chat),
        (gchar*) g_bytes_get_data(chatview_bytes, NULL),
616
        "file://"
aviau's avatar
aviau committed
617 618 619 620
    );

    /* Now we wait for the load-changed event, before we
     * start loading javascript libraries */
621 622 623 624 625 626 627 628

    /* handle web view crash */
    g_signal_connect_swapped(priv->webview_chat, "web-process-crashed", G_CALLBACK(webview_crashed), view);
}

static gboolean
webview_crashed(WebKitChatContainer *self)
{
Philippe Gorley's avatar
Philippe Gorley committed
629
    g_warning("Gtk Web Process crashed! Recreating web view");
630 631 632 633 634 635 636 637 638 639 640 641

    auto priv = WEBKIT_CHAT_CONTAINER_GET_PRIVATE(self);

    /* make sure we destroy previous WebView */
    if (priv->webview_chat) {
        gtk_widget_destroy(priv->webview_chat);
        priv->webview_chat = nullptr;
    }

    build_view(self);

    return G_SOURCE_CONTINUE;
aviau's avatar
aviau committed
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
}

GtkWidget *
webkit_chat_container_new()
{
    gpointer view = g_object_new(WEBKIT_CHAT_CONTAINER_TYPE, NULL);

    WebKitChatContainerPrivate *priv = WEBKIT_CHAT_CONTAINER_GET_PRIVATE(view);
    priv->js_libs_loaded = FALSE;

    build_view(WEBKIT_CHAT_CONTAINER(view));

    return (GtkWidget *)view;
}

657 658 659
void
webkit_chat_container_set_display_links(WebKitChatContainer *view, bool display)
{
660
    gchar* function_call = g_strdup_printf("setDisplayLinks(%s);",
661
      display ? "true" : "false");
662 663
    webkit_chat_container_execute_js(view, function_call);
    g_free(function_call);
664 665
}

aviau's avatar
aviau committed
666
void
667
webkit_chat_container_clear_sender_images(WebKitChatContainer *view)
aviau's avatar
aviau committed
668
{
669
    webkit_chat_container_execute_js(view, "clearSenderImages();");
670 671 672 673 674
}

void
webkit_chat_container_clear(WebKitChatContainer *view)
{
675
    webkit_chat_container_execute_js(view, "clearMessages();");
676
    webkit_chat_container_clear_sender_images(view);
aviau's avatar
aviau committed
677 678 679
}

void
680
webkit_chat_container_update_interaction(WebKitChatContainer *view,
681
                                         lrc::api::ConversationModel& conversation_model,
682 683
                                         uint64_t msgId,
                                         const lrc::api::interaction::Info& interaction)
aviau's avatar
aviau committed
684
{
685
    auto interaction_object = interaction_to_json_interaction_object(conversation_model, msgId, interaction).toUtf8();
686
    gchar* function_call = g_strdup_printf("updateMessage(%s);", interaction_object.constData());
687
    webkit_chat_container_execute_js(view, function_call);
aviau's avatar
aviau committed
688 689 690
    g_free(function_call);
}

691 692 693
void
webkit_chat_container_remove_interaction(WebKitChatContainer *view, uint64_t interactionId)
{
694
    gchar* function_call = g_strdup_printf("removeInteraction(%lu);", interactionId);
695
    webkit_chat_container_execute_js(view, function_call);
696 697 698 699
    g_free(function_call);
}


aviau's avatar
aviau committed
700
void
701
webkit_chat_container_print_new_interaction(WebKitChatContainer *view,
702
                                            lrc::api::ConversationModel& conversation_model,
703 704
                                            uint64_t msgId,
                                            const lrc::api::interaction::Info& interaction)
aviau's avatar
aviau committed
705
{
706
    auto interaction_object = interaction_to_json_interaction_object(conversation_model, msgId, interaction).toUtf8();
707
    gchar* function_call = g_strdup_printf("addMessage(%s);", interaction_object.constData());
708
    webkit_chat_container_execute_js(view, function_call);
aviau's avatar
aviau committed
709 710 711
    g_free(function_call);
}

712
void
713 714 715
webkit_chat_container_print_history(WebKitChatContainer *view,
                                    lrc::api::ConversationModel& conversation_model,
                                    const std::map<uint64_t, lrc::api::interaction::Info> interactions)
716
{
717
    auto interactions_str = interactions_to_json_array_object(conversation_model, interactions).toUtf8();
718
    gchar* function_call = g_strdup_printf("printHistory(%s)", interactions_str.constData());
719
    webkit_chat_container_execute_js(view, function_call);
720 721 722
    g_free(function_call);
}

723 724
void
webkit_chat_container_set_invitation(WebKitChatContainer *view, bool show,
725
                                     const std::string& contactUri, const std::string& contactId)
726
{
727
    // TODO better escape names
728
    gchar* function_call = g_strdup_printf(show ? "showInvitation(\"%s\", \"%s\")" : "showInvitation()", contactUri.c_str(), contactId.c_str());
729
    webkit_chat_container_execute_js(view, function_call);
730 731 732 733 734 735 736
    g_free(function_call);
}

void
webkit_chat_container_set_sender_image(WebKitChatContainer *view, const std::string& sender, const std::string& senderImage)
{
    WebKitChatContainerPrivate *priv = WEBKIT_CHAT_CONTAINER_GET_PRIVATE(view);
aviau's avatar
aviau committed
737 738

    QJsonObject set_sender_image_object = QJsonObject();
739 740
    set_sender_image_object.insert("sender_contact_method", QJsonValue(QString(sender.c_str())));
    set_sender_image_object.insert("sender_image", QJsonValue(QString(senderImage.c_str())));
aviau's avatar
aviau committed
741

742
    auto set_sender_image_object_string = QString(QJsonDocument(set_sender_image_object).toJson(QJsonDocument::Compact));
aviau's avatar
aviau committed
743

744
    gchar* function_call = g_strdup_printf("setSenderImage(%s);", set_sender_image_object_string.toUtf8().constData());
aviau's avatar
aviau committed
745 746 747 748 749 750 751 752 753 754
    webkit_web_view_run_javascript(WEBKIT_WEB_VIEW(priv->webview_chat), function_call, NULL, NULL, NULL);
    g_free(function_call);
}

gboolean
webkit_chat_container_is_ready(WebKitChatContainer *view)
{
    WebKitChatContainerPrivate *priv = WEBKIT_CHAT_CONTAINER_GET_PRIVATE(view);
    return priv->js_libs_loaded;
}
755 756 757 758 759

void
webkit_chat_set_header_visible(WebKitChatContainer *view, bool isVisible)
{
    gchar* function_call = g_strdup_printf("displayNavbar(%s)", isVisible ? "true" : "false");
760
    webkit_chat_container_execute_js(view, function_call);
761 762 763
    g_free(function_call);
}

764 765 766 767 768 769 770 771
void
webkit_chat_set_record_visible(WebKitChatContainer *view, bool isVisible)
{
    gchar* function_call = g_strdup_printf("displayRecordControls(%s)", isVisible ? "true" : "false");
    webkit_chat_container_execute_js(view, function_call);
    g_free(function_call);
}

772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
void
webkit_chat_set_dark_mode(WebKitChatContainer *view, bool darkMode, const std::string& background)
{
    std::string theme = "";
    if (darkMode) {
        theme = "\
            --jami-light-blue: #003b4e;\
            --jami-dark-blue: #28b1ed;\
            --text-color: white;\
            --timestamp-color: #bbb;\
            --message-out-bg: #28b1ed;\
            --message-out-txt: white;\
            --message-in-bg: #616161;\
            --message-in-txt: white;\
            --file-in-timestamp-color: #999;\
            --file-out-timestamp-color: #eee;\
            --bg-color: " + background + ";\
            --non-action-icon-color: white;\
            --placeholder-text-color: #2b2b2b;\
            --invite-hover-color: black;\
            --hairline-color: #262626;\
        ";
    }
    gchar* function_call = g_strdup_printf("setTheme(\"%s\")", theme.c_str());
    webkit_chat_container_execute_js(view, function_call);
    g_free(function_call);
}

800
void
801
webkit_chat_update_chatview_frame(WebKitChatContainer *view, bool accountEnabled, bool isBanned, bool isTemporary, const gchar* alias, const gchar* bestId)
802
{
803 804
    gchar* function_call = g_strdup_printf("update_chatview_frame(%s, %s, %s, \"%s\", \"%s\")",
                                           accountEnabled ? "true" : "false",
805
                                           isBanned ? "true" : "false", isTemporary ? "true" : "false", alias, bestId);
806
    webkit_chat_container_execute_js(view, function_call);
807 808
    g_free(function_call);
}