summaryrefslogtreecommitdiffstats
path: root/src/eventqueue.cpp
blob: 6f010b735bb401027c2ceda015bad62567106025 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
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
345
346
347
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
#include "eventqueue.h"
#include "webclient.h"
#include <QImage>

void encodeText(QString &text)
{
    // encode "breakout" characters
    text.replace("&", "&amp;");
    text.replace("<", "&lt;");
    text.replace(">", "&gt;");
    text.replace("'", "&apos;");
    text.replace('"', "&quot;");
    text.replace("/", "&#47");

    // white-list for safe tags
    text.replace("&lt;b&gt;", "<b>");
    text.replace("&lt;&#47b&gt;", "</b>");
}

QString widgetGetText(QWidget *widget)
{
    QString text;

    if (QLineEdit *lineEdit = qobject_cast<QLineEdit *>(widget)) {
        text = lineEdit->text();
    } else if (QTextEdit *textEdit = qobject_cast<QTextEdit *>(widget)) {
        text = textEdit->toPlainText();
    } else if (QPushButton *pushButton = qobject_cast<QPushButton*>(widget)) {
        text = pushButton->text();
    } else if (QLabel *label = qobject_cast<QLabel*>(widget)) {
        text = label->text();
    } else {
        text = "unsupported text widget";;
    }

    encodeText(text);

    return text;
}

EventQueue::EventQueue(Session *session)
:m_session(session)
{
    reset();
}

void EventQueue::setSession(Session *session)
{
    m_session = session;
    reset();
}

void EventQueue::reset()
{
    DEBUG << "reset";
    images.clear();
    geometries.clear();
}

void EventQueue::handleRequest(HttpRequest *request, HttpResponse *response)
{
//    DEBUG << "handle request" << request->path();
    const QByteArray path = request->path();

    if (path == "/content") {
        DEBUG << "content";
        response->setBody(queueToByteArray());
    } else if (path == "/idle") {
        DEBUG << "idle";
        response->setBody(queueToByteArray());

    // If the part starts with "/json" then the rest of the string is an json-encoded
    // string object.
    } else if (path.startsWith("/json")) {
        QByteArray jsonText = path.mid(5); // remove "/json"
        handleJsonRequest(jsonText, response);
    }
}

void EventQueue::handleJsonRequest(QByteArray jsonText, HttpResponse *response)
{
    // replace symbols that can't be a part of the url text.
    jsonText.replace("%7B", "{");
    jsonText.replace("%7D", "}");
    jsonText.replace("%22", "\"");

    DEBUG << "json request" << jsonText;
    json_object* jsonRequest = json_tokener_parse(jsonText.data());
    if (!jsonRequest)
        return;
    json_object* type = json_object_object_get(jsonRequest, "type");

    QByteArray typeText = json_object_get_string(type);

    if (typeText == "img") {
        handleImageRequest(jsonRequest, response);
    } else if (typeText == "img-static") {
        handleStaticImageRequest(jsonRequest, response);
    }
    json_object_put(jsonRequest); //free
}

void EventQueue::handleImageRequest(json_object* jsonRequest, HttpResponse *response)
{
    json_object* idObject = json_object_object_get(jsonRequest, "id");
    if (!idObject)
        return;

    const quintptr id = json_object_get_int(idObject);
    DEBUG << "id" << this << id << images.value(id).size();
 //   if (staticCompressedImages.contains(id))
 //       qFatal("serving dynamic image for static widdget");

    // Save server memory and CPU time by storing images in the png
    // format after the first serve. The browser could request
    // the image again, for example if the user hits refresh.
    QByteArray pngImage;
    QImage uncompressedImage = images.value(id);
    if (uncompressedImage.isNull()== false) {
        images.remove(id);

        QBuffer buffer(&pngImage);
        buffer.open(QIODevice::WriteOnly);
        QImageWriter writer(&buffer, "png");
        writer.write(uncompressedImage);

        compressedImages.insert(id, pngImage);
    }

    if (pngImage.isEmpty()) {
        pngImage = compressedImages.value(id);
    }

    response->setBody(pngImage);
    response->setContentType("image/png");
}

void EventQueue::handleStaticImageRequest(json_object* jsonRequest, HttpResponse *response)
{
    json_object* imageHashObject = json_object_object_get(jsonRequest, "imagehash");
    DEBUG << "handleStaticImageRequest" << imageHashObject;
    if (!imageHashObject)
        return;

    const quintptr imageHash = json_object_get_int(imageHashObject);
    DEBUG << "imagehash" << this << imageHash;

    quintptr imageid = staticImageHashToWidgetId.value(imageHash);
    QByteArray pngImage = staticCompressedImages.value(imageid);
    DEBUG << imageid << pngImage.count();
    response->setBody(pngImage);
    response->setContentType("image/png");
}

void EventQueue::addUpdateEvent(quintptr id, const QImage &image, QRect updateRect)
{
    DEBUG << "addUpdateEvent" << this << id << image.size();
    images.insert(id, image);
    addEvent(id, EventEntry::Update);
}
void EventQueue::addStaticUpdateEvent(quintptr id, uint hash, const QByteArray &pngImage)
{
    DEBUG << "addStaticUpdateEvent" << this << hash << pngImage.size();
    staticCompressedImages.insert(id, pngImage);
    staticImageHashToWidgetId.insert(hash, id);
    staticWidgetIdToImageHash.insert(id, hash);
    addEvent(id, EventEntry::StaticUpdate);
}

void EventQueue::addStaticUpdateEvent(quintptr id)
{
    DEBUG << "addStaticUpdateEvent" << this << id;
    // assert staticCompressedImages.conrains(id);
    addEvent(id, EventEntry::StaticUpdate);
}

void EventQueue::addGeometryEvent(quintptr id, QRect globalGeometry)
{
    if (geometries[id] == globalGeometry) {
        return;
    }
    geometries[id] = globalGeometry;
    addEvent(id, EventEntry::Geometry);
}

void EventQueue::addParentChangeEvent(quintptr id)
{
//    DEBUG << "parentchanged";
    addEvent(id, EventEntry::ParentChange);
}

void EventQueue::addEvent(quintptr id, EventEntry::Type type)
{
    EventEntry entry(id, type);

    if (events.contains(entry)) {
//        DEBUG << "event already in queue";
        return;
    }

    events.enqueue(entry);
//    DEBUG << json_object_to_json_string(toJson(entry));

    if (m_session)
        m_session->contentAvailable();
}

QByteArray EventQueue::queueToByteArray()
{
    if (events.isEmpty())
        return QByteArray();

    json_object *array = json_object_new_array();
    while (events.isEmpty() == false) {
        json_object_array_add(array, toJson(events.dequeue()));
    }

    QByteArray text(json_object_to_json_string(array));

    DEBUG << "sending event text" << text;
    // json_free(array);

   return text;

}

json_object *EventQueue::toJson(const EventEntry &event) const
{
    switch(event.type)
    {
    case EventEntry::Update:
        return jsonUpdateEvent(event);
    case EventEntry::StaticUpdate:
        return jsonStaticUpdateEvent(event);
    case EventEntry::Show:
        return jsonShowEvent(event);
    case EventEntry::ShowLineEdit:
        return jsonShowLineEditEvent(event);
    case EventEntry::Hide:
        return jsonHideEvent(event);
    case EventEntry::Geometry:
        return jsonGeometryEvent(event);
    case EventEntry::ParentChange:
        return jsonParentChangeEvent(event);
    case EventEntry::TextUpdate:
        return jsonTextUpdateEvent(event);
    default:
        return json_object_new_object();
    break;
    }
}

json_object *EventQueue::jsonShowEvent(const EventEntry &event) const
{
    struct json_object *obj = json_object_new_object();
    QWidget *widget = (QWidget *)event.id;
    json_object_object_add(obj, "type", json_object_new_string("show"));
    json_object_object_add(obj, "id", json_object_new_int(event.id));
    json_object_object_add(obj, "widgetType", toJsonWidgetType(widget));
    json_object_object_add(obj, "className",
        json_object_new_string(const_cast<char *>(widget->metaObject()->className())));
    json_object_object_add(obj, "objectName",
        json_object_new_string(widget->objectName().toAscii().data()));
    return obj;
}

json_object *EventQueue::jsonShowLineEditEvent(const EventEntry &event) const
{
    DEBUG << "### Show line edit";
    struct json_object *obj = json_object_new_object();
    json_object_object_add(obj, "type", json_object_new_string("showLineEdit"));
    json_object_object_add(obj, "id", json_object_new_int(event.id));
    return obj;
}


json_object *EventQueue::jsonHideEvent(const EventEntry &event) const
{
    struct json_object *obj = json_object_new_object();
    json_object_object_add(obj, "type", json_object_new_string("hide"));
    json_object_object_add(obj, "id", json_object_new_int(event.id));
    json_object_object_add(obj, "widgetType", toJsonWidgetType((QWidget *)event.id));
    return obj;
}

json_object *EventQueue::jsonUpdateEvent(const EventEntry &event) const
{
    struct json_object *obj = json_object_new_object();
    json_object_object_add(obj, "type", json_object_new_string("update"));
    json_object_object_add(obj, "id", json_object_new_int(event.id));
    json_object_object_add(obj, "widgetType", toJsonWidgetType((QWidget *)event.id));
    return obj;
}

json_object *EventQueue::jsonStaticUpdateEvent(const EventEntry &event) const
{
    struct json_object *obj = json_object_new_object();
    json_object_object_add(obj, "type", json_object_new_string("update"));
    json_object_object_add(obj, "id", json_object_new_int(event.id));
    json_object_object_add(obj, "imagehash",
        json_object_new_string(QByteArray::number(staticWidgetIdToImageHash.value(event.id)).data()));
    json_object_object_add(obj, "widgetType", toJsonWidgetType((QWidget *)event.id));
    return obj;
}


json_object *EventQueue::jsonGeometryEvent(const EventEntry &event) const
{
    struct json_object *obj = json_object_new_object();
    json_object_object_add(obj, "type", json_object_new_string("geometry"));
    json_object_object_add(obj, "id", json_object_new_int(event.id));
    json_object_object_add(obj, "widgetType", toJsonWidgetType((QWidget *)event.id));

    QRect geometry = geometries.value(event.id);
    json_object_object_add(obj, "x", json_object_new_int(geometry.x()));
    json_object_object_add(obj, "y", json_object_new_int(geometry.y()));
    json_object_object_add(obj, "w", json_object_new_int(geometry.width()));
    json_object_object_add(obj, "h", json_object_new_int(geometry.height()));

    return obj;
}

json_object *EventQueue::jsonParentChangeEvent(const EventEntry &event) const
{
//    DEBUG << "parentchanged send";
    QWidget *parent = ((QWidget *)event.id)->parentWidget();
    struct json_object *obj = json_object_new_object();
    json_object_object_add(obj, "type", json_object_new_string("parentChange"));
    json_object_object_add(obj, "id", json_object_new_int(event.id));
    json_object_object_add(obj, "widgetType", toJsonWidgetType(parent));
    json_object_object_add(obj, "parent", json_object_new_int((int)(parent)));

    return obj;
}

json_object *EventQueue::jsonTextUpdateEvent(const EventEntry &event) const
{
    struct json_object *obj = json_object_new_object();
    json_object_object_add(obj, "type", json_object_new_string("textUpdate"));
    json_object_object_add(obj, "id", json_object_new_int(event.id));
    json_object_object_add(obj, "widgetType", toJsonWidgetType((QWidget *)event.id));
    json_object_object_add(obj, "text", json_object_new_string(widgetGetText((QLineEdit *)event.id).toLocal8Bit().data()));
    return obj;
}

json_object *EventQueue::toJsonWidgetType(QWidget *widget) const
{
    if (!widget || m_session->m_server->shouldSkipUpdate(widget->metaObject()->className()))
        return json_object_new_string("skippedwidget");
    if (qobject_cast<QLineEdit *>(widget))
        return json_object_new_string("lineedit");
    if (qobject_cast<QTextEdit *>(widget))
        return json_object_new_string("textedit");
    if (qobject_cast<QLabel *>(widget))
        return json_object_new_string("label");
    if (qobject_cast<QMdiSubWindow *>(widget))
        return json_object_new_string("midisubwindow");
    if (qobject_cast<QPushButton *>(widget))
        return json_object_new_string("pusbutton");

    if (m_session->m_server->testHint(widget, WebClient::StaticWidget)) {
        return json_object_new_string("genericstatic");
    } else {
        return json_object_new_string("generic");
    }
}

QByteArray EventQueue::pngCompress(const QImage &image)
{
    QByteArray pngImage;
    QBuffer buffer(&pngImage);
    buffer.open(QIODevice::WriteOnly);
    QImageWriter writer(&buffer, "png");
    writer.write(image);
    return pngImage;
}