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