File: chatviewsearchcontroller.cpp

package info (click to toggle)
quassel 1:0.13.1-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 25,640 kB
  • sloc: cpp: 66,953; perl: 15,837; ansic: 4,418; sql: 1,225; sh: 328; xml: 263; python: 224; makefile: 24
file content (485 lines) | stat: -rw-r--r-- 16,320 bytes parent folder | download
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
378
379
380
381
382
383
384
385
386
387
388
389
390
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
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
/***************************************************************************
 *   Copyright (C) 2005-2019 by the Quassel Project                        *
 *   devel@quassel-irc.org                                                 *
 *                                                                         *
 *   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 2 of the License, or     *
 *   (at your option) version 3.                                           *
 *                                                                         *
 *   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 "chatviewsearchcontroller.h"

#include <QAbstractItemModel>
#include <QPainter>

#include "chatitem.h"
#include "chatline.h"
#include "chatlinemodel.h"
#include "chatscene.h"
#include "messagemodel.h"

ChatViewSearchController::ChatViewSearchController(QObject *parent)
    : QObject(parent),
    _scene(0),
    _currentHighlight(0),
    _caseSensitive(false),
    _searchSenders(false),
    _searchMsgs(true),
    _searchOnlyRegularMsgs(true)
{
}


void ChatViewSearchController::setSearchString(const QString &searchString)
{
    QString oldSearchString = _searchString;
    _searchString = searchString;
    if (_scene) {
        if (!searchString.startsWith(oldSearchString) || oldSearchString.isEmpty()) {
            // we can't reuse our all findings... cler the scene and do it all over
            updateHighlights();
        }
        else {
            // reuse all findings
            updateHighlights(true);
        }
    }
}


void ChatViewSearchController::setScene(ChatScene *scene)
{
    Q_ASSERT(scene);
    if (scene == _scene)
        return;

    if (_scene) {
        disconnect(_scene, 0, this, 0);
        disconnect(Client::messageModel(), 0, this, 0);
        qDeleteAll(_highlightItems);
        _highlightItems.clear();
    }

    _scene = scene;
    if (!scene)
        return;

    connect(_scene, SIGNAL(destroyed()), this, SLOT(sceneDestroyed()));
    connect(_scene, SIGNAL(layoutChanged()), this, SLOT(repositionHighlights()));
    connect(Client::messageModel(), SIGNAL(finishedBacklogFetch(BufferId)), this, SLOT(updateHighlights()));
    updateHighlights();
}


void ChatViewSearchController::highlightNext()
{
    if (_highlightItems.isEmpty())
        return;

    if (_currentHighlight < _highlightItems.count()) {
        _highlightItems.at(_currentHighlight)->setHighlighted(false);
    }

    _currentHighlight++;
    if (_currentHighlight >= _highlightItems.count())
        _currentHighlight = 0;
    _highlightItems.at(_currentHighlight)->setHighlighted(true);
    emit newCurrentHighlight(_highlightItems.at(_currentHighlight));
}


void ChatViewSearchController::highlightPrev()
{
    if (_highlightItems.isEmpty())
        return;

    if (_currentHighlight < _highlightItems.count()) {
        _highlightItems.at(_currentHighlight)->setHighlighted(false);
    }

    _currentHighlight--;
    if (_currentHighlight < 0)
        _currentHighlight = _highlightItems.count() - 1;
    _highlightItems.at(_currentHighlight)->setHighlighted(true);
    emit newCurrentHighlight(_highlightItems.at(_currentHighlight));
}


void ChatViewSearchController::updateHighlights(bool reuse)
{
    if (!_scene)
        return;

    if (reuse) {
        QSet<ChatLine *> chatLines;
        foreach(SearchHighlightItem *highlightItem, _highlightItems) {
            ChatLine *line = qgraphicsitem_cast<ChatLine *>(highlightItem->parentItem());
            if (line)
                chatLines << line;
        }
        foreach (ChatLine* line, chatLines) {
            updateHighlights(line);
        }
    }
    else {
        QPointF oldHighlightPos;
        if (!_highlightItems.isEmpty() && _currentHighlight < _highlightItems.count()) {
            oldHighlightPos = _highlightItems[_currentHighlight]->scenePos();
        }
        qDeleteAll(_highlightItems);
        _highlightItems.clear();
        Q_ASSERT(_highlightItems.isEmpty());

        if (searchString().isEmpty() || !(_searchSenders || _searchMsgs))
            return;

        checkMessagesForHighlight();

        if (!_highlightItems.isEmpty()) {
            if (!oldHighlightPos.isNull()) {
                int start = 0; int end = _highlightItems.count() - 1;
                QPointF startPos;
                QPointF endPos;
                while (1) {
                    startPos = _highlightItems[start]->scenePos();
                    endPos = _highlightItems[end]->scenePos();
                    if (startPos == oldHighlightPos) {
                        _currentHighlight = start;
                        break;
                    }
                    if (endPos == oldHighlightPos) {
                        _currentHighlight = end;
                        break;
                    }
                    if (end - start == 1) {
                        _currentHighlight = start;
                        break;
                    }
                    if (end == 0 && start == 0) {
                        // Sometimes we can run into an issue where the start and end are both set
                        // to zero.  Rather than endlessly spin this loop, bail out.  Search seems
                        // to work fine.
                        // [Test case]
                        // Unfortunately, this seems specific to the contents of a buffer.  First,
                        // find a buffer that you've encountered freezing, and keep track of what
                        // was loaded, where it was, and the two most recent search terms.
                        // For example...
                        // 1.  Load some backlog to a buffer
                        // 2.  Search for term with any number of matches
                        // 3.  Making sure to -type over existing words without first backspacing-,
                        //     search for another term with only one match
                        // Expected: Search results found, no freezing
                        // Actual:   Quassel hangs.  startPos and endPos = same place, start = 0,
                        //           end = 0, _currentHighlight appears to retain values from the
                        //           previous search.

                        // Reset _currentHighlight to start, otherwise it'll retain the value from
                        // previous search, resulting in an index-out-of-bounds error.
                        _currentHighlight = start;
                        // Escape from the loop!
                        break;
                    }
                    int pivot = (end + start) / 2;
                    QPointF pivotPos = _highlightItems[pivot]->scenePos();
                    if (startPos.y() == endPos.y()) {
                        if (oldHighlightPos.x() <= pivotPos.x())
                            end = pivot;
                        else
                            start = pivot;
                    }
                    else {
                        if (oldHighlightPos.y() <= pivotPos.y())
                            end = pivot;
                        else
                            start = pivot;
                    }
                }
            }
            else {
                _currentHighlight = _highlightItems.count() - 1;
            }
            _highlightItems[_currentHighlight]->setHighlighted(true);
            emit newCurrentHighlight(_highlightItems[_currentHighlight]);
        }
    }
}


void ChatViewSearchController::checkMessagesForHighlight(int start, int end)
{
    QAbstractItemModel *model = _scene->model();
    Q_ASSERT(model);

    if (end == -1) {
        end = model->rowCount() - 1;
        if (end == -1)
            return;
    }

    QModelIndex index;
    for (int row = start; row <= end; row++) {
        if (_searchOnlyRegularMsgs) {
            index = model->index(row, 0);
            if (!checkType((Message::Type)index.data(MessageModel::TypeRole).toInt()))
                continue;
        }
        highlightLine(_scene->chatLine(row));
    }
}


void ChatViewSearchController::updateHighlights(ChatLine *line)
{
    QList<ChatItem *> checkItems;
    if (_searchSenders)
        checkItems << line->item(MessageModel::SenderColumn);

    if (_searchMsgs)
        checkItems << line->item(MessageModel::ContentsColumn);

    QHash<quint64, QHash<quint64, QRectF> > wordRects;
    foreach(ChatItem *item, checkItems) {
        foreach(QRectF wordRect, item->findWords(searchString(), caseSensitive())) {
            wordRects[(quint64)(wordRect.x() + item->x())][(quint64)(wordRect.y())] = wordRect;
        }
    }

    bool deleteAll = false;
    QAbstractItemModel *model = _scene->model();
    Q_ASSERT(model);
    if (_searchOnlyRegularMsgs) {
        QModelIndex index = model->index(line->row(), 0);
        if (!checkType((Message::Type)index.data(MessageModel::TypeRole).toInt()))
            deleteAll = true;
    }

    foreach(QGraphicsItem *child, line->childItems()) {
        SearchHighlightItem *highlightItem = qgraphicsitem_cast<SearchHighlightItem *>(child);
        if (!highlightItem)
            continue;

        if (!deleteAll && wordRects.contains((quint64)(highlightItem->pos().x())) && wordRects[(quint64)(highlightItem->pos().x())].contains((quint64)(highlightItem->pos().y()))) {
            QRectF &wordRect = wordRects[(quint64)(highlightItem->pos().x())][(quint64)(highlightItem->pos().y())];
            highlightItem->updateGeometry(wordRect.width(), wordRect.height());
        }
        else {
            int pos = _highlightItems.indexOf(highlightItem);
            if (pos == _currentHighlight) {
                highlightPrev();
            }
            else if (pos < _currentHighlight) {
                _currentHighlight--;
            }

            _highlightItems.removeAt(pos);
            delete highlightItem;
        }
    }
}


void ChatViewSearchController::highlightLine(ChatLine *line)
{
    QList<ChatItem *> checkItems;
    if (_searchSenders)
        checkItems << line->item(MessageModel::SenderColumn);

    if (_searchMsgs)
        checkItems << line->item(MessageModel::ContentsColumn);

    foreach(ChatItem *item, checkItems) {
        foreach(QRectF wordRect, item->findWords(searchString(), caseSensitive())) {
            _highlightItems << new SearchHighlightItem(wordRect.adjusted(item->x(), 0, item->x(), 0), line);
        }
    }
}


void ChatViewSearchController::repositionHighlights()
{
    QSet<ChatLine *> chatLines;
    foreach(SearchHighlightItem *item, _highlightItems) {
        ChatLine *line = qgraphicsitem_cast<ChatLine *>(item->parentItem());
        if (line)
            chatLines << line;
    }
    foreach (ChatLine* line, chatLines) {
        repositionHighlights(line);
    }
}


void ChatViewSearchController::repositionHighlights(ChatLine *line)
{
    QList<SearchHighlightItem *> searchHighlights;
    foreach(QGraphicsItem *child, line->childItems()) {
        SearchHighlightItem *highlightItem = qgraphicsitem_cast<SearchHighlightItem *>(child);
        if (highlightItem)
            searchHighlights << highlightItem;
    }

    if (searchHighlights.isEmpty())
        return;

    QList<QPointF> wordPos;
    if (_searchSenders) {
        foreach(QRectF wordRect, line->senderItem()->findWords(searchString(), caseSensitive())) {
            wordPos << QPointF(wordRect.x() + line->senderItem()->x(), wordRect.y());
        }
    }
    if (_searchMsgs) {
        foreach(QRectF wordRect, line->contentsItem()->findWords(searchString(), caseSensitive())) {
            wordPos << QPointF(wordRect.x() + line->contentsItem()->x(), wordRect.y());
        }
    }

    qSort(searchHighlights.begin(), searchHighlights.end(), SearchHighlightItem::firstInLine);

    Q_ASSERT(wordPos.count() == searchHighlights.count());
    for (int i = 0; i < searchHighlights.count(); i++) {
        searchHighlights.at(i)->setPos(wordPos.at(i));
    }
}


void ChatViewSearchController::sceneDestroyed()
{
    // WARNING: don't call any methods on scene!
    _scene = 0;
    // the items will be automatically deleted when the scene is destroyed
    // so we just have to clear the list;
    _highlightItems.clear();
}


void ChatViewSearchController::setCaseSensitive(bool caseSensitive)
{
    if (_caseSensitive == caseSensitive)
        return;

    _caseSensitive = caseSensitive;

    // we can reuse the original search results if the new search
    // parameters are a restriction of the original one
    updateHighlights(caseSensitive);
}


void ChatViewSearchController::setSearchSenders(bool searchSenders)
{
    if (_searchSenders == searchSenders)
        return;

    _searchSenders = searchSenders;
    // we can reuse the original search results if the new search
    // parameters are a restriction of the original one
    updateHighlights(!searchSenders);
}


void ChatViewSearchController::setSearchMsgs(bool searchMsgs)
{
    if (_searchMsgs == searchMsgs)
        return;

    _searchMsgs = searchMsgs;

    // we can reuse the original search results if the new search
    // parameters are a restriction of the original one
    updateHighlights(!searchMsgs);
}


void ChatViewSearchController::setSearchOnlyRegularMsgs(bool searchOnlyRegularMsgs)
{
    if (_searchOnlyRegularMsgs == searchOnlyRegularMsgs)
        return;

    _searchOnlyRegularMsgs = searchOnlyRegularMsgs;

    // we can reuse the original search results if the new search
    // parameters are a restriction of the original one
    updateHighlights(searchOnlyRegularMsgs);
}


// ==================================================
//  SearchHighlightItem
// ==================================================
SearchHighlightItem::SearchHighlightItem(QRectF wordRect, QGraphicsItem *parent)
    : QObject(),
    QGraphicsItem(parent),
    _highlighted(false),
    _alpha(70),
    _timeLine(150)
{
    setPos(wordRect.x(), wordRect.y());
    updateGeometry(wordRect.width(), wordRect.height());

    connect(&_timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(updateHighlight(qreal)));
}


void SearchHighlightItem::setHighlighted(bool highlighted)
{
    _highlighted = highlighted;

    if (highlighted)
        _timeLine.setDirection(QTimeLine::Forward);
    else
        _timeLine.setDirection(QTimeLine::Backward);

    if (_timeLine.state() != QTimeLine::Running)
        _timeLine.start();

    update();
}


void SearchHighlightItem::updateHighlight(qreal value)
{
    _alpha = 70 + (int)(80 * value);
    update();
}


void SearchHighlightItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    Q_UNUSED(option);
    Q_UNUSED(widget);

    painter->setPen(QPen(QColor(0, 0, 0), 1.5));
    painter->setBrush(QColor(254, 237, 45, _alpha));
    painter->setRenderHints(QPainter::Antialiasing);
    qreal radius = boundingRect().height() * 0.30;
    painter->drawRoundedRect(boundingRect(), radius, radius);
}


void SearchHighlightItem::updateGeometry(qreal width, qreal height)
{
    prepareGeometryChange();
    qreal sizedelta = height * 0.1;
    _boundingRect = QRectF(-sizedelta, -sizedelta, width + 2 * sizedelta, height + 2 * sizedelta);
    update();
}


bool SearchHighlightItem::firstInLine(QGraphicsItem *item1, QGraphicsItem *item2)
{
    if (item1->pos().y() != item2->pos().y())
        return item1->pos().y() < item2->pos().y();
    else
        return item1->pos().x() < item2->pos().x();
}