Sanitize topic message
[quassel.git] / src / qtui / bufferwidget.cpp
index dbeb571..d632420 100644 (file)
@@ -1,11 +1,11 @@
 /***************************************************************************
- *   Copyright (C) 2005-07 by The Quassel Team                             *
+ *   Copyright (C) 2005-2013 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) any later version.                                   *
+ *   (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        *
  *   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.,                                       *
- *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
+ *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
  ***************************************************************************/
 
+#include <QLayout>
+#include <QKeyEvent>
+#include <QMenu>
+#include <QScrollBar>
+
+#include "action.h"
+#include "actioncollection.h"
 #include "bufferwidget.h"
-#include "buffer.h"
 #include "chatline.h"
-#include "chatwidget.h"
+#include "chatview.h"
+#include "chatviewsearchbar.h"
+#include "chatviewsearchcontroller.h"
+#include "chatviewsettings.h"
+#include "client.h"
+#include "iconloader.h"
+#include "multilineedit.h"
+#include "qtui.h"
 #include "settings.h"
 
-BufferWidget::BufferWidget(QWidget *parent) : QWidget(parent) {
-  ui.setupUi(this);
+BufferWidget::BufferWidget(QWidget *parent)
+    : AbstractBufferContainer(parent),
+    _chatViewSearchController(new ChatViewSearchController(this)),
+    _autoMarkerLine(true)
+{
+    ui.setupUi(this);
+    layout()->setContentsMargins(0, 0, 0, 0);
+    layout()->setSpacing(0);
+    // ui.searchBar->hide();
 
-  curBuf = 0;
-  //setBaseSize(QSize(600,400));
-  //setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
-  connect(ui.inputEdit, SIGNAL(returnPressed()), this, SLOT(enterPressed()));
-  connect(this, SIGNAL(nickListUpdated(QStringList)), ui.inputEdit, SLOT(updateNickList(QStringList)));
+    _chatViewSearchController->setCaseSensitive(ui.searchBar->caseSensitiveBox()->isChecked());
+    _chatViewSearchController->setSearchSenders(ui.searchBar->searchSendersBox()->isChecked());
+    _chatViewSearchController->setSearchMsgs(ui.searchBar->searchMsgsBox()->isChecked());
+    _chatViewSearchController->setSearchOnlyRegularMsgs(ui.searchBar->searchOnlyRegularMsgsBox()->isChecked());
 
-}
+    connect(ui.searchBar, SIGNAL(searchChanged(const QString &)),
+        _chatViewSearchController, SLOT(setSearchString(const QString &)));
+    connect(ui.searchBar->caseSensitiveBox(), SIGNAL(toggled(bool)),
+        _chatViewSearchController, SLOT(setCaseSensitive(bool)));
+    connect(ui.searchBar->searchSendersBox(), SIGNAL(toggled(bool)),
+        _chatViewSearchController, SLOT(setSearchSenders(bool)));
+    connect(ui.searchBar->searchMsgsBox(), SIGNAL(toggled(bool)),
+        _chatViewSearchController, SLOT(setSearchMsgs(bool)));
+    connect(ui.searchBar->searchOnlyRegularMsgsBox(), SIGNAL(toggled(bool)),
+        _chatViewSearchController, SLOT(setSearchOnlyRegularMsgs(bool)));
+    connect(ui.searchBar->searchUpButton(), SIGNAL(clicked()),
+        _chatViewSearchController, SLOT(highlightPrev()));
+    connect(ui.searchBar->searchDownButton(), SIGNAL(clicked()),
+        _chatViewSearchController, SLOT(highlightNext()));
 
-void BufferWidget::init() {
+    connect(ui.searchBar, SIGNAL(hidden()), this, SLOT(setFocus()));
 
-}
+    connect(_chatViewSearchController, SIGNAL(newCurrentHighlight(QGraphicsItem *)),
+        this, SLOT(scrollToHighlight(QGraphicsItem *)));
+
+    ActionCollection *coll = QtUi::actionCollection();
+
+    Action *zoomInChatview = coll->add<Action>("ZoomInChatView", this, SLOT(zoomIn()));
+    zoomInChatview->setText(tr("Zoom In"));
+    zoomInChatview->setIcon(SmallIcon("zoom-in"));
+    zoomInChatview->setShortcut(QKeySequence::ZoomIn);
+
+    Action *zoomOutChatview = coll->add<Action>("ZoomOutChatView", this, SLOT(zoomOut()));
+    zoomOutChatview->setIcon(SmallIcon("zoom-out"));
+    zoomOutChatview->setText(tr("Zoom Out"));
+    zoomOutChatview->setShortcut(QKeySequence::ZoomOut);
 
-BufferWidget::~BufferWidget() {
-  foreach(BufferState *s, states.values()) {
-    delete s;
-  }
+    Action *zoomOriginalChatview = coll->add<Action>("ZoomOriginalChatView", this, SLOT(zoomOriginal()));
+    zoomOriginalChatview->setIcon(SmallIcon("zoom-original"));
+    zoomOriginalChatview->setText(tr("Actual Size"));
+    //zoomOriginalChatview->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0)); // used for RTS switching
+
+    Action *setMarkerLine = coll->add<Action>("SetMarkerLineToBottom", this, SLOT(setMarkerLine()));
+    setMarkerLine->setText(tr("Set Marker Line"));
+    setMarkerLine->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_R));
+
+    Action *jumpToMarkerLine = QtUi::actionCollection("Navigation")->add<Action>("JumpToMarkerLine", this, SLOT(jumpToMarkerLine()));
+    jumpToMarkerLine->setText(tr("Go to Marker Line"));
+    jumpToMarkerLine->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_K));
+
+    ChatViewSettings s;
+    s.initAndNotify("AutoMarkerLine", this, SLOT(setAutoMarkerLine(QVariant)), true);
 }
 
-void BufferWidget::setBuffer(Buffer *buf) {
-  BufferState *state;
-  curBuf = buf;
-  if(states.contains(buf)) {
-    state = states[buf];
-  } else {
-    BufferState *s = new BufferState;
-    s->currentLine = Settings::guiValue(QString("BufferStates/%1/%2/currentLine").arg(buf->networkName()).arg(buf->bufferName()), -1).toInt();
-    if(buf->bufferType() == Buffer::ChannelType) {
-      s->splitterState = Settings::guiValue(QString("BufferStates/%1/%2/splitter").arg(buf->networkName()).arg(buf->bufferName())).toByteArray();
-      s->splitter = new QSplitter(this);
-      s->chatWidget = new ChatWidget(s->splitter);
-      s->nickTree = new QTreeWidget(s->splitter);
-      s->nickTree->headerItem()->setHidden(true);
-      s->nickTree->setRootIsDecorated(false);
-      s->page = s->splitter;
-      s->ownNick = buf->ownNick();
-      s->topic = buf->topic();
-      updateNickList(s, buf->nickList());
-      s->splitter->restoreState(s->splitterState);
-      connect(buf, SIGNAL(nickListChanged(QVariantMap)), this, SLOT(updateNickList(QVariantMap)));
-      connect(s->nickTree, SIGNAL(itemExpanded(QTreeWidgetItem *)), this, SLOT(itemExpansionChanged(QTreeWidgetItem*)));
-      connect(s->nickTree, SIGNAL(itemCollapsed(QTreeWidgetItem *)), this, SLOT(itemExpansionChanged(QTreeWidgetItem*)));
-    } else {
-      s->splitter = 0; s->nickTree = 0;
-      s->chatWidget = new ChatWidget(this);
-      s->page = s->chatWidget;
-      s->ownNick = buf->ownNick();
-      s->topic = buf->bufferName();
-    }
-    s->opsExpanded = Settings::guiValue(QString("BufferStates/%1/%2/opsExpanded").arg(buf->networkName()).arg(buf->bufferName()), true).toBool();
-    s->voicedExpanded = Settings::guiValue(QString("BufferStates/%1/%2/voicedExpanded").arg(buf->networkName()).arg(buf->bufferName()), true).toBool();
-    s->usersExpanded = Settings::guiValue(QString("BufferStates/%1/%2/usersExpanded").arg(buf->networkName()).arg(buf->bufferName()), true).toBool();
-    states[buf] = s;
-    state = s;
-    state->chatWidget->init(networkName, bufferName);
-    QList<ChatLine *> lines;
-    QList<AbstractUiMsg *> msgs = buf->contents();
-    foreach(AbstractUiMsg *msg, msgs) {
-      lines.append(dynamic_cast<ChatLine*>(msg));
-    }
-    state->chatWidget->setContents(lines);
-    connect(buf, SIGNAL(msgAppended(AbstractUiMsg *)), state->chatWidget, SLOT(appendMsg(AbstractUiMsg *)));
-    connect(buf, SIGNAL(msgPrepended(AbstractUiMsg *)), state->chatWidget, SLOT(prependMsg(AbstractUiMsg *)));
-    connect(buf, SIGNAL(topicSet(QString)), this, SLOT(setTopic(QString)));
-    connect(buf, SIGNAL(ownNickSet(QString)), this, SLOT(setOwnNick(QString)));
-    ui.stackedWidget->addWidget(s->page);
-  }
-  ui.stackedWidget->setCurrentWidget(state->page);
-  ui.topicEdit->setText(buf->topic());
-  chatWidget = state->chatWidget;
-  nickTree = state->nickTree;
-  splitter = state->splitter;
-  //ui.ownNick->set
-  disconnect(this, SIGNAL(userInput(QString)), 0, 0);
-  connect(this, SIGNAL(userInput(QString)), buf, SLOT(processUserInput(QString)));
-  state->chatWidget->setFocusProxy(ui.inputEdit);
-  ui.inputEdit->setFocus();
-  ui.topicEdit->setText(state->topic);
-  ui.ownNick->clear();  // TODO add nick history
-  ui.ownNick->addItem(state->ownNick);
-  updateTitle();
+
+BufferWidget::~BufferWidget()
+{
+    delete _chatViewSearchController;
+    _chatViewSearchController = 0;
 }
 
-void BufferWidget::saveState() {
-  foreach(Buffer *buf, states.keys()) {
-    BufferState *s = states[buf];
-    if(s->splitter) Settings::setGuiValue(QString("BufferStates/%1/%2/splitter").arg(buf->networkName()).arg(buf->bufferName()), s->splitter->saveState());
-    Settings::setGuiValue(QString("BufferStates/%1/%2/currentLine").arg(buf->networkName()).arg(buf->bufferName()), s->currentLine);
-    Settings::setGuiValue(QString("BufferStates/%1/%2/opsExpanded").arg(buf->networkName()).arg(buf->bufferName()), s->opsExpanded);
-    Settings::setGuiValue(QString("BufferStates/%1/%2/voicedExpanded").arg(buf->networkName()).arg(buf->bufferName()), s->voicedExpanded);
-    Settings::setGuiValue(QString("BufferStates/%1/%2/usersExpanded").arg(buf->networkName()).arg(buf->bufferName()), s->usersExpanded);
-  }
+
+void BufferWidget::setAutoMarkerLine(const QVariant &v)
+{
+    _autoMarkerLine = v.toBool();
 }
 
-QSize BufferWidget::sizeHint() const {
-  return QSize(800,400);
+
+AbstractChatView *BufferWidget::createChatView(BufferId id)
+{
+    ChatView *chatView;
+    chatView = new ChatView(id, this);
+    chatView->setBufferContainer(this);
+    _chatViews[id] = chatView;
+    ui.stackedWidget->addWidget(chatView);
+    chatView->setFocusProxy(this);
+    return chatView;
 }
 
-void BufferWidget::updateTitle() {
-  QString title = QString("%1 in %2 [%3]: %4").arg(ui.ownNick->currentText()).arg(bufferName).arg(networkName).arg(ui.topicEdit->text());
-  setWindowTitle(title);
+
+void BufferWidget::removeChatView(BufferId id)
+{
+    QWidget *view = _chatViews.value(id, 0);
+    if (!view) return;
+    ui.stackedWidget->removeWidget(view);
+    view->deleteLater();
+    _chatViews.take(id);
 }
 
-void BufferWidget::enterPressed() {
-  QStringList lines = ui.inputEdit->text().split('\n', QString::SkipEmptyParts);
-  foreach(QString msg, lines) {
-    if(msg.isEmpty()) continue;
-    emit userInput(msg);
-  }
-  ui.inputEdit->clear();
+
+void BufferWidget::showChatView(BufferId id)
+{
+    if (!id.isValid()) {
+        ui.stackedWidget->setCurrentWidget(ui.page);
+    }
+    else {
+        ChatView *view = qobject_cast<ChatView *>(_chatViews.value(id));
+        Q_ASSERT(view);
+        ui.stackedWidget->setCurrentWidget(view);
+        _chatViewSearchController->setScene(view->scene());
+    }
 }
 
-void BufferWidget::setActive(bool act) {
-  if(act != active) {
-    active = act;
-    //renderContents();
-    //scrollToEnd();
-  }
+
+void BufferWidget::scrollToHighlight(QGraphicsItem *highlightItem)
+{
+    ChatView *view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+    if (view) {
+        view->centerOn(highlightItem);
+    }
 }
 
-void BufferWidget::resizeEvent ( QResizeEvent * event ) {
-  //qDebug() << "resizing:" << bufferName << event->size();
-  QWidget::resizeEvent(event);
 
+void BufferWidget::zoomIn()
+{
+    ChatView *view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+    if (view)
+        view->zoomIn();
 }
 
-/*
-void BufferWidget::displayMsg(Message msg) {
-  chatWidget->appendMsg(msg);
+
+void BufferWidget::zoomOut()
+{
+    ChatView *view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+    if (view)
+        view->zoomOut();
 }
-*/
-
-void BufferWidget::setOwnNick(QString nick) {
-  Buffer *buf = qobject_cast<Buffer*>(sender());
-  Q_ASSERT(buf);
-  states[buf]->ownNick = nick;
-  if(buf == curBuf) {
-    ui.ownNick->clear();
-    ui.ownNick->addItem(nick);
-    updateTitle();
-  }
+
+
+void BufferWidget::zoomOriginal()
+{
+    ChatView *view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+    if (view)
+        view->zoomOriginal();
 }
 
-void BufferWidget::setTopic(QString topic) {
-  Buffer *buf = qobject_cast<Buffer*>(sender());
-  Q_ASSERT(buf);
-  states[buf]->topic = topic;
-  if(buf == curBuf) {
-    ui.topicEdit->setText(topic);
-    updateTitle();
-  }
+
+void BufferWidget::addActionsToMenu(QMenu *menu, const QPointF &pos)
+{
+    Q_UNUSED(pos);
+    ActionCollection *coll = QtUi::actionCollection();
+    menu->addSeparator();
+    menu->addAction(coll->action("ZoomInChatView"));
+    menu->addAction(coll->action("ZoomOutChatView"));
+    menu->addAction(coll->action("ZoomOriginalChatView"));
 }
 
 
-void BufferWidget::updateNickList(QVariantMap nicks) {
-  Buffer *buf = qobject_cast<Buffer*>(sender());
-  Q_ASSERT(buf);
-  updateNickList(states[buf], nicks);
+bool BufferWidget::eventFilter(QObject *watched, QEvent *event)
+{
+    if (event->type() != QEvent::KeyPress)
+        return false;
+
+    QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
+
+    MultiLineEdit *inputLine = qobject_cast<MultiLineEdit *>(watched);
+    if (!inputLine)
+        return false;
+
+    // Intercept copy key presses
+    if (keyEvent == QKeySequence::Copy) {
+        if (inputLine->hasSelectedText())
+            return false;
+        ChatView *view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+        if (view)
+            view->scene()->selectionToClipboard();
+        return true;
+    }
+
+    // We don't want to steal cursor movement keys if the input line is in multiline mode
+    if (!inputLine->isSingleLine())
+        return false;
+
+    switch (keyEvent->key()) {
+    case Qt::Key_Up:
+    case Qt::Key_Down:
+        if (!(keyEvent->modifiers() & Qt::ShiftModifier))
+            return false;
+    case Qt::Key_PageUp:
+    case Qt::Key_PageDown:
+        // static cast to access public qobject::event
+        return static_cast<QObject *>(ui.stackedWidget->currentWidget())->event(event);
+    default:
+        return false;
+    }
 }
 
-// TODO Use 005
-void BufferWidget::updateNickList(BufferState *state, QVariantMap nicks) {
-  emit nickListUpdated(nicks.keys());
-  QTreeWidget *tree = state->nickTree;
-  if(!tree) return;
-  tree->clear();
-  if(nicks.count() != 1) tree->setHeaderLabel(tr("%1 Users").arg(nicks.count()));
-  else tree->setHeaderLabel(tr("1 User"));
-  QTreeWidgetItem *ops = new QTreeWidgetItem();
-  QTreeWidgetItem *voiced = new QTreeWidgetItem();
-  QTreeWidgetItem *users = new QTreeWidgetItem();
-  // To sort case-insensitive, we have to put all nicks in a map which is sorted by (lowercase) key...
-  QMap<QString, QString> sorted;
-  foreach(QString n, nicks.keys()) { sorted[n.toLower()] = n; }
-  foreach(QString n, sorted.keys()) {
-    QString nick = sorted[n];
-    QString mode = nicks[nick].toMap()["Channels"].toMap()[bufferName].toMap()["Mode"].toString();
-    if(mode.contains('o')) { new QTreeWidgetItem(ops, QStringList(QString("@%1").arg(nick))); }
-    else if(mode.contains('v')) { new QTreeWidgetItem(voiced, QStringList(QString("+%1").arg(nick))); }
-    else new QTreeWidgetItem(users, QStringList(nick));
-  }
-  if(ops->childCount()) {
-    ops->setText(0, tr("%1 Operators").arg(ops->childCount()));
-    tree->addTopLevelItem(ops);
-    ops->setExpanded(state->opsExpanded);
-  } else delete ops;
-  if(voiced->childCount()) {
-    voiced->setText(0, tr("%1 Voiced").arg(voiced->childCount()));
-    tree->addTopLevelItem(voiced);
-    voiced->setExpanded(state->voicedExpanded);
-  } else delete voiced;
-  if(users->childCount()) {
-    users->setText(0, tr("%1 Users").arg(users->childCount()));
-    tree->addTopLevelItem(users);
-    users->setExpanded(state->usersExpanded);
-  } else delete users;
+
+void BufferWidget::currentChanged(const QModelIndex &current, const QModelIndex &previous)
+{
+    ChatView *prevView = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+
+    AbstractBufferContainer::currentChanged(current, previous); // switch first to avoid a redraw
+
+    // we need to hide the marker line if it's already/still at the bottom of the view (and not scrolled up)
+    ChatView *curView = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+    if (curView) {
+        BufferId curBufferId = current.data(NetworkModel::BufferIdRole).value<BufferId>();
+        if (curBufferId.isValid()) {
+            MsgId markerMsgId = Client::networkModel()->markerLineMsgId(curBufferId);
+            if (markerMsgId == curView->lastMsgId() && markerMsgId == curView->lastVisibleMsgId())
+                curView->setMarkerLineVisible(false);
+            else
+                curView->setMarkerLineVisible(true);
+        }
+    }
+
+    if (prevView && autoMarkerLine())
+        setMarkerLine(prevView, false);
 }
 
-// TODO Use 005 and additional user modes
-void BufferWidget::itemExpansionChanged(QTreeWidgetItem *item) {
-  if(item->child(0)->text(0).startsWith('@')) states[curBuf]->opsExpanded = item->isExpanded();
-  else if(item->child(0)->text(0).startsWith('+')) states[curBuf]->voicedExpanded = item->isExpanded();
-  else states[curBuf]->usersExpanded = item->isExpanded();
+
+void BufferWidget::setMarkerLine(ChatView *view, bool allowGoingBack)
+{
+    if (!view)
+        view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+    if (!view)
+        return;
+
+    ChatLine *lastLine = view->lastVisibleChatLine();
+    if (lastLine) {
+        QModelIndex idx = lastLine->index();
+        MsgId msgId = idx.data(MessageModel::MsgIdRole).value<MsgId>();
+
+        if (!allowGoingBack) {
+            BufferId bufId = view->scene()->singleBufferId();
+            MsgId oldMsgId = Client::markerLine(bufId);
+            if (oldMsgId.isValid() && msgId <= oldMsgId)
+                return;
+        }
+        view->setMarkerLine(msgId);
+    }
 }
 
+
+void BufferWidget::jumpToMarkerLine(ChatView *view, bool requestBacklog)
+{
+    if (!view)
+        view = qobject_cast<ChatView *>(ui.stackedWidget->currentWidget());
+    if (!view)
+        return;
+
+    view->jumpToMarkerLine(requestBacklog);
+}