Fixing selections, also prevent from crashing in some circumstances
[quassel.git] / src / qtui / chatscene.cpp
index 8207248..8f36e1d 100644 (file)
@@ -45,6 +45,7 @@ ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, QObject
   connect(this, SIGNAL(sceneRectChanged(const QRectF &)), this, SLOT(rectChanged(const QRectF &)));
 
   connect(model, SIGNAL(rowsInserted(const QModelIndex &, int, int)), this, SLOT(rowsInserted(const QModelIndex &, int, int)));
+  connect(model, SIGNAL(modelAboutToBeReset()), this, SLOT(modelReset()));
   for(int i = 0; i < model->rowCount(); i++) {
     ChatLine *line = new ChatLine(model->index(i, 0));
     _lines.append(line);
@@ -76,7 +77,6 @@ ChatScene::ChatScene(QAbstractItemModel *model, const QString &idString, QObject
 
 ChatScene::~ChatScene() {
 
-
 }
 
 void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
@@ -106,6 +106,15 @@ void ChatScene::rowsInserted(const QModelIndex &index, int start, int end) {
   }
 }
 
+void ChatScene::modelReset() {
+  foreach(ChatLine *line, _lines) {
+    removeItem(line);
+    delete line;
+  }
+  _lines.clear();
+  setSceneRect(QRectF(0, 0, _width, 0));
+}
+
 void ChatScene::setWidth(qreal w) {
   _width = w;
   _height = 0;
@@ -243,9 +252,15 @@ void ChatScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
 //!\brief Convert current selection to human-readable string.
 QString ChatScene::selectionToString() const {
   //TODO Make selection format configurable!
-  if(!_isSelecting) return "";
+  if(!_isSelecting) return QString();
+  int start = qMin(_selectionStart, _selectionEnd);
+  int end = qMax(_selectionStart, _selectionEnd);
+  if(start < 0 || end >= _lines.count()) {
+    qDebug() << "Invalid selection range:" << start << end;
+    return QString();
+  }
   QString result;
-  for(int l = _selectionStart; l <= _selectionEnd; l++) {
+  for(int l = start; l <= end; l++) {
     if(_selectionMinCol == ChatLineModel::TimestampColumn)
       result += _lines[l]->item(ChatLineModel::TimestampColumn)->data(MessageModel::DisplayRole).toString() + " ";
     if(_selectionMinCol <= ChatLineModel::SenderColumn)