1 /***************************************************************************
2 * Copyright (C) 2005-09 by the Quassel Project *
3 * devel@quassel-irc.org *
5 * This program is free software; you can redistribute it and/or modify *
6 * it under the terms of the GNU General Public License as published by *
7 * the Free Software Foundation; either version 2 of the License, or *
8 * (at your option) version 3. *
10 * This program is distributed in the hope that it will be useful, *
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13 * GNU General Public License for more details. *
15 * You should have received a copy of the GNU General Public License *
16 * along with this program; if not, write to the *
17 * Free Software Foundation, Inc., *
18 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19 ***************************************************************************/
21 #include "messagemodel.h"
25 #include "backlogsettings.h"
26 #include "clientbacklogmanager.h"
29 #include "networkmodel.h"
31 class ProcessBufferEvent : public QEvent {
33 inline ProcessBufferEvent() : QEvent(QEvent::User) {}
36 MessageModel::MessageModel(QObject *parent)
37 : QAbstractItemModel(parent)
39 QDateTime now = QDateTime::currentDateTime();
40 now.setTimeSpec(Qt::UTC);
41 _nextDayChange.setTimeSpec(Qt::UTC);
42 _nextDayChange.setTime_t(((now.toTime_t() / 86400) + 1) * 86400);
43 _nextDayChange.setTimeSpec(Qt::LocalTime);
44 _dayChangeTimer.setInterval(QDateTime::currentDateTime().secsTo(_nextDayChange) * 1000);
45 _dayChangeTimer.start();
46 connect(&_dayChangeTimer, SIGNAL(timeout()), this, SLOT(changeOfDay()));
49 QVariant MessageModel::data(const QModelIndex &index, int role) const {
50 int row = index.row(); int column = index.column();
51 if(row < 0 || row >= messageCount() || column < 0)
54 if(role == ColumnTypeRole)
57 return messageItemAt(row)->data(index.column(), role);
58 // return _messageList[row]->data(index.column(), role);
61 bool MessageModel::setData(const QModelIndex &index, const QVariant &value, int role) {
62 int row = index.row();
63 if(row < 0 || row >= messageCount())
66 if(messageItemAt(row)->setData(index.column(), value, role)) {
67 emit dataChanged(index, index);
73 bool MessageModel::insertMessage(const Message &msg, bool fakeMsg) {
74 MsgId id = msg.msgId();
75 int idx = indexForId(id);
76 if(!fakeMsg && idx < messageCount()) { // check for duplicate
77 if(messageItemAt(idx)->msgId() == id)
81 insertMessageGroup(QList<Message>() << msg);
85 void MessageModel::insertMessages(const QList<Message> &msglist) {
89 if(_messageBuffer.isEmpty()) {
90 int processedMsgs = insertMessagesGracefully(msglist);
91 int remainingMsgs = msglist.count() - processedMsgs;
92 if(remainingMsgs > 0) {
93 if(msglist.first().msgId() < msglist.last().msgId()) {
94 // in Order - we have just successfully processed "processedMsg" messages from the end of the list
95 _messageBuffer = msglist.mid(0, remainingMsgs);
97 _messageBuffer = msglist.mid(processedMsgs);
99 qSort(_messageBuffer);
100 QCoreApplication::postEvent(this, new ProcessBufferEvent());
103 _messageBuffer << msglist;
104 qSort(_messageBuffer);
108 void MessageModel::insertMessageGroup(const QList<Message> &msglist) {
109 Q_ASSERT(!msglist.isEmpty()); // the msglist can be assumed to be non empty
110 // int last = msglist.count() - 1;
111 // Q_ASSERT(0 == last || msglist.at(0).msgId() != msglist.at(last).msgId() || msglist.at(last).type() == Message::DayChange);
112 int start = indexForId(msglist.first().msgId());
113 int end = start + msglist.count() - 1;
114 Message dayChangeMsg;
117 // check if the preceeding msg is a daychange message and if so if
118 // we have to drop or relocate it at the end of this chunk
119 int prevIdx = start - 1;
120 if(messageItemAt(prevIdx)->msgType() == Message::DayChange
121 && messageItemAt(prevIdx)->timestamp() > msglist.at(0).timestamp()) {
123 beginRemoveRows(QModelIndex(), prevIdx, prevIdx);
124 Message oldDayChangeMsg = takeMessageAt(prevIdx);
125 if(msglist.last().timestamp() < oldDayChangeMsg.timestamp()) {
126 // we have to reinsert it with a changed msgId
127 dayChangeMsg = oldDayChangeMsg;
128 dayChangeMsg.setMsgId(msglist.last().msgId());
137 if(!dayChangeMsg.isValid() && start < messageCount()) {
138 // if(!dayChangeItem && start < _messageList.count()) {
139 // check if we need to insert a daychange message at the end of the this group
141 // if this assert triggers then indexForId() would have found a spot right before a DayChangeMsg
142 // this should never happen as daychange messages share the msgId with the preceeding message
143 Q_ASSERT(messageItemAt(start)->msgType() != Message::DayChange);
144 QDateTime nextTs = messageItemAt(start)->timestamp();
145 QDateTime prevTs = msglist.last().timestamp();
146 nextTs.setTimeSpec(Qt::UTC);
147 prevTs.setTimeSpec(Qt::UTC);
148 uint nextDay = nextTs.toTime_t() / 86400;
149 uint prevDay = prevTs.toTime_t() / 86400;
150 if(nextDay != prevDay) {
151 nextTs.setTime_t(nextDay * 86400);
152 nextTs.setTimeSpec(Qt::LocalTime);
153 dayChangeMsg = Message::ChangeOfDay(nextTs);
154 dayChangeMsg.setMsgId(msglist.last().msgId());
158 if(dayChangeMsg.isValid())
161 Q_ASSERT(start == 0 || messageItemAt(start - 1)->msgId() < msglist.first().msgId());
162 Q_ASSERT(start == messageCount() || messageItemAt(start)->msgId() > msglist.last().msgId());
163 beginInsertRows(QModelIndex(), start, end);
164 insertMessages__(start, msglist);
165 if(dayChangeMsg.isValid())
166 insertMessage__(start + msglist.count(), dayChangeMsg);
169 Q_ASSERT(start == end || messageItemAt(start)->msgId() != messageItemAt(end)->msgId() || messageItemAt(end)->msgType() == Message::DayChange);
170 Q_ASSERT(start == 0 || messageItemAt(start - 1)->msgId() < messageItemAt(start)->msgId());
171 Q_ASSERT(end + 1 == messageCount() || messageItemAt(end)->msgId() < messageItemAt(end + 1)->msgId());
174 int MessageModel::insertMessagesGracefully(const QList<Message> &msglist) {
175 /* short description:
176 * 1) first we check where the message with the highest msgId from msglist would be inserted
177 * 2) check that position for dupe
178 * 3) determine the messageId of the preceeding msg
179 * 4) insert as many msgs from msglist with with msgId larger then the just determined id
180 * those messages are automatically less then the msg of the position we just determined in 1)
182 bool inOrder = (msglist.first().msgId() < msglist.last().msgId());
183 // depending on the order we have to traverse from the front to the back or vice versa
185 QList<Message> grouplist;
188 int processedMsgs = 1; // we know the list isn't empty, so we at least process one message
190 bool fastForward = false;
191 QList<Message>::const_iterator iter;
193 iter = msglist.constEnd();
194 iter--; // this op is safe as we've allready passed an empty check
196 iter = msglist.constBegin();
199 idx = indexForId((*iter).msgId());
200 if(idx < messageCount())
201 dupeId = messageItemAt(idx)->msgId();
203 // we always compare to the previous entry...
204 // if there isn't, we can fastforward to the top
206 minId = messageItemAt(idx - 1)->msgId();
210 if((*iter).msgId() != dupeId) {
212 dupeId = (*iter).msgId();
219 while(iter != msglist.constBegin()) {
222 if(!fastForward && (*iter).msgId() <= minId)
226 if(grouplist.isEmpty()) { // as long as we don't have a starting point, we have to update the dupeId
227 idx = indexForId((*iter).msgId());
228 if(idx >= 0 && !messagesIsEmpty())
229 dupeId = messageItemAt(idx)->msgId();
231 if((*iter).msgId() != dupeId) {
232 if(!grouplist.isEmpty()) {
233 QDateTime nextTs = grouplist.value(0).timestamp();
234 QDateTime prevTs = (*iter).timestamp();
235 nextTs.setTimeSpec(Qt::UTC);
236 prevTs.setTimeSpec(Qt::UTC);
237 uint nextDay = nextTs.toTime_t() / 86400;
238 uint prevDay = prevTs.toTime_t() / 86400;
239 if(nextDay != prevDay) {
240 nextTs.setTime_t(nextDay * 86400);
241 nextTs.setTimeSpec(Qt::LocalTime);
242 Message dayChangeMsg = Message::ChangeOfDay(nextTs);
243 dayChangeMsg.setMsgId((*iter).msgId());
244 grouplist.prepend(dayChangeMsg);
247 dupeId = (*iter).msgId();
248 grouplist.prepend(*iter);
252 while(iter != msglist.constEnd()) {
253 if(!fastForward && (*iter).msgId() <= minId)
257 if(grouplist.isEmpty()) { // as long as we don't have a starting point, we have to update the dupeId
258 idx = indexForId((*iter).msgId());
259 if(idx >= 0 && !messagesIsEmpty())
260 dupeId = messageItemAt(idx)->msgId();
262 if((*iter).msgId() != dupeId) {
263 if(!grouplist.isEmpty()) {
264 QDateTime nextTs = grouplist.value(0).timestamp();
265 QDateTime prevTs = (*iter).timestamp();
266 nextTs.setTimeSpec(Qt::UTC);
267 prevTs.setTimeSpec(Qt::UTC);
268 uint nextDay = nextTs.toTime_t() / 86400;
269 uint prevDay = prevTs.toTime_t() / 86400;
270 if(nextDay != prevDay) {
271 nextTs.setTime_t(nextDay * 86400);
272 nextTs.setTimeSpec(Qt::LocalTime);
273 Message dayChangeMsg = Message::ChangeOfDay(nextTs);
274 dayChangeMsg.setMsgId((*iter).msgId());
275 grouplist.prepend(dayChangeMsg);
278 dupeId = (*iter).msgId();
279 grouplist.prepend(*iter);
285 if(!grouplist.isEmpty())
286 insertMessageGroup(grouplist);
287 return processedMsgs;
290 void MessageModel::customEvent(QEvent *event) {
291 if(event->type() != QEvent::User)
296 if(_messageBuffer.isEmpty())
299 int processedMsgs = insertMessagesGracefully(_messageBuffer);
300 int remainingMsgs = _messageBuffer.count() - processedMsgs;
302 QList<Message>::iterator removeStart = _messageBuffer.begin() + remainingMsgs;
303 QList<Message>::iterator removeEnd = _messageBuffer.end();
304 _messageBuffer.erase(removeStart, removeEnd);
305 if(!_messageBuffer.isEmpty())
306 QCoreApplication::postEvent(this, new ProcessBufferEvent());
309 void MessageModel::clear() {
310 _messagesWaiting.clear();
311 if (rowCount() > 0) {
312 beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
318 // returns index of msg with given Id or of the next message after that (i.e., the index where we'd insert this msg)
319 int MessageModel::indexForId(MsgId id) {
320 if(messagesIsEmpty() || id <= messageItemAt(0)->msgId())
323 if(id > lastMessageItem()->msgId())
324 return messageCount();
327 int start = 0; int end = messageCount() - 1;
331 int pivot = (end + start) / 2;
332 if(id <= messageItemAt(pivot)->msgId()) end = pivot;
337 void MessageModel::changeOfDay() {
338 _dayChangeTimer.setInterval(86400000);
339 if(!messagesIsEmpty()) {
340 int idx = messageCount();
341 while(idx > 0 && messageItemAt(idx - 1)->timestamp() > _nextDayChange) {
344 beginInsertRows(QModelIndex(), idx, idx);
345 Message dayChangeMsg = Message::ChangeOfDay(_nextDayChange);
346 dayChangeMsg.setMsgId(messageItemAt(idx - 1)->msgId());
347 insertMessage__(idx, dayChangeMsg);
350 _nextDayChange = _nextDayChange.addSecs(86400);
353 void MessageModel::insertErrorMessage(BufferInfo bufferInfo, const QString &errorString) {
354 int idx = messageCount();
355 beginInsertRows(QModelIndex(), idx, idx);
356 Message msg(bufferInfo, Message::Error, errorString);
357 if(!messagesIsEmpty())
358 msg.setMsgId(messageItemAt(idx-1)->msgId());
361 insertMessage__(idx, msg);
365 void MessageModel::requestBacklog(BufferId bufferId) {
366 if(_messagesWaiting.contains(bufferId))
369 BacklogSettings backlogSettings;
370 int requestCount = backlogSettings.dynamicBacklogAmount();
372 for(int i = 0; i < messageCount(); i++) {
373 if(messageItemAt(i)->bufferId() == bufferId) {
374 _messagesWaiting[bufferId] = requestCount;
375 Client::backlogManager()->emitMessagesRequested(tr("Requesting %1 messages from backlog for buffer %2:%3")
377 .arg(Client::networkModel()->networkName(bufferId))
378 .arg(Client::networkModel()->bufferName(bufferId)));
379 Client::backlogManager()->requestBacklog(bufferId, -1, messageItemAt(i)->msgId(), requestCount);
385 void MessageModel::messagesReceived(BufferId bufferId, int count) {
386 if(!_messagesWaiting.contains(bufferId))
389 _messagesWaiting[bufferId] -= count;
390 if(_messagesWaiting[bufferId] <= 0) {
391 _messagesWaiting.remove(bufferId);
392 emit finishedBacklogFetch(bufferId);
396 void MessageModel::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) {
397 for(int i = 0; i < messageCount(); i++) {
398 if(messageItemAt(i)->bufferId() == bufferId2) {
399 messageItemAt(i)->setBufferId(bufferId1);
400 QModelIndex idx = index(i, 0);
401 emit dataChanged(idx, idx);
406 // ========================================
408 // ========================================
409 QVariant MessageModelItem::data(int column, int role) const {
410 if(column < MessageModel::TimestampColumn || column > MessageModel::ContentsColumn)
414 case MessageModel::MessageRole: return QVariant::fromValue<Message>(message());
415 case MessageModel::MsgIdRole: return QVariant::fromValue<MsgId>(msgId());
416 case MessageModel::BufferIdRole: return QVariant::fromValue<BufferId>(bufferId());
417 case MessageModel::TypeRole: return msgType();
418 case MessageModel::FlagsRole: return (int)msgFlags();
419 case MessageModel::TimestampRole: return timestamp();
420 case MessageModel::RedirectedToRole: return qVariantFromValue<BufferId>(_redirectedTo);
421 default: return QVariant();
425 bool MessageModelItem::setData(int column, const QVariant &value, int role) {
429 case MessageModel::RedirectedToRole:
430 _redirectedTo = value.value<BufferId>();
438 bool MessageModelItem::lessThan(const MessageModelItem *m1, const MessageModelItem *m2){
439 return (*m1) < (*m2);
442 bool MessageModelItem::operator<(const MessageModelItem &other) const {
443 return msgId() < other.msgId();
446 bool MessageModelItem::operator==(const MessageModelItem &other) const {
447 return msgId() == other.msgId();
450 bool MessageModelItem::operator>(const MessageModelItem &other) const {
451 return msgId() > other.msgId();
454 QDebug operator<<(QDebug dbg, const MessageModelItem &msgItem) {
455 dbg.nospace() << qPrintable(QString("MessageModelItem(MsgId:")) << msgItem.msgId()
456 << qPrintable(QString(",")) << msgItem.timestamp()
457 << qPrintable(QString(", Type:")) << msgItem.msgType()
458 << qPrintable(QString(", Flags:")) << msgItem.msgFlags() << qPrintable(QString(")"))
459 << msgItem.data(1, Qt::DisplayRole).toString() << ":" << msgItem.data(2, Qt::DisplayRole).toString();