Removing the new chatwidget and other cruft from trunk (which is now our 0.2 branch)
[quassel.git] / src / uisupport / bufferview.cpp
1 /***************************************************************************
2  *   Copyright (C) 2005-08 by the Quassel Project                          *
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 "client.h"
22 #include "buffersyncer.h"
23 #include "bufferview.h"
24 #include "networkmodel.h"
25 #include "network.h"
26
27 #include "uisettings.h"
28
29 #include "global.h"
30
31 /*****************************************
32 * The TreeView showing the Buffers
33 *****************************************/
34 // Please be carefull when reimplementing methods which are used to inform the view about changes to the data
35 // to be on the safe side: call QTreeView's method aswell
36 BufferView::BufferView(QWidget *parent) : QTreeView(parent) {
37   setContextMenuPolicy(Qt::CustomContextMenu);
38
39   connect(this, SIGNAL(customContextMenuRequested(const QPoint &)),
40           this, SLOT(showContextMenu(const QPoint &)));
41 }
42
43 void BufferView::init() {
44   setIndentation(10);
45   header()->setContextMenuPolicy(Qt::ActionsContextMenu);
46   hideColumn(1);
47   hideColumn(2);
48   expandAll();
49
50   setAnimated(true);
51
52 #ifndef QT_NO_DRAGANDDROP
53   setDragEnabled(true);
54   setAcceptDrops(true);
55   setDropIndicatorShown(true);
56 #endif
57
58   setSortingEnabled(true);
59   sortByColumn(0, Qt::AscendingOrder);
60 #ifndef Q_WS_QWS
61   // this is a workaround to not join channels automatically... we need a saner way to navigate for qtopia anyway though,
62   // such as mark first, activate at second click...
63   connect(this, SIGNAL(activated(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));
64 #else
65   connect(this, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(joinChannel(QModelIndex)));  // Qtopia uses single click for activation
66 #endif
67 }
68
69 void BufferView::setFilteredModel(QAbstractItemModel *model, BufferViewFilter::Modes mode, QList<NetworkId> nets) {
70   BufferViewFilter *filter = new BufferViewFilter(model, mode, nets);
71   setModel(filter);
72   connect(this, SIGNAL(removeBuffer(const QModelIndex &)), filter, SLOT(removeBuffer(const QModelIndex &)));
73 }
74
75 void BufferView::setModel(QAbstractItemModel *model) {
76   delete selectionModel();
77   QTreeView::setModel(model);
78   init();
79
80   // remove old Actions
81   QList<QAction *> oldactions = header()->actions();
82   foreach(QAction *action, oldactions) {
83     header()->removeAction(action);
84     action->deleteLater();
85   }
86
87   QString sectionName;
88   QAction *showSection;
89   for(int i = 1; i < model->columnCount(); i++) {
90     sectionName = (model->headerData(i, Qt::Horizontal, Qt::DisplayRole)).toString();
91     showSection = new QAction(sectionName, header());
92     showSection->setCheckable(true);
93     showSection->setChecked(!isColumnHidden(i));
94     showSection->setProperty("column", i);
95     connect(showSection, SIGNAL(toggled(bool)), this, SLOT(toggleHeader(bool)));
96     header()->addAction(showSection);
97   }
98   
99 }
100
101 void BufferView::joinChannel(const QModelIndex &index) {
102   BufferInfo::Type bufferType = (BufferInfo::Type)index.data(NetworkModel::BufferTypeRole).value<int>();
103
104   if(bufferType != BufferInfo::ChannelBuffer)
105     return;
106
107   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
108   
109   Client::userInput(bufferInfo, QString("/JOIN %1").arg(bufferInfo.bufferName()));
110 }
111
112 void BufferView::keyPressEvent(QKeyEvent *event) {
113   if(event->key() == Qt::Key_Backspace || event->key() == Qt::Key_Delete) {
114     event->accept();
115     QModelIndex index = selectionModel()->selectedIndexes().first();
116     if(index.isValid()) {
117       emit removeBuffer(index);
118     }
119   }
120   QTreeView::keyPressEvent(event);
121 }
122
123 // ensure that newly inserted network nodes are expanded per default
124 void BufferView::rowsInserted(const QModelIndex & parent, int start, int end) {
125   QTreeView::rowsInserted(parent, start, end);
126   if(model()->rowCount(parent) == 1 && parent.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType
127      && parent.data(NetworkModel::ItemActiveRole) == true) {
128     // without updating the parent the expand will have no effect... Qt Bug?
129     update(parent);
130     expand(parent);
131   }
132 }
133
134 void BufferView::dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) {
135   QTreeView::dataChanged(topLeft, bottomRight);
136   
137   // determine how many items have been changed and if any of them is a networkitem
138   // which just swichted from active to inactive or vice versa
139   if(topLeft.data(NetworkModel::ItemTypeRole) != NetworkModel::NetworkItemType)
140     return;
141
142   for(int i = topLeft.row(); i <= bottomRight.row(); i++) {
143     QModelIndex networkIdx = topLeft.sibling(topLeft.row(), 0);
144     if(model()->rowCount(networkIdx) == 0)
145       continue;
146
147     bool isActive = networkIdx.data(NetworkModel::ItemActiveRole).toBool();
148     if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, isActive);
149   }
150 }
151
152
153 void BufferView::toggleHeader(bool checked) {
154   QAction *action = qobject_cast<QAction *>(sender());
155   header()->setSectionHidden((action->property("column")).toInt(), !checked);
156 }
157
158 void BufferView::showContextMenu(const QPoint &pos) {
159   QModelIndex index = indexAt(pos);
160   if(!index.isValid()) return;
161   QMenu contextMenu(this);
162   QAction *connectNetAction = new QAction(tr("Connect"), this);
163   QAction *disconnectNetAction = new QAction(tr("Disconnect"), this);
164   QAction *joinChannelAction = new QAction(tr("Join Channel"), this);
165
166   QAction *joinBufferAction = new QAction(tr("Join"), this);
167   QAction *partBufferAction = new QAction(tr("Part"), this);
168   QAction *removeBufferAction = new QAction(tr("Delete buffer"), this);
169
170   QMenu *hideEventsMenu = new QMenu(tr("Hide Events"), this);
171   QAction *hideJoinAction = hideEventsMenu->addAction(tr("Join Events"));
172   QAction *hidePartAction = hideEventsMenu->addAction(tr("Part Events"));
173   QAction *hideKillAction = hideEventsMenu->addAction(tr("Kill Events"));
174   QAction *hideQuitAction = hideEventsMenu->addAction(tr("Quit Events"));
175   QAction *hideModeAction = hideEventsMenu->addAction(tr("Mode Events"));
176   hideJoinAction->setCheckable(true);
177   hidePartAction->setCheckable(true);
178   hideKillAction->setCheckable(true);
179   hideQuitAction->setCheckable(true);
180   hideModeAction->setCheckable(true);
181   hideJoinAction->setEnabled(false);
182   hidePartAction->setEnabled(false);
183   hideKillAction->setEnabled(false);
184   hideQuitAction->setEnabled(false);
185   hideModeAction->setEnabled(false);
186
187   QAction *ignoreListAction = new QAction(tr("Ignore list"), this);
188   ignoreListAction->setEnabled(false);
189   QAction *whoBufferAction = new QAction(tr("WHO"), this);
190
191   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType) {
192     if(index.data(NetworkModel::ItemActiveRole).toBool()) {
193       contextMenu.addAction(disconnectNetAction);
194       contextMenu.addSeparator();
195       contextMenu.addAction(joinChannelAction);
196     } else {
197       contextMenu.addAction(connectNetAction);
198     }
199   }
200
201   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
202   QString channelname = index.sibling(index.row(), 0).data().toString();
203
204   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType) {
205     if(bufferInfo.type() != BufferInfo::ChannelBuffer && bufferInfo.type() != BufferInfo::QueryBuffer) return;
206     contextMenu.addAction(joinBufferAction);
207     contextMenu.addAction(partBufferAction);
208     contextMenu.addAction(removeBufferAction);
209     contextMenu.addMenu(hideEventsMenu);
210     contextMenu.addAction(ignoreListAction);
211     contextMenu.addAction(whoBufferAction);
212
213     if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
214       if(index.data(NetworkModel::ItemActiveRole).toBool()) {
215         removeBufferAction->setEnabled(false);
216         removeBufferAction->setToolTip("To delete the buffer, part the channel first.");
217         joinBufferAction->setVisible(false);
218         whoBufferAction->setVisible(false);
219       } else {
220         partBufferAction->setVisible(false);
221       }
222     } else {
223       joinBufferAction->setVisible(false);
224       partBufferAction->setVisible(false);
225     }
226   }
227
228   QAction *result = contextMenu.exec(QCursor::pos());
229   if(result == connectNetAction || result == disconnectNetAction) {
230     const Network *network = Client::network(index.data(NetworkModel::NetworkIdRole).value<NetworkId>());
231     if(!network) return;
232     if(network->connectionState() == Network::Disconnected) 
233       network->requestConnect();
234     else 
235       network->requestDisconnect();
236   } else
237   if(result == joinChannelAction) {
238     // FIXME no QInputDialog in Qtopia
239 #ifndef Q_WS_QWS
240     bool ok;
241     QString channelName = QInputDialog::getText(this, tr("Join Channel"), 
242                                                 tr("Input channel name:"),QLineEdit::Normal,
243                                                 QDir::home().dirName(), &ok);
244
245     if (ok && !channelName.isEmpty()) {
246       BufferInfo bufferInfo = index.child(0,0).data(NetworkModel::BufferInfoRole).value<BufferInfo>();
247       if(bufferInfo.isValid()) {
248         Client::instance()->userInput(bufferInfo, QString("/J %1").arg(channelName));
249       }
250     }
251 #endif
252   } else
253   if(result == joinBufferAction) {
254     Client::instance()->userInput(bufferInfo, QString("/JOIN %1").arg(channelname));
255   } else
256   if(result == partBufferAction) {
257     Client::instance()->userInput(bufferInfo, QString("/PART %1").arg(channelname));
258   } else
259   if(result == removeBufferAction) {
260     int res = QMessageBox::question(this, tr("Remove buffer permanently?"),
261                                     tr("Do you want to delete the buffer \"%1\" permanently? This will delete all related data, including all backlog "
262                                        "data, from the core's database!").arg(bufferInfo.bufferName()),
263                                         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
264     if(res == QMessageBox::Yes) {
265       Client::removeBuffer(bufferInfo.bufferId());
266     } 
267   } else 
268   if(result == whoBufferAction) {
269     Client::instance()->userInput(bufferInfo, QString("/WHO %1").arg(channelname));
270   }
271 }
272
273 void BufferView::wheelEvent(QWheelEvent* event) {
274   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
275     return QTreeView::wheelEvent(event);
276
277   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
278   QModelIndex currentIndex = selectionModel()->currentIndex();
279   QModelIndex resultingIndex;
280   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
281     {
282       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
283     }
284     else //if we scroll into a the parent node...
285       {
286         QModelIndex parent = currentIndex.parent();
287         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
288         if( rowDelta == -1 )
289           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
290         else
291           resultingIndex = aunt.child( 0, 0 );
292         if( !resultingIndex.isValid() )
293           return;
294       }
295   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
296   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
297   
298 }
299
300
301 QSize BufferView::sizeHint() const {
302   return QSize(120, 50);
303   
304   if(!model())
305     return QTreeView::sizeHint();
306
307   if(model()->rowCount() == 0)
308     return QSize(120, 50);
309
310   int columnSize = 0;
311   for(int i = 0; i < model()->columnCount(); i++) {
312     if(!isColumnHidden(i))
313       columnSize += sizeHintForColumn(i);
314   }
315   return QSize(columnSize, 50);
316 }