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 beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
313 _messagesWaiting.clear();
316 // returns index of msg with given Id or of the next message after that (i.e., the index where we'd insert this msg)
317 int MessageModel::indexForId(MsgId id) {
318 if(messagesIsEmpty() || id <= messageItemAt(0)->msgId())
321 if(id > lastMessageItem()->msgId())
322 return messageCount();
325 int start = 0; int end = messageCount() - 1;
329 int pivot = (end + start) / 2;
330 if(id <= messageItemAt(pivot)->msgId()) end = pivot;
335 void MessageModel::changeOfDay() {
336 _dayChangeTimer.setInterval(86400000);
337 if(!messagesIsEmpty()) {
338 int idx = messageCount();
339 while(idx > 0 && messageItemAt(idx - 1)->timestamp() > _nextDayChange) {
342 beginInsertRows(QModelIndex(), idx, idx);
343 Message dayChangeMsg = Message::ChangeOfDay(_nextDayChange);
344 dayChangeMsg.setMsgId(messageItemAt(idx - 1)->msgId());
345 insertMessage__(idx, dayChangeMsg);
348 _nextDayChange = _nextDayChange.addSecs(86400);
351 void MessageModel::requestBacklog(BufferId bufferId) {
352 if(_messagesWaiting.contains(bufferId))
355 BacklogSettings backlogSettings;
356 int requestCount = backlogSettings.dynamicBacklogAmount();
358 for(int i = 0; i < messageCount(); i++) {
359 if(messageItemAt(i)->bufferId() == bufferId) {
360 _messagesWaiting[bufferId] = requestCount;
361 Client::backlogManager()->emitMessagesRequested(tr("Requesting %1 messages from backlog for buffer %2:%3")
363 .arg(Client::networkModel()->networkName(bufferId))
364 .arg(Client::networkModel()->bufferName(bufferId)));
365 Client::backlogManager()->requestBacklog(bufferId, -1, messageItemAt(i)->msgId(), requestCount);
371 void MessageModel::messagesReceived(BufferId bufferId, int count) {
372 if(!_messagesWaiting.contains(bufferId))
375 _messagesWaiting[bufferId] -= count;
376 if(_messagesWaiting[bufferId] <= 0)
377 _messagesWaiting.remove(bufferId);
380 void MessageModel::buffersPermanentlyMerged(BufferId bufferId1, BufferId bufferId2) {
381 for(int i = 0; i < messageCount(); i++) {
382 if(messageItemAt(i)->bufferId() == bufferId2) {
383 messageItemAt(i)->setBufferId(bufferId1);
384 QModelIndex idx = index(i, 0);
385 emit dataChanged(idx, idx);
390 // ========================================
392 // ========================================
393 QVariant MessageModelItem::data(int column, int role) const {
394 if(column < MessageModel::TimestampColumn || column > MessageModel::ContentsColumn)
398 case MessageModel::MsgIdRole: return QVariant::fromValue<MsgId>(msgId());
399 case MessageModel::BufferIdRole: return QVariant::fromValue<BufferId>(bufferId());
400 case MessageModel::TypeRole: return msgType();
401 case MessageModel::FlagsRole: return (int)msgFlags();
402 case MessageModel::TimestampRole: return timestamp();
403 case MessageModel::RedirectedToRole: return qVariantFromValue<BufferId>(_redirectedTo);
404 default: return QVariant();
408 bool MessageModelItem::setData(int column, const QVariant &value, int role) {
412 case MessageModel::RedirectedToRole:
413 _redirectedTo = value.value<BufferId>();
421 bool MessageModelItem::lessThan(const MessageModelItem *m1, const MessageModelItem *m2){
422 return (*m1) < (*m2);
425 bool MessageModelItem::operator<(const MessageModelItem &other) const {
426 return msgId() < other.msgId();
429 bool MessageModelItem::operator==(const MessageModelItem &other) const {
430 return msgId() == other.msgId();
433 bool MessageModelItem::operator>(const MessageModelItem &other) const {
434 return msgId() > other.msgId();
437 QDebug operator<<(QDebug dbg, const MessageModelItem &msgItem) {
438 dbg.nospace() << qPrintable(QString("MessageModelItem(MsgId:")) << msgItem.msgId()
439 << qPrintable(QString(",")) << msgItem.timestamp()
440 << qPrintable(QString(", Type:")) << msgItem.msgType()
441 << qPrintable(QString(", Flags:")) << msgItem.msgFlags() << qPrintable(QString(")"))
442 << msgItem.data(1, Qt::DisplayRole).toString() << ":" << msgItem.data(2, Qt::DisplayRole).toString();