e922559043bd65be57f4fdf99a0d8afdbdf2e9ec
[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      && (Global::SPUTDEV || 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(Global::SPUTDEV) {
149       if(isExpanded(networkIdx) != isActive) setExpanded(networkIdx, true);
150     } else {
151       if(isExpanded(networkIdx) != isActive)
152         setExpanded(networkIdx, isActive);
153     }
154   }
155 }
156
157
158 void BufferView::toggleHeader(bool checked) {
159   QAction *action = qobject_cast<QAction *>(sender());
160   header()->setSectionHidden((action->property("column")).toInt(), !checked);
161 }
162
163 void BufferView::showContextMenu(const QPoint &pos) {
164   QModelIndex index = indexAt(pos);
165   if(!index.isValid()) return;
166   QMenu contextMenu(this);
167   QAction *connectNetAction = new QAction(tr("Connect"), this);
168   QAction *disconnectNetAction = new QAction(tr("Disconnect"), this);
169   QAction *joinChannelAction = new QAction(tr("Join Channel"), this);
170
171   QAction *joinBufferAction = new QAction(tr("Join"), this);
172   QAction *partBufferAction = new QAction(tr("Part"), this);
173   QAction *removeBufferAction = new QAction(tr("Delete buffer"), this);
174
175   QMenu *hideEventsMenu = new QMenu(tr("Hide Events"), this);
176   QAction *hideJoinAction = hideEventsMenu->addAction(tr("Join Events"));
177   QAction *hidePartAction = hideEventsMenu->addAction(tr("Part Events"));
178   QAction *hideKillAction = hideEventsMenu->addAction(tr("Kill Events"));
179   QAction *hideQuitAction = hideEventsMenu->addAction(tr("Quit Events"));
180   QAction *hideModeAction = hideEventsMenu->addAction(tr("Mode Events"));
181   hideJoinAction->setCheckable(true);
182   hidePartAction->setCheckable(true);
183   hideKillAction->setCheckable(true);
184   hideQuitAction->setCheckable(true);
185   hideModeAction->setCheckable(true);
186   hideJoinAction->setEnabled(false);
187   hidePartAction->setEnabled(false);
188   hideKillAction->setEnabled(false);
189   hideQuitAction->setEnabled(false);
190   hideModeAction->setEnabled(false);
191
192   QAction *ignoreListAction = new QAction(tr("Ignore list"), this);
193   ignoreListAction->setEnabled(false);
194   QAction *whoBufferAction = new QAction(tr("WHO"), this);
195
196   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::NetworkItemType) {
197     if(index.data(NetworkModel::ItemActiveRole).toBool()) {
198       contextMenu.addAction(disconnectNetAction);
199       contextMenu.addSeparator();
200       contextMenu.addAction(joinChannelAction);
201     } else {
202       contextMenu.addAction(connectNetAction);
203     }
204   }
205
206   BufferInfo bufferInfo = index.data(NetworkModel::BufferInfoRole).value<BufferInfo>();
207   QString channelname = index.sibling(index.row(), 0).data().toString();
208
209   if(index.data(NetworkModel::ItemTypeRole) == NetworkModel::BufferItemType) {
210     if(bufferInfo.type() != BufferInfo::ChannelBuffer && bufferInfo.type() != BufferInfo::QueryBuffer) return;
211     contextMenu.addAction(joinBufferAction);
212     contextMenu.addAction(partBufferAction);
213     contextMenu.addAction(removeBufferAction);
214     contextMenu.addMenu(hideEventsMenu);
215     contextMenu.addAction(ignoreListAction);
216     contextMenu.addAction(whoBufferAction);
217
218     if(bufferInfo.type() == BufferInfo::ChannelBuffer) {
219       if(index.data(NetworkModel::ItemActiveRole).toBool()) {
220         removeBufferAction->setEnabled(false);
221         removeBufferAction->setToolTip("To delete the buffer, part the channel first.");
222         joinBufferAction->setVisible(false);
223         whoBufferAction->setVisible(false);
224       } else {
225         partBufferAction->setVisible(false);
226       }
227     } else {
228       joinBufferAction->setVisible(false);
229       partBufferAction->setVisible(false);
230     }
231   }
232
233   QAction *result = contextMenu.exec(QCursor::pos());
234   if(result == connectNetAction || result == disconnectNetAction) {
235     const Network *network = Client::network(index.data(NetworkModel::NetworkIdRole).value<NetworkId>());
236     if(!network) return;
237     if(network->connectionState() == Network::Disconnected) 
238       network->requestConnect();
239     else 
240       network->requestDisconnect();
241   } else
242   if(result == joinChannelAction) {
243     // FIXME no QInputDialog in Qtopia
244 #ifndef Q_WS_QWS
245     bool ok;
246     QString channelName = QInputDialog::getText(this, tr("Join Channel"), 
247                                                 tr("Input channel name:"),QLineEdit::Normal,
248                                                 QDir::home().dirName(), &ok);
249
250     if (ok && !channelName.isEmpty()) {
251       BufferInfo bufferInfo = index.child(0,0).data(NetworkModel::BufferInfoRole).value<BufferInfo>();
252       if(bufferInfo.isValid()) {
253         Client::instance()->userInput(bufferInfo, QString("/J %1").arg(channelName));
254       }
255     }
256 #endif
257   } else
258   if(result == joinBufferAction) {
259     Client::instance()->userInput(bufferInfo, QString("/JOIN %1").arg(channelname));
260   } else
261   if(result == partBufferAction) {
262     Client::instance()->userInput(bufferInfo, QString("/PART %1").arg(channelname));
263   } else
264   if(result == removeBufferAction) {
265     int res = QMessageBox::question(this, tr("Remove buffer permanently?"),
266                                     tr("Do you want to delete the buffer \"%1\" permanently? This will delete all related data, including all backlog "
267                                        "data, from the core's database!").arg(bufferInfo.bufferName()),
268                                         QMessageBox::Yes|QMessageBox::No, QMessageBox::No);
269     if(res == QMessageBox::Yes) {
270       Client::removeBuffer(bufferInfo.bufferId());
271     } 
272   } else 
273   if(result == whoBufferAction) {
274     Client::instance()->userInput(bufferInfo, QString("/WHO %1").arg(channelname));
275   }
276 }
277
278 void BufferView::wheelEvent(QWheelEvent* event) {
279   if(UiSettings().value("MouseWheelChangesBuffers", QVariant(true)).toBool() == (bool)(event->modifiers() & Qt::AltModifier))
280     return QTreeView::wheelEvent(event);
281
282   int rowDelta = ( event->delta() > 0 ) ? -1 : 1;
283   QModelIndex currentIndex = selectionModel()->currentIndex();
284   QModelIndex resultingIndex;
285   if( model()->hasIndex(  currentIndex.row() + rowDelta, currentIndex.column(), currentIndex.parent() ) )
286     {
287       resultingIndex = currentIndex.sibling( currentIndex.row() + rowDelta, currentIndex.column() );
288     }
289     else //if we scroll into a the parent node...
290       {
291         QModelIndex parent = currentIndex.parent();
292         QModelIndex aunt = parent.sibling( parent.row() + rowDelta, parent.column() );
293         if( rowDelta == -1 )
294           resultingIndex = aunt.child( model()->rowCount( aunt ) - 1, 0 );
295         else
296           resultingIndex = aunt.child( 0, 0 );
297         if( !resultingIndex.isValid() )
298           return;
299       }
300   selectionModel()->setCurrentIndex( resultingIndex, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows );
301   selectionModel()->select( resultingIndex, QItemSelectionModel::ClearAndSelect );
302   
303 }
304
305
306 QSize BufferView::sizeHint() const {
307   return QSize(120, 50);
308   
309   if(!model())
310     return QTreeView::sizeHint();
311
312   if(model()->rowCount() == 0)
313     return QSize(120, 50);
314
315   int columnSize = 0;
316   for(int i = 0; i < model()->columnCount(); i++) {
317     if(!isColumnHidden(i))
318       columnSize += sizeHintForColumn(i);
319   }
320   return QSize(columnSize, 50);
321 }