File: networkmodel.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 (1799 lines) | stat: -rw-r--r-- 56,945 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
486
487
488
489
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
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
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
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
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
/***************************************************************************
 *   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 "networkmodel.h"

#include <QAbstractItemView>
#include <QMimeData>
#if QT_VERSION < 0x050000
#include <QTextDocument>        // for Qt::escape()
#endif

#include "buffermodel.h"
#include "buffersettings.h"
#include "client.h"
#include "clientignorelistmanager.h"
#include "clientsettings.h"
#include "ircchannel.h"
#include "network.h"
#include "signalproxy.h"
#include "buffersyncer.h"

/*****************************************
*  Network Items
*****************************************/
NetworkItem::NetworkItem(const NetworkId &netid, AbstractTreeItem *parent)
    : PropertyMapItem(parent),
    _networkId(netid),
    _statusBufferItem(0)
{
    // DO NOT EMIT dataChanged() DIRECTLY IN NetworkItem
    // use networkDataChanged() instead. Otherwise you will end up in a infinite loop
    // as we "sync" the dataChanged() signals of NetworkItem and StatusBufferItem
    setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
    connect(this, SIGNAL(networkDataChanged(int)), this, SIGNAL(dataChanged(int)));
    connect(this, SIGNAL(beginRemoveChilds(int, int)), this, SLOT(onBeginRemoveChilds(int, int)));
}


QStringList NetworkItem::propertyOrder() const
{
    static auto order = QStringList() << "networkName" << "currentServer" << "nickCount";
    return order;
}


QVariant NetworkItem::data(int column, int role) const
{
    switch (role) {
    case NetworkModel::BufferIdRole:
    case NetworkModel::BufferInfoRole:
    case NetworkModel::BufferTypeRole:
    case NetworkModel::BufferActivityRole:
        if (_statusBufferItem)
            return _statusBufferItem->data(column, role);
        else
            return QVariant();
    case NetworkModel::NetworkIdRole:
        return QVariant::fromValue(_networkId);
    case NetworkModel::ItemTypeRole:
        return NetworkModel::NetworkItemType;
    case NetworkModel::ItemActiveRole:
        return isActive();
    default:
        return PropertyMapItem::data(column, role);
    }
}

QString NetworkItem::escapeHTML(const QString &string, bool useNonbreakingSpaces)
{
    // QString.replace() doesn't guarantee the source string will remain constant.
    // Use a local variable to avoid compiler errors.
#if QT_VERSION < 0x050000
    QString formattedString = Qt::escape(string);
#else
    QString formattedString = string.toHtmlEscaped();
#endif
    return (useNonbreakingSpaces ? formattedString.replace(" ", "&nbsp;") : formattedString);
}


// FIXME shouldn't we check the bufferItemCache here?
BufferItem *NetworkItem::findBufferItem(BufferId bufferId)
{
    BufferItem *bufferItem = 0;

    for (int i = 0; i < childCount(); i++) {
        bufferItem = qobject_cast<BufferItem *>(child(i));
        if (!bufferItem)
            continue;
        if (bufferItem->bufferId() == bufferId)
            return bufferItem;
    }
    return 0;
}


BufferItem *NetworkItem::bufferItem(const BufferInfo &bufferInfo)
{
    BufferItem *bufferItem = findBufferItem(bufferInfo);
    if (bufferItem)
        return bufferItem;

    switch (bufferInfo.type()) {
    case BufferInfo::StatusBuffer:
        _statusBufferItem = new StatusBufferItem(bufferInfo, this);
        bufferItem = _statusBufferItem;
        disconnect(this, SIGNAL(networkDataChanged(int)), this, SIGNAL(dataChanged(int)));
        connect(this, SIGNAL(networkDataChanged(int)), bufferItem, SIGNAL(dataChanged(int)));
        connect(bufferItem, SIGNAL(dataChanged(int)), this, SIGNAL(dataChanged(int)));
        break;
    case BufferInfo::ChannelBuffer:
        bufferItem = new ChannelBufferItem(bufferInfo, this);
        break;
    case BufferInfo::QueryBuffer:
        bufferItem = new QueryBufferItem(bufferInfo, this);
        break;
    default:
        bufferItem = new BufferItem(bufferInfo, this);
    }

    newChild(bufferItem);

    // postprocess... this is necessary because Qt doesn't seem to like adding children which already have children on their own
    switch (bufferInfo.type()) {
    case BufferInfo::ChannelBuffer:
    {
        ChannelBufferItem *channelBufferItem = static_cast<ChannelBufferItem *>(bufferItem);
        if (_network) {
            IrcChannel *ircChannel = _network->ircChannel(bufferInfo.bufferName());
            if (ircChannel)
                channelBufferItem->attachIrcChannel(ircChannel);
        }
    }
    break;
    default:
        break;
    }

    BufferSyncer *bufferSyncer = Client::bufferSyncer();
    if (bufferSyncer) {
        bufferItem->addActivity(
                bufferSyncer->activity(bufferItem->bufferId()),
                bufferSyncer->highlightCount(bufferItem->bufferId()) > 0
        );
    }

    return bufferItem;
}


void NetworkItem::attachNetwork(Network *network)
{
    if (!network)
        return;

    _network = network;

    connect(network, SIGNAL(networkNameSet(QString)),
        this, SLOT(setNetworkName(QString)));
    connect(network, SIGNAL(currentServerSet(QString)),
        this, SLOT(setCurrentServer(QString)));
    connect(network, SIGNAL(ircChannelAdded(IrcChannel *)),
        this, SLOT(attachIrcChannel(IrcChannel *)));
    connect(network, SIGNAL(ircUserAdded(IrcUser *)),
        this, SLOT(attachIrcUser(IrcUser *)));
    connect(network, SIGNAL(connectedSet(bool)),
        this, SIGNAL(networkDataChanged()));
    connect(network, SIGNAL(destroyed()),
        this, SLOT(onNetworkDestroyed()));

    emit networkDataChanged();
}


void NetworkItem::attachIrcChannel(IrcChannel *ircChannel)
{
    ChannelBufferItem *channelItem;
    for (int i = 0; i < childCount(); i++) {
        channelItem = qobject_cast<ChannelBufferItem *>(child(i));
        if (!channelItem)
            continue;

        if (channelItem->bufferName().toLower() == ircChannel->name().toLower()) {
            channelItem->attachIrcChannel(ircChannel);
            return;
        }
    }
}


void NetworkItem::attachIrcUser(IrcUser *ircUser)
{
    QueryBufferItem *queryItem = 0;
    for (int i = 0; i < childCount(); i++) {
        queryItem = qobject_cast<QueryBufferItem *>(child(i));
        if (!queryItem)
            continue;

        if (queryItem->bufferName().toLower() == ircUser->nick().toLower()) {
            queryItem->setIrcUser(ircUser);
            break;
        }
    }
}


void NetworkItem::setNetworkName(const QString &networkName)
{
    Q_UNUSED(networkName);
    emit networkDataChanged(0);
}


void NetworkItem::setCurrentServer(const QString &serverName)
{
    Q_UNUSED(serverName);
    emit networkDataChanged(1);
}


QString NetworkItem::toolTip(int column) const
{
    Q_UNUSED(column);
    QString strTooltip;
    QTextStream tooltip( &strTooltip, QIODevice::WriteOnly );
    tooltip << "<qt><style>.bold { font-weight: bold; } .italic { font-style: italic; }</style>";

    // Function to add a row to the tooltip table
    auto addRow = [&](const QString& key, const QString& value, bool condition) {
        if (condition) {
            tooltip << "<tr><td class='bold' align='right'>" << key << "</td><td>" << value << "</td></tr>";
        }
    };

    tooltip << "<p class='bold' align='center'>" << NetworkItem::escapeHTML(networkName(), true) << "</p>";
    if (isActive()) {
        tooltip << "<table cellspacing='5' cellpadding='0'>";
        addRow(tr("Server"), NetworkItem::escapeHTML(currentServer(), true), !currentServer().isEmpty());
        addRow(tr("Users"), QString::number(nickCount()), true);
        if (_network)
            addRow(tr("Lag"), NetworkItem::escapeHTML(tr("%1 msecs").arg(_network->latency()), true), true);

        tooltip << "</table>";
    } else {
        tooltip << "<p class='italic' align='center'>" << tr("Not connected") << "</p>";
    }
    tooltip << "</qt>";
    return strTooltip;
}


void NetworkItem::onBeginRemoveChilds(int start, int end)
{
    for (int i = start; i <= end; i++) {
        StatusBufferItem *statusBufferItem = qobject_cast<StatusBufferItem *>(child(i));
        if (statusBufferItem) {
            _statusBufferItem = 0;
            break;
        }
    }
}


void NetworkItem::onNetworkDestroyed()
{
    _network = 0;
    emit networkDataChanged();
    removeAllChilds();
}


/*****************************************
*  Fancy Buffer Items
*****************************************/
BufferItem::BufferItem(const BufferInfo &bufferInfo, AbstractTreeItem *parent)
    : PropertyMapItem(parent),
    _bufferInfo(bufferInfo),
    _activity(BufferInfo::NoActivity)
{
    setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled);
}


QStringList BufferItem::propertyOrder() const
{
    static auto order = QStringList() << "bufferName" << "topic" << "nickCount";
    return order;
}


void BufferItem::setActivityLevel(BufferInfo::ActivityLevel level)
{
    if (_activity != level) {
        _activity = level;
        emit dataChanged();
    }
}


void BufferItem::clearActivityLevel()
{
    if (Client::isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync)) {
        // If the core handles activity sync, clear only the highlight flag
        _activity &= ~BufferInfo::Highlight;
    } else {
        _activity = BufferInfo::NoActivity;
    }
    _firstUnreadMsgId = MsgId();

    // FIXME remove with core proto v11
    if (!Client::isCoreFeatureEnabled(Quassel::Feature::SynchronizedMarkerLine)) {
        _markerLineMsgId = _lastSeenMsgId;
    }

    emit dataChanged();
}


void BufferItem::updateActivityLevel(const Message &msg)
{
    // If the core handles activity, and this message is not a highlight, ignore this
    if (Client::isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync) && !msg.flags().testFlag(Message::Highlight)) {
        return;
    }

    if (isCurrentBuffer()) {
        return;
    }

    if (msg.flags() & Message::Self)    // don't update activity for our own messages
        return;

    if (Client::ignoreListManager()
        && Client::ignoreListManager()->match(msg, qobject_cast<NetworkItem *>(parent())->networkName()))
        return;

    if (msg.msgId() <= lastSeenMsgId())
        return;

    bool stateChanged = false;
    if (!firstUnreadMsgId().isValid() || msg.msgId() < firstUnreadMsgId()) {
        stateChanged = true;
        _firstUnreadMsgId = msg.msgId();
    }

    Message::Types type;
    // If the core handles activities, ignore types
    if (Client::isCoreFeatureEnabled(Quassel::Feature::BufferActivitySync)) {
        type = Message::Types();
    } else {
        type = msg.type();
    }

    if (addActivity(type, msg.flags().testFlag(Message::Highlight)) || stateChanged) {
        emit dataChanged();
    }
}

void BufferItem::setActivity(Message::Types type, bool highlight) {
    BufferInfo::ActivityLevel oldLevel = activityLevel();

    _activity &= BufferInfo::Highlight;
    addActivity(type, highlight);

    if (_activity != oldLevel) {
        emit dataChanged();
    }
}

bool BufferItem::addActivity(Message::Types type, bool highlight) {
    auto oldActivity = activityLevel();

    if (type != Message::Types())
        _activity |= BufferInfo::OtherActivity;

    if (type.testFlag(Message::Plain) || type.testFlag(Message::Notice) || type.testFlag(Message::Action))
        _activity |= BufferInfo::NewMessage;

    if (highlight)
        _activity |= BufferInfo::Highlight;

    return oldActivity != _activity;
}


QVariant BufferItem::data(int column, int role) const
{
    switch (role) {
    case NetworkModel::ItemTypeRole:
        return NetworkModel::BufferItemType;
    case NetworkModel::BufferIdRole:
        return QVariant::fromValue(bufferInfo().bufferId());
    case NetworkModel::NetworkIdRole:
        return QVariant::fromValue(bufferInfo().networkId());
    case NetworkModel::BufferInfoRole:
        return QVariant::fromValue(bufferInfo());
    case NetworkModel::BufferTypeRole:
        return int(bufferType());
    case NetworkModel::ItemActiveRole:
        return isActive();
    case NetworkModel::BufferActivityRole:
        return (int)activityLevel();
    case NetworkModel::BufferFirstUnreadMsgIdRole:
        return QVariant::fromValue(firstUnreadMsgId());
    case NetworkModel::MarkerLineMsgIdRole:
        return QVariant::fromValue(markerLineMsgId());
    default:
        return PropertyMapItem::data(column, role);
    }
}


bool BufferItem::setData(int column, const QVariant &value, int role)
{
    switch (role) {
    case NetworkModel::BufferActivityRole:
        setActivityLevel((BufferInfo::ActivityLevel)value.toInt());
        return true;
    default:
        return PropertyMapItem::setData(column, value, role);
    }
}


void BufferItem::setBufferName(const QString &name)
{
    _bufferInfo = BufferInfo(_bufferInfo.bufferId(), _bufferInfo.networkId(), _bufferInfo.type(), _bufferInfo.groupId(), name);
    emit dataChanged(0);
}


void BufferItem::setLastSeenMsgId(MsgId msgId)
{
    _lastSeenMsgId = msgId;

    // FIXME remove with core protocol v11
    if (!Client::isCoreFeatureEnabled(Quassel::Feature::SynchronizedMarkerLine)) {
        if (!isCurrentBuffer())
            _markerLineMsgId = msgId;
    }

    setActivityLevel(BufferInfo::NoActivity);
}


void BufferItem::setMarkerLineMsgId(MsgId msgId)
{
    _markerLineMsgId = msgId;
    emit dataChanged();
}


bool BufferItem::isCurrentBuffer() const
{
    return _bufferInfo.bufferId() == Client::bufferModel()->currentIndex().data(NetworkModel::BufferIdRole).value<BufferId>();
}


QString BufferItem::toolTip(int column) const
{
    Q_UNUSED(column);
    return tr("<p> %1 - %2 </p>").arg(bufferInfo().bufferId().toInt()).arg(bufferName());
}


/*****************************************
*  StatusBufferItem
*****************************************/
StatusBufferItem::StatusBufferItem(const BufferInfo &bufferInfo, NetworkItem *parent)
    : BufferItem(bufferInfo, parent)
{
}


QString StatusBufferItem::toolTip(int column) const
{
    NetworkItem *networkItem = qobject_cast<NetworkItem *>(parent());
    if (networkItem)
        return networkItem->toolTip(column);
    else
        return QString();
}


/*****************************************
*  QueryBufferItem
*****************************************/
QueryBufferItem::QueryBufferItem(const BufferInfo &bufferInfo, NetworkItem *parent)
    : BufferItem(bufferInfo, parent),
    _ircUser(0)
{
    setFlags(flags() | Qt::ItemIsDropEnabled | Qt::ItemIsEditable);

    const Network *net = Client::network(bufferInfo.networkId());
    if (!net)
        return;

    IrcUser *ircUser = net->ircUser(bufferInfo.bufferName());
    setIrcUser(ircUser);
}


QVariant QueryBufferItem::data(int column, int role) const
{
    switch (role) {
    case Qt::EditRole:
        return BufferItem::data(column, Qt::DisplayRole);
    case NetworkModel::IrcUserRole:
        return QVariant::fromValue(_ircUser);
    case NetworkModel::UserAwayRole:
        return (bool)_ircUser ? _ircUser->isAway() : false;
    default:
        return BufferItem::data(column, role);
    }
}


bool QueryBufferItem::setData(int column, const QVariant &value, int role)
{
    if (column != 0)
        return BufferItem::setData(column, value, role);

    switch (role) {
    case Qt::EditRole:
    {
        QString newName = value.toString();

        // Sanity check - buffer names must not contain newlines!
        int nlpos = newName.indexOf('\n');
        if (nlpos >= 0)
            newName = newName.left(nlpos);

        if (!newName.isEmpty()) {
            Client::renameBuffer(bufferId(), newName);
            return true;
        }
        else {
            return false;
        }
    }
    break;
    default:
        return BufferItem::setData(column, value, role);
    }
}


void QueryBufferItem::setBufferName(const QString &name)
{
    BufferItem::setBufferName(name);
    NetworkId netId = data(0, NetworkModel::NetworkIdRole).value<NetworkId>();
    const Network *net = Client::network(netId);
    if (net)
        setIrcUser(net->ircUser(name));
}


QString QueryBufferItem::toolTip(int column) const
{
    // pretty much code duplication of IrcUserItem::toolTip() but inheritance won't solve this...
    Q_UNUSED(column);
    QString strTooltip;
    QTextStream tooltip( &strTooltip, QIODevice::WriteOnly );
    tooltip << "<qt><style>.bold { font-weight: bold; } .italic { font-style: italic; }</style>";

    // Keep track of whether or not information has been added
    bool infoAdded = false;

    // Use bufferName() for QueryBufferItem, nickName() for IrcUserItem
    tooltip << "<p class='bold' align='center'>";
    tooltip << tr("Query with %1").arg(NetworkItem::escapeHTML(bufferName(), true));
    if (!_ircUser) {
        // User seems to be offline, let the no information message be added below
        tooltip << "</p>";
    } else {
        // Function to add a row to the tooltip table
        auto addRow = [&](const QString& key, const QString& value, bool condition) {
            if (condition) {
                tooltip << "<tr><td class='bold' align='right'>" << key << "</td><td>" << value << "</td></tr>";
                infoAdded = true;
            }
        };

        // User information is available
        if (_ircUser->userModes() != "") {
            //TODO Translate user Modes and add them to the table below and in IrcUserItem::toolTip
            tooltip << " (" << _ircUser->userModes() << ")";
        }
        tooltip << "</p>";

        tooltip << "<table cellspacing='5' cellpadding='0'>";
        if (_ircUser->isAway()) {
            QString awayMessageHTML = QString("<p class='italic'>%1</p>").arg(tr("Unknown"));

            // If away message is known, replace with the escaped message.
            if (!_ircUser->awayMessage().isEmpty()) {
                awayMessageHTML = NetworkItem::escapeHTML(_ircUser->awayMessage());
            }
            addRow(NetworkItem::escapeHTML(tr("Away message"), true), awayMessageHTML, true);
        }
        addRow(tr("Realname"),
               NetworkItem::escapeHTML(_ircUser->realName()),
               !_ircUser->realName().isEmpty());
        // suserHost may return "<nick> is available for help", which should be translated.
        // See https://www.alien.net.au/irc/irc2numerics.html
        if(_ircUser->suserHost().endsWith("available for help")) {
            addRow(NetworkItem::escapeHTML(tr("Help status"), true),
                   NetworkItem::escapeHTML(tr("Available for help")),
                   true);
        } else {
            addRow(NetworkItem::escapeHTML(tr("Service status"), true),
                   NetworkItem::escapeHTML(_ircUser->suserHost()),
                   !_ircUser->suserHost().isEmpty());
        }

        // Keep track of whether or not the account information's been added.  Don't show it twice.
        bool accountAdded = false;
        if(!_ircUser->account().isEmpty()) {
            // IRCv3 account-notify is supported by the core and IRC server.
            // Assume logged out (seems to be more common)
            QString accountHTML = QString("<p class='italic'>%1</p>").arg(tr("Not logged in"));

            // If account is logged in, replace with the escaped account name.
            if (_ircUser->account() != "*") {
                accountHTML = NetworkItem::escapeHTML(_ircUser->account());
            }
            addRow(NetworkItem::escapeHTML(tr("Account"), true),
                   accountHTML,
                   true);
            // Mark the row as added
            accountAdded = true;
        }
        // whoisServiceReply may return "<nick> is identified for this nick", which should be translated.
        // See https://www.alien.net.au/irc/irc2numerics.html
        if(_ircUser->whoisServiceReply().endsWith("identified for this nick")) {
            addRow(NetworkItem::escapeHTML(tr("Account"), true),
                   NetworkItem::escapeHTML(tr("Identified for this nick")),
                   !accountAdded);
            // Don't add the account row again if information's already added via account-notify
            // Not used further down...
            // accountAdded = true;
        } else {
            addRow(NetworkItem::escapeHTML(tr("Service Reply"), true),
                   NetworkItem::escapeHTML(_ircUser->whoisServiceReply()),
                   !_ircUser->whoisServiceReply().isEmpty());
        }
        addRow(tr("Hostmask"),
               NetworkItem::escapeHTML(_ircUser->hostmask().remove(0, _ircUser->hostmask().indexOf("!") + 1)),
               !(_ircUser->hostmask().remove(0, _ircUser->hostmask().indexOf("!") + 1) == "@"));
        // ircOperator may contain "is an" or "is a", which should be removed.
        addRow(tr("Operator"),
               NetworkItem::escapeHTML(_ircUser->ircOperator().replace("is an ", "").replace("is a ", "")),
               !_ircUser->ircOperator().isEmpty());

        if (_ircUser->idleTime().isValid()) {
            QDateTime now = QDateTime::currentDateTime();
            QDateTime idle = _ircUser->idleTime();
            int idleTime = idle.secsTo(now);
            addRow(NetworkItem::escapeHTML(tr("Idling since"), true), secondsToString(idleTime), true);
        }

        if (_ircUser->loginTime().isValid()) {
            addRow(NetworkItem::escapeHTML(tr("Login time"), true), _ircUser->loginTime().toString(), true);
        }

        addRow(tr("Server"), NetworkItem::escapeHTML(_ircUser->server()), !_ircUser->server().isEmpty());
        tooltip << "</table>";
    }

    // If no further information found, offer an explanatory message
    if (!infoAdded)
        tooltip << "<p class='italic' align='center'>" << tr("No information available") << "</p>";

    tooltip << "</qt>";
    return strTooltip;
}


void QueryBufferItem::setIrcUser(IrcUser *ircUser)
{
    if (_ircUser == ircUser)
        return;

    if (_ircUser) {
        disconnect(_ircUser, 0, this, 0);
    }

    if (ircUser) {
        connect(ircUser, SIGNAL(destroyed(QObject*)), SLOT(removeIrcUser()));
        connect(ircUser, SIGNAL(quited()), this, SLOT(removeIrcUser()));
        connect(ircUser, SIGNAL(awaySet(bool)), this, SIGNAL(dataChanged()));
        connect(ircUser, SIGNAL(encryptedSet(bool)), this, SLOT(setEncrypted(bool)));
    }

    _ircUser = ircUser;
    emit dataChanged();
}


void QueryBufferItem::removeIrcUser()
{
    if (_ircUser) {
        // Disconnect the active IrcUser before removing it, otherwise it will fire removeIrcUser()
        // a second time when the object's destroyed due to QueryBufferItem::setIrcUser() connecting
        // SIGNAL destroyed(QObject*) to SLOT removeIrcUser().
        // This fixes removing an active IrcUser if the user had quit then rejoined in a nonstandard
        // manner (e.g. updateNickFromHost calling newIrcUser, triggered by an away-notify message).
        disconnect(_ircUser, 0, this, 0);

        // Clear IrcUser (only set to 0 if not already 0)
        _ircUser = 0;

        // Only emit dataChanged() if data actually changed.  This might serve as a small
        // optimization, but it can be moved outside the if statement if other behavior depends on
        // it always being called.
        emit dataChanged();
    }
}


/*****************************************
*  ChannelBufferItem
*****************************************/
ChannelBufferItem::ChannelBufferItem(const BufferInfo &bufferInfo, AbstractTreeItem *parent)
    : BufferItem(bufferInfo, parent),
    _ircChannel(0)
{
    setFlags(flags() | Qt::ItemIsDropEnabled);
}


QVariant ChannelBufferItem::data(int column, int role) const
{
    switch (role) {
    case NetworkModel::IrcChannelRole:
        return QVariant::fromValue(_ircChannel);
    default:
        return BufferItem::data(column, role);
    }
}


QString ChannelBufferItem::toolTip(int column) const
{
    Q_UNUSED(column);
    QString strTooltip;
    QTextStream tooltip( &strTooltip, QIODevice::WriteOnly );
    tooltip << "<qt><style>.bold { font-weight: bold; } .italic { font-style: italic; }</style>";

    // Function to add a row to the tooltip table
    auto addRow = [&](const QString& key, const QString& value, bool condition) {
        if (condition) {
            tooltip << "<tr><td class='bold' align='right'>" << key << "</td><td>" << value << "</td></tr>";
        }
    };

    tooltip << "<p class='bold' align='center'>";
    tooltip << NetworkItem::escapeHTML(tr("Channel %1").arg(bufferName()), true) << "</p>";

    if (isActive()) {
        tooltip << "<table cellspacing='5' cellpadding='0'>";
        addRow(tr("Users"), QString::number(nickCount()), true);

        if (_ircChannel) {
            QString channelMode = _ircChannel->channelModeString(); // channelModeString is compiled on the fly -> thus cache the result
            if (!channelMode.isEmpty())
                addRow(tr("Mode"), channelMode, true);
        }

        ItemViewSettings s;
        bool showTopic = s.displayTopicInTooltip();
        if (showTopic) {
            QString _topic = topic();
            if (_topic != "") {
                _topic = stripFormatCodes(_topic);
                _topic = NetworkItem::escapeHTML(_topic);
                addRow(tr("Topic"), _topic, true);
            }
        }

        tooltip << "</table>";
    } else {
        tooltip << "<p class='italic' align='center'>" << tr("Not active, double-click to join") << "</p>";
    }

    tooltip << "</qt>";
    return strTooltip;
}


void ChannelBufferItem::attachIrcChannel(IrcChannel *ircChannel)
{
    if (_ircChannel) {
        qWarning() << Q_FUNC_INFO << "IrcChannel already set; cleanup failed!?";
        disconnect(_ircChannel, 0, this, 0);
    }

    _ircChannel = ircChannel;

    connect(ircChannel, SIGNAL(destroyed(QObject*)),
        this, SLOT(ircChannelDestroyed()));
    connect(ircChannel, SIGNAL(topicSet(QString)),
        this, SLOT(setTopic(QString)));
    connect(ircChannel, SIGNAL(encryptedSet(bool)),
        this, SLOT(setEncrypted(bool)));
    connect(ircChannel, SIGNAL(ircUsersJoined(QList<IrcUser *> )),
        this, SLOT(join(QList<IrcUser *> )));
    connect(ircChannel, SIGNAL(ircUserParted(IrcUser *)),
        this, SLOT(part(IrcUser *)));
    connect(ircChannel, SIGNAL(parted()),
        this, SLOT(ircChannelParted()));
    connect(ircChannel, SIGNAL(ircUserModesSet(IrcUser *, QString)),
        this, SLOT(userModeChanged(IrcUser *)));
    connect(ircChannel, SIGNAL(ircUserModeAdded(IrcUser *, QString)),
        this, SLOT(userModeChanged(IrcUser *)));
    connect(ircChannel, SIGNAL(ircUserModeRemoved(IrcUser *, QString)),
        this, SLOT(userModeChanged(IrcUser *)));

    if (!ircChannel->ircUsers().isEmpty())
        join(ircChannel->ircUsers());

    emit dataChanged();
}

QString ChannelBufferItem::nickChannelModes(const QString &nick) const
{
    if (!_ircChannel) {
        qDebug() << Q_FUNC_INFO << "IrcChannel not set, can't get user modes";
        return QString();
    }

    return _ircChannel->userModes(nick);
}


void ChannelBufferItem::ircChannelParted()
{
    Q_CHECK_PTR(_ircChannel);
    disconnect(_ircChannel, 0, this, 0);
    _ircChannel = 0;
    emit dataChanged();
    removeAllChilds();
}


void ChannelBufferItem::ircChannelDestroyed()
{
    if (_ircChannel) {
        _ircChannel = 0;
        emit dataChanged();
        removeAllChilds();
    }
}


void ChannelBufferItem::join(const QList<IrcUser *> &ircUsers)
{
    addUsersToCategory(ircUsers);
    emit dataChanged(2);
}


UserCategoryItem *ChannelBufferItem::findCategoryItem(int categoryId)
{
    UserCategoryItem *categoryItem = 0;

    for (int i = 0; i < childCount(); i++) {
        categoryItem = qobject_cast<UserCategoryItem *>(child(i));
        if (!categoryItem)
            continue;
        if (categoryItem->categoryId() == categoryId)
            return categoryItem;
    }
    return 0;
}


void ChannelBufferItem::addUserToCategory(IrcUser *ircUser)
{
    addUsersToCategory(QList<IrcUser *>() << ircUser);
}


void ChannelBufferItem::addUsersToCategory(const QList<IrcUser *> &ircUsers)
{
    Q_ASSERT(_ircChannel);

    QHash<UserCategoryItem *, QList<IrcUser *> > categories;

    int categoryId = -1;
    UserCategoryItem *categoryItem = 0;

    foreach(IrcUser *ircUser, ircUsers) {
        categoryId = UserCategoryItem::categoryFromModes(_ircChannel->userModes(ircUser));
        categoryItem = findCategoryItem(categoryId);
        if (!categoryItem) {
            categoryItem = new UserCategoryItem(categoryId, this);
            categories[categoryItem] = QList<IrcUser *>();
            newChild(categoryItem);
        }
        categories[categoryItem] << ircUser;
    }

    QHash<UserCategoryItem *, QList<IrcUser *> >::const_iterator catIter = categories.constBegin();
    while (catIter != categories.constEnd()) {
        catIter.key()->addUsers(catIter.value());
        ++catIter;
    }
}


void ChannelBufferItem::part(IrcUser *ircUser)
{
    if (!ircUser) {
        qWarning() << bufferName() << "ChannelBufferItem::part(): unknown User" << ircUser;
        return;
    }

    disconnect(ircUser, 0, this, 0);
    removeUserFromCategory(ircUser);
    emit dataChanged(2);
}


void ChannelBufferItem::removeUserFromCategory(IrcUser *ircUser)
{
    if (!_ircChannel) {
        // If we parted the channel there might still be some ircUsers connected.
        // in that case we just ignore the call
        Q_ASSERT(childCount() == 0);
        return;
    }

    UserCategoryItem *categoryItem = 0;
    for (int i = 0; i < childCount(); i++) {
        categoryItem = qobject_cast<UserCategoryItem *>(child(i));
        if (categoryItem->removeUser(ircUser)) {
            if (categoryItem->childCount() == 0)
                removeChild(i);
            break;
        }
    }
}


void ChannelBufferItem::userModeChanged(IrcUser *ircUser)
{
    Q_ASSERT(_ircChannel);

    int categoryId = UserCategoryItem::categoryFromModes(_ircChannel->userModes(ircUser));
    UserCategoryItem *categoryItem = findCategoryItem(categoryId);

    if (categoryItem) {
        if (categoryItem->findIrcUser(ircUser)) {
            return; // already in the right category;
        }
    }
    else {
        categoryItem = new UserCategoryItem(categoryId, this);
        newChild(categoryItem);
    }

    // find the item that needs reparenting
    IrcUserItem *ircUserItem = 0;
    for (int i = 0; i < childCount(); i++) {
        UserCategoryItem *oldCategoryItem = qobject_cast<UserCategoryItem *>(child(i));
        Q_ASSERT(oldCategoryItem);
        IrcUserItem *userItem = oldCategoryItem->findIrcUser(ircUser);
        if (userItem) {
            ircUserItem = userItem;
            break;
        }
    }

    if (!ircUserItem) {
        qWarning() << "ChannelBufferItem::userModeChanged(IrcUser *): unable to determine old category of" << ircUser;
        return;
    }
    ircUserItem->reParent(categoryItem);
}


/*****************************************
*  User Category Items (like @vh etc.)
*****************************************/
// we hardcode this even though we have PREFIX in network... but that wouldn't help with mapping modes to
// category strings anyway.
const QList<QChar> UserCategoryItem::categories = QList<QChar>() << 'q' << 'a' << 'o' << 'h' << 'v';

UserCategoryItem::UserCategoryItem(int category, AbstractTreeItem *parent)
    : PropertyMapItem(parent),
    _category(category)
{
    setFlags(Qt::ItemIsEnabled);
    setTreeItemFlags(AbstractTreeItem::DeleteOnLastChildRemoved);
    setObjectName(parent->data(0, Qt::DisplayRole).toString() + "/" + QString::number(category));
}


QStringList UserCategoryItem::propertyOrder() const
{
    static QStringList order{"categoryName"};
    return order;
}


// caching this makes no sense, since we display the user number dynamically
QString UserCategoryItem::categoryName() const
{
    int n = childCount();
    switch (_category) {
    case 0:
        return tr("%n Owner(s)", 0, n);
    case 1:
        return tr("%n Admin(s)", 0, n);
    case 2:
        return tr("%n Operator(s)", 0, n);
    case 3:
        return tr("%n Half-Op(s)", 0, n);
    case 4:
        return tr("%n Voiced", 0, n);
    default:
        return tr("%n User(s)", 0, n);
    }
}


IrcUserItem *UserCategoryItem::findIrcUser(IrcUser *ircUser)
{
    IrcUserItem *userItem = 0;

    for (int i = 0; i < childCount(); i++) {
        userItem = qobject_cast<IrcUserItem *>(child(i));
        if (!userItem)
            continue;
        if (userItem->ircUser() == ircUser)
            return userItem;
    }
    return 0;
}


void UserCategoryItem::addUsers(const QList<IrcUser *> &ircUsers)
{
    QList<AbstractTreeItem *> userItems;
    foreach(IrcUser *ircUser, ircUsers)
    userItems << new IrcUserItem(ircUser, this);
    newChilds(userItems);
    emit dataChanged(0);
}


bool UserCategoryItem::removeUser(IrcUser *ircUser)
{
    IrcUserItem *userItem = findIrcUser(ircUser);
    bool success = (bool)userItem;
    if (success) {
        removeChild(userItem);
        emit dataChanged(0);
    }
    return success;
}


int UserCategoryItem::categoryFromModes(const QString &modes)
{
    for (int i = 0; i < categories.count(); i++) {
        if (modes.contains(categories[i]))
            return i;
    }
    return categories.count();
}


QVariant UserCategoryItem::data(int column, int role) const
{
    switch (role) {
    case TreeModel::SortRole:
        return _category;
    case NetworkModel::ItemActiveRole:
        return true;
    case NetworkModel::ItemTypeRole:
        return NetworkModel::UserCategoryItemType;
    case NetworkModel::BufferIdRole:
        return parent()->data(column, role);
    case NetworkModel::NetworkIdRole:
        return parent()->data(column, role);
    case NetworkModel::BufferInfoRole:
        return parent()->data(column, role);
    default:
        return PropertyMapItem::data(column, role);
    }
}


/*****************************************
*  Irc User Items
*****************************************/
IrcUserItem::IrcUserItem(IrcUser *ircUser, AbstractTreeItem *parent)
    : PropertyMapItem(parent),
    _ircUser(ircUser)
{
    setObjectName(ircUser->nick());
    connect(ircUser, SIGNAL(quited()), this, SLOT(ircUserQuited()));
    connect(ircUser, SIGNAL(nickSet(QString)), this, SIGNAL(dataChanged()));
    connect(ircUser, SIGNAL(awaySet(bool)), this, SIGNAL(dataChanged()));
}


QStringList IrcUserItem::propertyOrder() const
{
    static QStringList order{"nickName"};
    return order;
}


QVariant IrcUserItem::data(int column, int role) const
{
    switch (role) {
    case NetworkModel::ItemActiveRole:
        return isActive();
    case NetworkModel::ItemTypeRole:
        return NetworkModel::IrcUserItemType;
    case NetworkModel::BufferIdRole:
        return parent()->data(column, role);
    case NetworkModel::NetworkIdRole:
        return parent()->data(column, role);
    case NetworkModel::BufferInfoRole:
        return parent()->data(column, role);
    case NetworkModel::IrcChannelRole:
        return parent()->data(column, role);
    case NetworkModel::IrcUserRole:
        return QVariant::fromValue(_ircUser.data());
    case NetworkModel::UserAwayRole:
        return (bool)_ircUser ? _ircUser->isAway() : false;
    default:
        return PropertyMapItem::data(column, role);
    }
}


QString IrcUserItem::toolTip(int column) const
{
    Q_UNUSED(column);
    QString strTooltip;
    QTextStream tooltip( &strTooltip, QIODevice::WriteOnly );
    tooltip << "<qt><style>.bold { font-weight: bold; } .italic { font-style: italic; }</style>";

    // Keep track of whether or not information has been added
    bool infoAdded = false;

    // Use bufferName() for QueryBufferItem, nickName() for IrcUserItem
    tooltip << "<p class='bold' align='center'>" << NetworkItem::escapeHTML(nickName(), true);
    if (_ircUser->userModes() != "") {
        //TODO: Translate user Modes and add them to the table below and in QueryBufferItem::toolTip
        tooltip << " (" << _ircUser->userModes() << ")";
    }
    tooltip << "</p>";

    auto addRow = [&](const QString& key, const QString& value, bool condition) {
        if (condition)
        {
            tooltip << "<tr><td class='bold' align='right'>" << key << "</td><td>" << value << "</td></tr>";
            infoAdded = true;
        }
    };

    tooltip << "<table cellspacing='5' cellpadding='0'>";
    addRow(tr("Modes"),
           NetworkItem::escapeHTML(channelModes()),
           !channelModes().isEmpty());
    if (_ircUser->isAway()) {
        QString awayMessageHTML = QString("<p class='italic'>%1</p>").arg(tr("Unknown"));

        // If away message is known, replace with the escaped message.
        if (!_ircUser->awayMessage().isEmpty()) {
            awayMessageHTML = NetworkItem::escapeHTML(_ircUser->awayMessage());
        }
        addRow(NetworkItem::escapeHTML(tr("Away message"), true), awayMessageHTML, true);
    }
    addRow(tr("Realname"),
           NetworkItem::escapeHTML(_ircUser->realName()),
           !_ircUser->realName().isEmpty());

    // suserHost may return "<nick> is available for help", which should be translated.
    // See https://www.alien.net.au/irc/irc2numerics.html
    if(_ircUser->suserHost().endsWith("available for help")) {
        addRow(NetworkItem::escapeHTML(tr("Help status"), true),
               NetworkItem::escapeHTML(tr("Available for help")),
               true);
    } else {
        addRow(NetworkItem::escapeHTML(tr("Service status"), true),
               NetworkItem::escapeHTML(_ircUser->suserHost()),
               !_ircUser->suserHost().isEmpty());
    }

    // Keep track of whether or not the account information's been added.  Don't show it twice.
    bool accountAdded = false;
    if(!_ircUser->account().isEmpty()) {
        // IRCv3 account-notify is supported by the core and IRC server.
        // Assume logged out (seems to be more common)
        QString accountHTML = QString("<p class='italic'>%1</p>").arg(tr("Not logged in"));

        // If account is logged in, replace with the escaped account name.
        if (_ircUser->account() != "*") {
            accountHTML = NetworkItem::escapeHTML(_ircUser->account());
        }
        addRow(NetworkItem::escapeHTML(tr("Account"), true),
               accountHTML,
               true);
        // Mark the row as added
        accountAdded = true;
    }
    // whoisServiceReply may return "<nick> is identified for this nick", which should be translated.
    // See https://www.alien.net.au/irc/irc2numerics.html
    if(_ircUser->whoisServiceReply().endsWith("identified for this nick")) {
        addRow(NetworkItem::escapeHTML(tr("Account"), true),
               NetworkItem::escapeHTML(tr("Identified for this nick")),
               !accountAdded);
        // Don't add the account row again if information's already added via account-notify
        // Not used further down...
        // accountAdded = true;
    } else {
        addRow(NetworkItem::escapeHTML(tr("Service Reply"), true),
               NetworkItem::escapeHTML(_ircUser->whoisServiceReply()),
               !_ircUser->whoisServiceReply().isEmpty());
    }
    addRow(tr("Hostmask"),
           NetworkItem::escapeHTML(_ircUser->hostmask().remove(0, _ircUser->hostmask().indexOf("!") + 1)),
           !(_ircUser->hostmask().remove(0, _ircUser->hostmask().indexOf("!") + 1) == "@"));
    // ircOperator may contain "is an" or "is a", which should be removed.
    addRow(tr("Operator"),
           NetworkItem::escapeHTML(_ircUser->ircOperator().replace("is an ", "").replace("is a ", "")),
           !_ircUser->ircOperator().isEmpty());

    if (_ircUser->idleTime().isValid()) {
        QDateTime now = QDateTime::currentDateTime();
        QDateTime idle = _ircUser->idleTime();
        int idleTime = idle.secsTo(now);
        addRow(NetworkItem::escapeHTML(tr("Idling since"), true), secondsToString(idleTime), true);
    }

    if (_ircUser->loginTime().isValid()) {
        addRow(NetworkItem::escapeHTML(tr("Login time"), true), _ircUser->loginTime().toString(), true);
    }

    addRow(tr("Server"), NetworkItem::escapeHTML(_ircUser->server()), !_ircUser->server().isEmpty());
    tooltip << "</table>";

    // If no further information found, offer an explanatory message
    if (!infoAdded)
        tooltip << "<p class='italic' align='center'>" << tr("No information available") << "</p>";

    tooltip << "</qt>";
    return strTooltip;
}

QString IrcUserItem::channelModes() const
{
    // IrcUserItems are parented to UserCategoryItem, which are parented to ChannelBufferItem.
    // We want the channel buffer item in order to get the channel-specific user modes.
    UserCategoryItem *category = qobject_cast<UserCategoryItem *>(parent());
    if (!category)
        return QString();

    ChannelBufferItem *channel = qobject_cast<ChannelBufferItem *>(category->parent());
    if (!channel)
        return QString();

    return channel->nickChannelModes(nickName());
}


/*****************************************
 * NetworkModel
 *****************************************/
NetworkModel::NetworkModel(QObject *parent)
    : TreeModel(NetworkModel::defaultHeader(), parent)
{
    connect(this, SIGNAL(rowsInserted(const QModelIndex &, int, int)),
        this, SLOT(checkForNewBuffers(const QModelIndex &, int, int)));
    connect(this, SIGNAL(rowsAboutToBeRemoved(const QModelIndex &, int, int)),
        this, SLOT(checkForRemovedBuffers(const QModelIndex &, int, int)));

    BufferSettings defaultSettings;
    defaultSettings.notify("UserNoticesTarget", this, SLOT(messageRedirectionSettingsChanged()));
    defaultSettings.notify("ServerNoticesTarget", this, SLOT(messageRedirectionSettingsChanged()));
    defaultSettings.notify("ErrorMsgsTarget", this, SLOT(messageRedirectionSettingsChanged()));
    messageRedirectionSettingsChanged();
}


QList<QVariant> NetworkModel::defaultHeader()
{
    QList<QVariant> data;
    data << tr("Chat") << tr("Topic") << tr("Nick Count");
    return data;
}


bool NetworkModel::isBufferIndex(const QModelIndex &index) const
{
    return index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType;
}


int NetworkModel::networkRow(NetworkId networkId) const
{
    NetworkItem *netItem = 0;
    for (int i = 0; i < rootItem->childCount(); i++) {
        netItem = qobject_cast<NetworkItem *>(rootItem->child(i));
        if (!netItem)
            continue;
        if (netItem->networkId() == networkId)
            return i;
    }
    return -1;
}


QModelIndex NetworkModel::networkIndex(NetworkId networkId)
{
    int netRow = networkRow(networkId);
    if (netRow == -1)
        return QModelIndex();
    else
        return indexByItem(qobject_cast<NetworkItem *>(rootItem->child(netRow)));
}


NetworkItem *NetworkModel::findNetworkItem(NetworkId networkId) const
{
    int netRow = networkRow(networkId);
    if (netRow == -1)
        return 0;
    else
        return qobject_cast<NetworkItem *>(rootItem->child(netRow));
}


NetworkItem *NetworkModel::networkItem(NetworkId networkId)
{
    NetworkItem *netItem = findNetworkItem(networkId);

    if (netItem == 0) {
        netItem = new NetworkItem(networkId, rootItem);
        rootItem->newChild(netItem);
    }
    return netItem;
}


void NetworkModel::networkRemoved(const NetworkId &networkId)
{
    int netRow = networkRow(networkId);
    if (netRow != -1) {
        rootItem->removeChild(netRow);
    }
}


QModelIndex NetworkModel::bufferIndex(BufferId bufferId)
{
    if (!_bufferItemCache.contains(bufferId))
        return QModelIndex();

    return indexByItem(_bufferItemCache[bufferId]);
}


BufferItem *NetworkModel::findBufferItem(BufferId bufferId) const
{
    if (_bufferItemCache.contains(bufferId))
        return _bufferItemCache[bufferId];
    else
        return 0;
}


BufferItem *NetworkModel::bufferItem(const BufferInfo &bufferInfo)
{
    if (_bufferItemCache.contains(bufferInfo.bufferId()))
        return _bufferItemCache[bufferInfo.bufferId()];

    NetworkItem *netItem = networkItem(bufferInfo.networkId());
    return netItem->bufferItem(bufferInfo);
}


QStringList NetworkModel::mimeTypes() const
{
    // mimetypes we accept for drops
    QStringList types;
    // comma separated list of colon separated pairs of networkid and bufferid
    // example: 0:1,0:2,1:4
    types << "application/Quassel/BufferItemList";
    return types;
}


bool NetworkModel::mimeContainsBufferList(const QMimeData *mimeData)
{
    return mimeData->hasFormat("application/Quassel/BufferItemList");
}


QList<QPair<NetworkId, BufferId> > NetworkModel::mimeDataToBufferList(const QMimeData *mimeData)
{
    QList<QPair<NetworkId, BufferId> > bufferList;

    if (!mimeContainsBufferList(mimeData))
        return bufferList;

    QStringList rawBufferList = QString::fromLatin1(mimeData->data("application/Quassel/BufferItemList")).split(",");
    NetworkId networkId;
    BufferId bufferUid;
    foreach(QString rawBuffer, rawBufferList) {
        if (!rawBuffer.contains(":"))
            continue;
        networkId = rawBuffer.section(":", 0, 0).toInt();
        bufferUid = rawBuffer.section(":", 1, 1).toInt();
        bufferList.append(qMakePair(networkId, bufferUid));
    }
    return bufferList;
}


QMimeData *NetworkModel::mimeData(const QModelIndexList &indexes) const
{
    QMimeData *mimeData = new QMimeData();

    QStringList bufferlist;
    QString netid, uid, bufferid;
    foreach(QModelIndex index, indexes) {
        netid = QString::number(index.data(NetworkIdRole).value<NetworkId>().toInt());
        uid = QString::number(index.data(BufferIdRole).value<BufferId>().toInt());
        bufferid = QString("%1:%2").arg(netid).arg(uid);
        if (!bufferlist.contains(bufferid))
            bufferlist << bufferid;
    }

    mimeData->setData("application/Quassel/BufferItemList", bufferlist.join(",").toLatin1());

    return mimeData;
}


void NetworkModel::attachNetwork(Network *net)
{
    NetworkItem *netItem = networkItem(net->networkId());
    netItem->attachNetwork(net);
}


void NetworkModel::bufferUpdated(BufferInfo bufferInfo)
{
    BufferItem *bufItem = bufferItem(bufferInfo);
    QModelIndex itemindex = indexByItem(bufItem);
    emit dataChanged(itemindex, itemindex);
}


void NetworkModel::removeBuffer(BufferId bufferId)
{
    BufferItem *buffItem = findBufferItem(bufferId);
    if (!buffItem)
        return;

    buffItem->parent()->removeChild(buffItem);
}


MsgId NetworkModel::lastSeenMsgId(BufferId bufferId) const
{
    if (!_bufferItemCache.contains(bufferId))
        return MsgId();

    return _bufferItemCache[bufferId]->lastSeenMsgId();
}


MsgId NetworkModel::markerLineMsgId(BufferId bufferId) const
{
    if (!_bufferItemCache.contains(bufferId))
        return MsgId();

    return _bufferItemCache[bufferId]->markerLineMsgId();
}


// FIXME we always seem to use this (expensive) non-const version
MsgId NetworkModel::lastSeenMsgId(const BufferId &bufferId)
{
    BufferItem *bufferItem = findBufferItem(bufferId);
    if (!bufferItem) {
        qDebug() << "NetworkModel::lastSeenMsgId(): buffer is unknown:" << bufferId;
        Client::purgeKnownBufferIds();
        return MsgId();
    }
    return bufferItem->lastSeenMsgId();
}


void NetworkModel::setLastSeenMsgId(const BufferId &bufferId, const MsgId &msgId)
{
    BufferItem *bufferItem = findBufferItem(bufferId);
    if (!bufferItem) {
        qDebug() << "NetworkModel::setLastSeenMsgId(): buffer is unknown:" << bufferId;
        Client::purgeKnownBufferIds();
        return;
    }
    bufferItem->setLastSeenMsgId(msgId);
    emit lastSeenMsgSet(bufferId, msgId);
}


void NetworkModel::setMarkerLineMsgId(const BufferId &bufferId, const MsgId &msgId)
{
    BufferItem *bufferItem = findBufferItem(bufferId);
    if (!bufferItem) {
        qDebug() << "NetworkModel::setMarkerLineMsgId(): buffer is unknown:" << bufferId;
        Client::purgeKnownBufferIds();
        return;
    }
    bufferItem->setMarkerLineMsgId(msgId);
    emit markerLineSet(bufferId, msgId);
}


void NetworkModel::updateBufferActivity(Message &msg)
{
    int redirectionTarget = 0;
    switch (msg.type()) {
    case Message::Notice:
        if (bufferType(msg.bufferId()) != BufferInfo::ChannelBuffer) {
            msg.setFlags(msg.flags() | Message::Redirected);
            if (msg.flags() & Message::ServerMsg) {
                // server notice
                redirectionTarget = _serverNoticesTarget;
            }
            else {
                redirectionTarget = _userNoticesTarget;
            }
        }
        break;
    case Message::Error:
        msg.setFlags(msg.flags() | Message::Redirected);
        redirectionTarget = _errorMsgsTarget;
        break;
    // Update IrcUser's last activity
    case Message::Plain:
    case Message::Action:
        if (bufferType(msg.bufferId()) == BufferInfo::ChannelBuffer) {
            const Network *net = Client::network(msg.bufferInfo().networkId());
            IrcUser *user = net ? net->ircUser(nickFromMask(msg.sender())) : 0;
            if (user)
                user->setLastChannelActivity(msg.bufferId(), msg.timestamp());
        }
        break;
    default:
        break;
    }

    if (msg.flags() & Message::Redirected) {
        if (redirectionTarget & BufferSettings::DefaultBuffer)
            updateBufferActivity(bufferItem(msg.bufferInfo()), msg);

        if (redirectionTarget & BufferSettings::StatusBuffer) {
            const NetworkItem *netItem = findNetworkItem(msg.bufferInfo().networkId());
            if (netItem) {
                updateBufferActivity(netItem->statusBufferItem(), msg);
            }
        }
    }
    else {
        if ((BufferSettings(msg.bufferId()).messageFilter() & msg.type()) != msg.type())
            updateBufferActivity(bufferItem(msg.bufferInfo()), msg);
    }
}


void NetworkModel::updateBufferActivity(BufferItem *bufferItem, const Message &msg)
{
    if (!bufferItem)
        return;

    bufferItem->updateActivityLevel(msg);
    if (bufferItem->isCurrentBuffer())
        emit requestSetLastSeenMsg(bufferItem->bufferId(), msg.msgId());
}


void NetworkModel::setBufferActivity(const BufferId &bufferId, BufferInfo::ActivityLevel level)
{
    BufferItem *bufferItem = findBufferItem(bufferId);
    if (!bufferItem) {
        qDebug() << "NetworkModel::setBufferActivity(): buffer is unknown:" << bufferId;
        return;
    }
    bufferItem->setActivityLevel(level);
}


void NetworkModel::clearBufferActivity(const BufferId &bufferId)
{
    BufferItem *bufferItem = findBufferItem(bufferId);
    if (!bufferItem) {
        qDebug() << "NetworkModel::clearBufferActivity(): buffer is unknown:" << bufferId;
        return;
    }
    bufferItem->clearActivityLevel();
}


const Network *NetworkModel::networkByIndex(const QModelIndex &index) const
{
    QVariant netVariant = index.data(NetworkIdRole);
    if (!netVariant.isValid())
        return 0;

    NetworkId networkId = netVariant.value<NetworkId>();
    return Client::network(networkId);
}


void NetworkModel::checkForRemovedBuffers(const QModelIndex &parent, int start, int end)
{
    if (parent.data(ItemTypeRole) != NetworkItemType)
        return;

    for (int row = start; row <= end; row++) {
        _bufferItemCache.remove(parent.child(row, 0).data(BufferIdRole).value<BufferId>());
    }
}


void NetworkModel::checkForNewBuffers(const QModelIndex &parent, int start, int end)
{
    if (parent.data(ItemTypeRole) != NetworkItemType)
        return;

    for (int row = start; row <= end; row++) {
        QModelIndex child = parent.child(row, 0);
        _bufferItemCache[child.data(BufferIdRole).value < BufferId > ()] = static_cast<BufferItem *>(child.internalPointer());
    }
}


QString NetworkModel::bufferName(BufferId bufferId) const
{
    if (!_bufferItemCache.contains(bufferId))
        return QString();

    return _bufferItemCache[bufferId]->bufferName();
}


BufferInfo::Type NetworkModel::bufferType(BufferId bufferId) const
{
    if (!_bufferItemCache.contains(bufferId))
        return BufferInfo::InvalidBuffer;

    return _bufferItemCache[bufferId]->bufferType();
}


BufferInfo NetworkModel::bufferInfo(BufferId bufferId) const
{
    if (!_bufferItemCache.contains(bufferId))
        return BufferInfo();

    return _bufferItemCache[bufferId]->bufferInfo();
}


NetworkId NetworkModel::networkId(BufferId bufferId) const
{
    if (!_bufferItemCache.contains(bufferId))
        return NetworkId();

    NetworkItem *netItem = qobject_cast<NetworkItem *>(_bufferItemCache[bufferId]->parent());
    if (netItem)
        return netItem->networkId();
    else
        return NetworkId();
}


QString NetworkModel::networkName(BufferId bufferId) const
{
    if (!_bufferItemCache.contains(bufferId))
        return QString();

    NetworkItem *netItem = qobject_cast<NetworkItem *>(_bufferItemCache[bufferId]->parent());
    if (netItem)
        return netItem->networkName();
    else
        return QString();
}


BufferId NetworkModel::bufferId(NetworkId networkId, const QString &bufferName, Qt::CaseSensitivity cs) const
{
    const NetworkItem *netItem = findNetworkItem(networkId);
    if (!netItem)
        return BufferId();

    for (int i = 0; i < netItem->childCount(); i++) {
        BufferItem *bufferItem = qobject_cast<BufferItem *>(netItem->child(i));
        if (bufferItem && !bufferItem->bufferName().compare(bufferName, cs))
            return bufferItem->bufferId();
    }
    return BufferId();
}


void NetworkModel::sortBufferIds(QList<BufferId> &bufferIds) const
{
    QList<BufferItem *> bufferItems;
    foreach(BufferId bufferId, bufferIds) {
        if (_bufferItemCache.contains(bufferId))
            bufferItems << _bufferItemCache[bufferId];
    }

    qSort(bufferItems.begin(), bufferItems.end(), bufferItemLessThan);

    bufferIds.clear();
    foreach(BufferItem *bufferItem, bufferItems) {
        bufferIds << bufferItem->bufferId();
    }
}


QList<BufferId> NetworkModel::allBufferIdsSorted() const
{
    QList<BufferId> bufferIds = allBufferIds();
    sortBufferIds(bufferIds);
    return bufferIds;
}


bool NetworkModel::bufferItemLessThan(const BufferItem *left, const BufferItem *right)
{
    int leftType = left->bufferType();
    int rightType = right->bufferType();

    if (leftType != rightType)
        return leftType < rightType;
    else
        return QString::compare(left->bufferName(), right->bufferName(), Qt::CaseInsensitive) < 0;
}


void NetworkModel::messageRedirectionSettingsChanged()
{
    BufferSettings bufferSettings;

    _userNoticesTarget = bufferSettings.userNoticesTarget();
    _serverNoticesTarget = bufferSettings.serverNoticesTarget();
    _errorMsgsTarget = bufferSettings.errorMsgsTarget();
}

void NetworkModel::bufferActivityChanged(BufferId bufferId, const Message::Types activity) {
    auto _bufferItem = findBufferItem(bufferId);
    if (!_bufferItem) {
        qDebug() << "NetworkModel::bufferActivityChanged(): buffer is unknown:" << bufferId;
        return;
    }
    auto hiddenTypes = BufferSettings(bufferId).messageFilter();
    auto visibleTypes = ~hiddenTypes;
    auto activityVisibleTypesIntersection = activity & visibleTypes;
    _bufferItem->setActivity(activityVisibleTypesIntersection, false);
}

void NetworkModel::highlightCountChanged(BufferId bufferId, int count) {
    auto _bufferItem = findBufferItem(bufferId);
    if (!_bufferItem) {
        qDebug() << "NetworkModel::highlightCountChanged(): buffer is unknown:" << bufferId;
        return;
    }
    _bufferItem->addActivity(Message::Types{}, count > 0);
}