properly fixing inserting and deleting chatlines at arbitrary positions in the scene
[quassel.git] / src / client / messagemodel.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel IRC Team                         *
3  *   devel@quassel-irc.org                                                 *
4  *                                                                         *
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.                                           *
9  *                                                                         *
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.                          *
14  *                                                                         *
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  ***************************************************************************/
20
21 #include "messagemodel.h"
22
23 #include "message.h"
24
25 #include <QEvent>
26
27 class ProcessBufferEvent : public QEvent {
28 public:
29   inline ProcessBufferEvent() : QEvent(QEvent::User) {}
30 };
31
32 MessageModel::MessageModel(QObject *parent)
33   : QAbstractItemModel(parent)
34 {
35 }
36
37 QVariant MessageModel::data(const QModelIndex &index, int role) const {
38   int row = index.row(); int column = index.column();
39   if(row < 0 || row >= _messageList.count() || column < 0)
40     return QVariant();
41
42   if(role == ColumnTypeRole)
43     return column;
44
45   return _messageList[row]->data(index.column(), role);
46 }
47
48 bool MessageModel::setData(const QModelIndex &index, const QVariant &value, int role) {
49   int row = index.row();
50   if(row < 0 || row >= _messageList.count())
51     return false;
52
53   if(_messageList[row]->setData(index.column(), value, role)) {
54     emit dataChanged(index, index);
55     return true;
56   }
57
58   return false;
59 }
60
61
62
63 bool MessageModel::insertMessage(const Message &msg, bool fakeMsg) {
64   MsgId id = msg.msgId();
65   int idx = indexForId(id);
66   if(!fakeMsg && idx < _messageList.count()) { // check for duplicate
67     if(_messageList[idx]->msgId() == id)
68       return false;
69   }
70
71   MessageModelItem *item = createMessageModelItem(msg);
72   beginInsertRows(QModelIndex(), idx, idx);
73   _messageList.insert(idx, item);
74   endInsertRows();
75   return true;
76 }
77
78 void MessageModel::insertMessages(const QList<Message> &msglist) {
79   if(msglist.isEmpty())
80     return;
81
82 //   if(_messageList.isEmpty()) {
83 //     insertMessageGroup(msglist);
84 //   } else {
85     int processedMsgs = insertMessagesGracefully(msglist);
86     int remainingMsgs = msglist.count() - processedMsgs;
87     if(remainingMsgs > 0) {
88       if(msglist.first().msgId() < msglist.last().msgId()) {
89         // in Order
90         _messageBuffer << msglist.mid(0, remainingMsgs);
91       } else {
92         _messageBuffer << msglist.mid(processedMsgs);
93       }
94       qSort(_messageBuffer);
95       QCoreApplication::postEvent(this, new ProcessBufferEvent());
96     }
97 //   }
98 }
99
100 void MessageModel::insertMessageGroup(const QList<Message> &msglist) {
101   int idx = indexForId(msglist.first().msgId());
102   if(idx > 0) {
103     int prevIdx = idx - 1;
104     if(_messageList[prevIdx]->msgType() == Message::DayChange
105        && _messageList[prevIdx]->timeStamp() > msglist.value(0).timestamp()) {
106       beginRemoveRows(QModelIndex(), prevIdx, prevIdx);
107       MessageModelItem *oldItem = _messageList.takeAt(prevIdx);
108       delete oldItem;
109       endRemoveRows();
110       idx--;
111     }
112   }
113   beginInsertRows(QModelIndex(), idx, idx+msglist.count()-1);
114   foreach(Message msg, msglist) {
115     _messageList.insert(idx, createMessageModelItem(msg));
116     idx++;
117   }
118   endInsertRows();
119 }
120
121 int MessageModel::insertMessagesGracefully(const QList<Message> &msglist) {
122   bool inOrder = (msglist.first().msgId() < msglist.last().msgId());
123   // depending on the order we have to traverse from the front to the back or vice versa
124
125   QList<Message> grouplist;
126   MsgId id;
127   MsgId dupeId;
128   int dupeCount = 0;
129   bool fastForward = false;
130   QList<Message>::const_iterator iter;
131   if(inOrder) {
132     iter = msglist.constEnd();
133     iter--; // this op is safe as we've allready passed an empty check
134   } else {
135     iter = msglist.constBegin();
136   }
137
138   int idx = indexForId((*iter).msgId());
139   if(idx >= 0 && !_messageList.isEmpty())
140     dupeId = _messageList[idx]->msgId();
141
142   // we always compare to the previous entry...
143   // if there isn't, we can fastforward to the top
144   if(idx - 1 >= 0)
145     id = _messageList[idx - 1]->msgId();
146   else
147     fastForward = true;
148
149   if((*iter).msgId() != dupeId)
150     grouplist << *iter;
151   else
152     dupeCount++;
153
154   if(!inOrder)
155     iter++;
156
157   if(inOrder) {
158     while(iter != msglist.constBegin()) {
159       iter--;
160
161       if(!fastForward && (*iter).msgId() < id)
162         break;
163
164       if((*iter).msgId() != dupeId) {
165         if(!grouplist.isEmpty()) {
166           QDateTime nextTs = grouplist.value(0).timestamp();
167           QDateTime prevTs = (*iter).timestamp();
168           nextTs.setTimeSpec(Qt::UTC);
169           prevTs.setTimeSpec(Qt::UTC);
170           uint nextDay = nextTs.toTime_t() / 86400;
171           uint prevDay = prevTs.toTime_t() / 86400;
172           if(nextDay != prevDay) {
173             nextTs.setTime_t(nextDay * 86400);
174             nextTs.setTimeSpec(Qt::LocalTime);
175             Message dayChangeMsg = Message::ChangeOfDay(nextTs);
176             dayChangeMsg.setMsgId((*iter).msgId());
177             grouplist.prepend(dayChangeMsg);
178             dupeCount--;
179           }
180         }
181         grouplist.prepend(*iter);
182       } else {
183         dupeCount++;
184       }
185     }
186   } else {
187     while(iter != msglist.constEnd()) {
188       if(!fastForward && (*iter).msgId() < id)
189         break;
190
191       if((*iter).msgId() != dupeId) {
192         if(!grouplist.isEmpty()) {
193           qWarning() << "copy day change check";
194         }
195         grouplist.prepend(*iter);
196       } else {
197         dupeCount++;
198       }
199
200       iter++;
201     }
202   }
203
204   insertMessageGroup(grouplist);
205   return grouplist.count() + dupeCount;
206 }
207
208 void MessageModel::customEvent(QEvent *event) {
209   if(event->type() != QEvent::User)
210     return;
211
212   event->accept();
213
214   if(_messageBuffer.isEmpty())
215     return;
216
217   int processedMsgs = insertMessagesGracefully(_messageBuffer);
218   int remainingMsgs = _messageBuffer.count() - processedMsgs;
219
220   QList<Message>::iterator removeStart = _messageBuffer.begin() + remainingMsgs;
221   QList<Message>::iterator removeEnd = _messageBuffer.end();
222   _messageBuffer.erase(removeStart, removeEnd);
223
224   if(!_messageBuffer.isEmpty())
225     QCoreApplication::postEvent(this, new ProcessBufferEvent());
226 }
227
228 void MessageModel::clear() {
229   beginRemoveRows(QModelIndex(), 0, rowCount() - 1);
230   qDeleteAll(_messageList);
231   _messageList.clear();
232   endRemoveRows();
233 }
234
235
236
237 // returns index of msg with given Id or of the next message after that (i.e., the index where we'd insert this msg)
238 int MessageModel::indexForId(MsgId id) {
239   if(_messageList.isEmpty() || id <= _messageList.value(0)->msgId())
240     return 0;
241   if(id > _messageList.last()->msgId())
242     return _messageList.count();
243
244   // binary search
245   int start = 0; int end = _messageList.count()-1;
246   while(1) {
247     if(end - start == 1)
248       return end;
249     int pivot = (end + start) / 2;
250     if(id <= _messageList.value(pivot)->msgId()) end = pivot;
251     else start = pivot;
252   }
253 }
254
255 /**********************************************************************************/
256
257 MessageModelItem::MessageModelItem(const Message &msg) :
258   _timestamp(msg.timestamp()),
259   _msgId(msg.msgId()),
260   _bufferId(msg.bufferInfo().bufferId()),
261   _type(msg.type()),
262   _flags(msg.flags())
263 {
264 }
265
266 QVariant MessageModelItem::data(int column, int role) const {
267   if(column < MessageModel::TimestampColumn || column > MessageModel::ContentsColumn)
268     return QVariant();
269
270   switch(role) {
271   case MessageModel::MsgIdRole: return QVariant::fromValue<MsgId>(_msgId);
272   case MessageModel::BufferIdRole: return QVariant::fromValue<BufferId>(_bufferId);
273   case MessageModel::TypeRole: return _type;
274   case MessageModel::FlagsRole: return (int)_flags;
275   case MessageModel::TimestampRole: return _timestamp;
276   default: return QVariant();
277   }
278 }
279
280
281 // Stuff for later
282 bool MessageModelItem::lessThan(const MessageModelItem *m1, const MessageModelItem *m2){
283   return (*m1) < (*m2);
284 }
285
286 bool MessageModelItem::operator<(const MessageModelItem &other) const {
287   return _msgId < other._msgId;
288 }
289
290 bool MessageModelItem::operator==(const MessageModelItem &other) const {
291   return _msgId == other._msgId;
292 }
293
294 bool MessageModelItem::operator>(const MessageModelItem &other) const {
295   return _msgId > other._msgId;
296 }