527eb79540a01a953355fd89e3ec64bb18ce5d68
[quassel.git] / src / uisupport / tabcompleter.cpp
1 /***************************************************************************
2 *   Copyright (C) 2005-09 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 "tabcompleter.h"
22
23 #include "buffermodel.h"
24 #include "client.h"
25 #include "ircchannel.h"
26 #include "ircuser.h"
27 #include "multilineedit.h"
28 #include "network.h"
29 #include "networkmodel.h"
30 #include "uisettings.h"
31 #include "action.h"
32 #include "actioncollection.h"
33 #include "qtui.h"
34
35 #include <QRegExp>
36
37 const Network *TabCompleter::_currentNetwork;
38 BufferId TabCompleter::_currentBufferId;
39 QString TabCompleter::_currentBufferName;
40 TabCompleter::Type TabCompleter::_completionType;
41
42 TabCompleter::TabCompleter(MultiLineEdit *_lineEdit)
43   : QObject(_lineEdit),
44     _lineEdit(_lineEdit),
45     _enabled(false),
46     _nickSuffix(": ")
47 {
48   // use both an Action and generic eventFilter, to make the shortcut configurable
49   // yet still be able to reset() when required
50   _lineEdit->installEventFilter(this);
51   ActionCollection *coll = QtUi::actionCollection("General");
52   coll->addAction("TabCompletionKey", new Action(tr("Tab completion"), coll,
53                                               this, SLOT(onTabCompletionKey()), QKeySequence(Qt::Key_Tab)));
54 }
55
56 void TabCompleter::onTabCompletionKey() {
57   complete();
58 }
59
60 void TabCompleter::buildCompletionList() {
61   // ensure a safe state in case we return early.
62   _completionMap.clear();
63   _nextCompletion = _completionMap.begin();
64
65   // this is the first time tab is pressed -> build up the completion list and it's iterator
66   QModelIndex currentIndex = Client::bufferModel()->currentIndex();
67   _currentBufferId = currentIndex.data(NetworkModel::BufferIdRole).value<BufferId>();
68   if(!_currentBufferId.isValid())
69     return;
70
71   NetworkId networkId = currentIndex.data(NetworkModel::NetworkIdRole).value<NetworkId>();
72   _currentBufferName = currentIndex.sibling(currentIndex.row(), 0).data().toString();
73
74   _currentNetwork = Client::network(networkId);
75   if(!_currentNetwork)
76     return;
77
78   QString tabAbbrev = _lineEdit->text().left(_lineEdit->cursorPosition()).section(QRegExp("[^#\\w\\d-_\\[\\]{}|`^.\\\\]"),-1,-1);
79   QRegExp regex(QString("^[-_\\[\\]{}|`^.\\\\]*").append(QRegExp::escape(tabAbbrev)), Qt::CaseInsensitive);
80
81   // channel completion - add all channels of the current network to the map
82   if(tabAbbrev.startsWith('#')) {
83     _completionType = ChannelTab;
84     foreach(IrcChannel *ircChannel, _currentNetwork->ircChannels()) {
85       if(regex.indexIn(ircChannel->name()) > -1)
86         _completionMap[ircChannel->name()] = ircChannel->name();
87     }
88   } else {
89     // user completion
90     _completionType = UserTab;
91     switch(static_cast<BufferInfo::Type>(currentIndex.data(NetworkModel::BufferTypeRole).toInt())) {
92     case BufferInfo::ChannelBuffer:
93       { // scope is needed for local var declaration
94         IrcChannel *channel = _currentNetwork->ircChannel(_currentBufferName);
95         if(!channel)
96           return;
97         foreach(IrcUser *ircUser, channel->ircUsers()) {
98           if(regex.indexIn(ircUser->nick()) > -1)
99             _completionMap[ircUser->nick().toLower()] = ircUser->nick();
100         }
101       }
102       break;
103     case BufferInfo::QueryBuffer:
104       if(regex.indexIn(_currentBufferName) > -1)
105         _completionMap[_currentBufferName.toLower()] = _currentBufferName;
106     case BufferInfo::StatusBuffer:
107       if(!_currentNetwork->myNick().isEmpty() && regex.indexIn(_currentNetwork->myNick()) > -1)
108         _completionMap[_currentNetwork->myNick().toLower()] = _currentNetwork->myNick();
109       break;
110     default:
111       return;
112     }
113   }
114
115   _nextCompletion = _completionMap.begin();
116   _lastCompletionLength = tabAbbrev.length();
117 }
118
119 void TabCompleter::complete() {
120   TabCompletionSettings s;
121   _nickSuffix = s.completionSuffix();
122
123   if(!_enabled) {
124     buildCompletionList();
125     _enabled = true;
126   }
127
128   if (_nextCompletion != _completionMap.end()) {
129     // clear previous completion
130     for (int i = 0; i < _lastCompletionLength; i++) {
131       _lineEdit->backspace();
132     }
133
134     // insert completion
135     _lineEdit->insert(*_nextCompletion);
136
137     // remember charcount to delete next time and advance to next completion
138     _lastCompletionLength = _nextCompletion->length();
139     _nextCompletion++;
140
141     // we're completing the first word of the line
142     if(_completionType == UserTab && _lineEdit->cursorPosition() == _lastCompletionLength) {
143       _lineEdit->insert(_nickSuffix);
144       _lastCompletionLength += _nickSuffix.length();
145     } else if (s.addSpaceMidSentence()) {
146       _lineEdit->insert(" ");
147     }
148
149   // we're at the end of the list -> start over again
150   } else {
151     if(!_completionMap.isEmpty()) {
152       _nextCompletion = _completionMap.begin();
153       complete();
154     }
155   }
156 }
157
158 void TabCompleter::reset() {
159   _enabled = false;
160 }
161
162 bool TabCompleter::eventFilter(QObject *obj, QEvent *event) {
163   if(obj != _lineEdit || event->type() != QEvent::KeyPress)
164     return QObject::eventFilter(obj, event);
165
166   QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
167
168   if(keyEvent->key() != QtUi::actionCollection("General")->action("TabCompletionKey")->shortcut()) {
169     reset();
170   }
171   return false;
172 }
173
174 // this determines the sort order
175 bool TabCompleter::CompletionKey::operator<(const CompletionKey &other) const {
176   switch(_completionType) {
177     case UserTab:
178       {
179         IrcUser *thisUser = _currentNetwork->ircUser(this->contents);
180         if(thisUser && _currentNetwork->isMe(thisUser))
181           return false;
182
183         IrcUser *thatUser = _currentNetwork->ircUser(other.contents);
184         if(thatUser && _currentNetwork->isMe(thatUser))
185           return true;
186
187         if(!thisUser || !thatUser)
188           return QString::localeAwareCompare(this->contents, other.contents) < 0;
189
190         QDateTime thisSpokenTo = thisUser->lastSpokenTo(_currentBufferId);
191         QDateTime thatSpokenTo = thatUser->lastSpokenTo(_currentBufferId);
192
193         if(thisSpokenTo.isValid() || thatSpokenTo.isValid())
194           return thisSpokenTo > thatSpokenTo;
195
196         QDateTime thisTime = thisUser->lastChannelActivity(_currentBufferId);
197         QDateTime thatTime = thatUser->lastChannelActivity(_currentBufferId);
198
199         if(thisTime.isValid() || thatTime.isValid())
200           return thisTime > thatTime;
201       }
202       break;
203     case ChannelTab:
204       if(QString::compare(_currentBufferName, this->contents, Qt::CaseInsensitive) == 0)
205           return true;
206
207       if(QString::compare(_currentBufferName, other.contents, Qt::CaseInsensitive) == 0)
208           return false;
209       break;
210     default:
211       break;
212   }
213
214   return QString::localeAwareCompare(this->contents, other.contents) < 0;
215 }