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