Prevent ChatView from scrolling up 1px on buffer switch, fixes #544
[quassel.git] / src / common / network.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 #include <QSettings>
21 #include <QTextCodec>
22
23 #include "network.h"
24 #include "quassel.h"
25
26 QTextCodec *Network::_defaultCodecForServer = 0;
27 QTextCodec *Network::_defaultCodecForEncoding = 0;
28 QTextCodec *Network::_defaultCodecForDecoding = 0;
29 QString Network::_networksIniPath = QString();
30
31 // ====================
32 //  Public:
33 // ====================
34 Network::Network(const NetworkId &networkid, QObject *parent)
35   : SyncableObject(parent),
36     _proxy(0),
37     _networkId(networkid),
38     _identity(0),
39     _myNick(QString()),
40     _latency(0),
41     _networkName(QString("<not initialized>")),
42     _currentServer(QString()),
43     _connected(false),
44     _connectionState(Disconnected),
45     _prefixes(QString()),
46     _prefixModes(QString()),
47     _useRandomServer(false),
48     _useAutoIdentify(false),
49     _useAutoReconnect(false),
50     _autoReconnectInterval(60),
51     _autoReconnectRetries(10),
52     _unlimitedReconnectRetries(false),
53     _codecForServer(0),
54     _codecForEncoding(0),
55     _codecForDecoding(0),
56     _autoAwayActive(false)
57 {
58   setObjectName(QString::number(networkid.toInt()));
59 }
60
61 Network::~Network() {
62   emit aboutToBeDestroyed();
63 }
64
65 bool Network::isChannelName(const QString &channelname) const {
66   if(channelname.isEmpty())
67     return false;
68
69   if(supports("CHANTYPES"))
70     return support("CHANTYPES").contains(channelname[0]);
71   else
72     return QString("#&!+").contains(channelname[0]);
73 }
74
75 NetworkInfo Network::networkInfo() const {
76   NetworkInfo info;
77   info.networkName = networkName();
78   info.networkId = networkId();
79   info.identity = identity();
80   info.codecForServer = codecForServer();
81   info.codecForEncoding = codecForEncoding();
82   info.codecForDecoding = codecForDecoding();
83   info.serverList = serverList();
84   info.useRandomServer = useRandomServer();
85   info.perform = perform();
86   info.useAutoIdentify = useAutoIdentify();
87   info.autoIdentifyService = autoIdentifyService();
88   info.autoIdentifyPassword = autoIdentifyPassword();
89   info.useAutoReconnect = useAutoReconnect();
90   info.autoReconnectInterval = autoReconnectInterval();
91   info.autoReconnectRetries = autoReconnectRetries();
92   info.unlimitedReconnectRetries = unlimitedReconnectRetries();
93   info.rejoinChannels = rejoinChannels();
94   return info;
95 }
96
97 void Network::setNetworkInfo(const NetworkInfo &info) {
98   // we don't set our ID!
99   if(!info.networkName.isEmpty() && info.networkName != networkName()) setNetworkName(info.networkName);
100   if(info.identity > 0 && info.identity != identity()) setIdentity(info.identity);
101   if(info.codecForServer != codecForServer()) setCodecForServer(QTextCodec::codecForName(info.codecForServer));
102   if(info.codecForEncoding != codecForEncoding()) setCodecForEncoding(QTextCodec::codecForName(info.codecForEncoding));
103   if(info.codecForDecoding != codecForDecoding()) setCodecForDecoding(QTextCodec::codecForName(info.codecForDecoding));
104   if(info.serverList.count()) setServerList(toVariantList(info.serverList)); // FIXME compare components
105   if(info.useRandomServer != useRandomServer()) setUseRandomServer(info.useRandomServer);
106   if(info.perform != perform()) setPerform(info.perform);
107   if(info.useAutoIdentify != useAutoIdentify()) setUseAutoIdentify(info.useAutoIdentify);
108   if(info.autoIdentifyService != autoIdentifyService()) setAutoIdentifyService(info.autoIdentifyService);
109   if(info.autoIdentifyPassword != autoIdentifyPassword()) setAutoIdentifyPassword(info.autoIdentifyPassword);
110   if(info.useAutoReconnect != useAutoReconnect()) setUseAutoReconnect(info.useAutoReconnect);
111   if(info.autoReconnectInterval != autoReconnectInterval()) setAutoReconnectInterval(info.autoReconnectInterval);
112   if(info.autoReconnectRetries != autoReconnectRetries()) setAutoReconnectRetries(info.autoReconnectRetries);
113   if(info.unlimitedReconnectRetries != unlimitedReconnectRetries()) setUnlimitedReconnectRetries(info.unlimitedReconnectRetries);
114   if(info.rejoinChannels != rejoinChannels()) setRejoinChannels(info.rejoinChannels);
115 }
116
117 QString Network::prefixToMode(const QString &prefix) {
118   if(prefixes().contains(prefix))
119     return QString(prefixModes()[prefixes().indexOf(prefix)]);
120   else
121     return QString();
122 }
123
124 QString Network::modeToPrefix(const QString &mode) {
125   if(prefixModes().contains(mode))
126     return QString(prefixes()[prefixModes().indexOf(mode)]);
127   else
128     return QString();
129 }
130
131 QStringList Network::nicks() const {
132   // we don't use _ircUsers.keys() since the keys may be
133   // not up to date after a nick change
134   QStringList nicks;
135   foreach(IrcUser *ircuser, _ircUsers.values()) {
136     nicks << ircuser->nick();
137   }
138   return nicks;
139 }
140
141 QString Network::prefixes() {
142   if(_prefixes.isNull())
143     determinePrefixes();
144
145   return _prefixes;
146 }
147
148 QString Network::prefixModes() {
149   if(_prefixModes.isNull())
150     determinePrefixes();
151
152   return _prefixModes;
153 }
154
155 // example Unreal IRCD: CHANMODES=beI,kfL,lj,psmntirRcOAQKVCuzNSMTG
156 Network::ChannelModeType Network::channelModeType(const QString &mode) {
157   if(mode.isEmpty())
158     return NOT_A_CHANMODE;
159
160   QString chanmodes = support("CHANMODES");
161   if(chanmodes.isEmpty())
162     return NOT_A_CHANMODE;
163
164   ChannelModeType modeType = A_CHANMODE;
165   for(int i = 0; i < chanmodes.count(); i++) {
166     if(chanmodes[i] == mode[0])
167       break;
168     else if(chanmodes[i] == ',')
169       modeType = (ChannelModeType)(modeType << 1);
170   }
171   if(modeType > D_CHANMODE) {
172     qWarning() << "Network" << networkId() << "supplied invalid CHANMODES:" << chanmodes;
173     modeType = NOT_A_CHANMODE;
174   }
175   return modeType;
176 }
177
178 QString Network::support(const QString &param) const {
179   QString support_ = param.toUpper();
180   if(_supports.contains(support_))
181     return _supports[support_];
182   else
183     return QString();
184 }
185
186 IrcUser *Network::newIrcUser(const QString &hostmask, const QVariantMap &initData) {
187   QString nick(nickFromMask(hostmask).toLower());
188   if(!_ircUsers.contains(nick)) {
189     IrcUser *ircuser = new IrcUser(hostmask, this);
190     if(!initData.isEmpty()) {
191       ircuser->fromVariantMap(initData);
192       ircuser->setInitialized();
193     }
194
195     if(proxy())
196       proxy()->synchronize(ircuser);
197     else
198       qWarning() << "unable to synchronize new IrcUser" << hostmask << "forgot to call Network::setProxy(SignalProxy *)?";
199
200     connect(ircuser, SIGNAL(nickSet(QString)), this, SLOT(ircUserNickChanged(QString)));
201
202     _ircUsers[nick] = ircuser;
203
204     emit ircUserAdded(hostmask);
205     emit ircUserAdded(ircuser);
206   }
207
208   return _ircUsers[nick];
209 }
210
211 IrcUser *Network::ircUser(QString nickname) const {
212   nickname = nickname.toLower();
213   if(_ircUsers.contains(nickname))
214     return _ircUsers[nickname];
215   else
216     return 0;
217 }
218
219 void Network::removeIrcUser(IrcUser *ircuser) {
220   QString nick = _ircUsers.key(ircuser);
221   if(nick.isNull())
222     return;
223
224   _ircUsers.remove(nick);
225   disconnect(ircuser, 0, this, 0);
226   ircuser->deleteLater();
227 }
228
229 void Network::removeIrcChannel(IrcChannel *channel) {
230   QString chanName = _ircChannels.key(channel);
231   if(chanName.isNull())
232     return;
233
234   _ircChannels.remove(chanName);
235   disconnect(channel, 0, this, 0);
236   channel->deleteLater();
237 }
238
239 void Network::removeChansAndUsers() {
240   QList<IrcUser *> users = ircUsers();
241   _ircUsers.clear();
242   QList<IrcChannel *> channels = ircChannels();
243   _ircChannels.clear();
244
245   foreach(IrcChannel *channel, channels) {
246     proxy()->detachObject(channel);
247     disconnect(channel, 0, this, 0);
248   }
249   foreach(IrcUser *user, users) {
250     proxy()->detachObject(user);
251     disconnect(user, 0, this, 0);
252   }
253
254   // the second loop is needed because quit can have sideffects
255   foreach(IrcUser *user, users) {
256     user->quit();
257   }
258
259   qDeleteAll(users);
260   qDeleteAll(channels);
261 }
262
263 IrcChannel *Network::newIrcChannel(const QString &channelname, const QVariantMap &initData) {
264   if(!_ircChannels.contains(channelname.toLower())) {
265     IrcChannel *channel = ircChannelFactory(channelname);
266     if(!initData.isEmpty()) {
267       channel->fromVariantMap(initData);
268       channel->setInitialized();
269     }
270
271     if(proxy())
272       proxy()->synchronize(channel);
273     else
274       qWarning() << "unable to synchronize new IrcChannel" << channelname << "forgot to call Network::setProxy(SignalProxy *)?";
275
276     _ircChannels[channelname.toLower()] = channel;
277
278     emit ircChannelAdded(channelname);
279     emit ircChannelAdded(channel);
280   }
281   return _ircChannels[channelname.toLower()];
282 }
283
284 IrcChannel *Network::ircChannel(QString channelname) const {
285   channelname = channelname.toLower();
286   if(_ircChannels.contains(channelname))
287     return _ircChannels[channelname];
288   else
289     return 0;
290 }
291
292 QByteArray Network::defaultCodecForServer() {
293   if(_defaultCodecForServer)
294     return _defaultCodecForServer->name();
295   return QByteArray();
296 }
297
298 void Network::setDefaultCodecForServer(const QByteArray &name) {
299   _defaultCodecForServer = QTextCodec::codecForName(name);
300 }
301
302 QByteArray Network::defaultCodecForEncoding() {
303   if(_defaultCodecForEncoding)
304     return _defaultCodecForEncoding->name();
305   return QByteArray();
306 }
307
308 void Network::setDefaultCodecForEncoding(const QByteArray &name) {
309   _defaultCodecForEncoding = QTextCodec::codecForName(name);
310 }
311
312 QByteArray Network::defaultCodecForDecoding() {
313   if(_defaultCodecForDecoding)
314     return _defaultCodecForDecoding->name();
315   return QByteArray();
316 }
317
318 void Network::setDefaultCodecForDecoding(const QByteArray &name) {
319   _defaultCodecForDecoding = QTextCodec::codecForName(name);
320 }
321
322 QByteArray Network::codecForServer() const {
323   if(_codecForServer)
324     return _codecForServer->name();
325   return QByteArray();
326 }
327
328 void Network::setCodecForServer(const QByteArray &name) {
329   setCodecForServer(QTextCodec::codecForName(name));
330 }
331
332 void Network::setCodecForServer(QTextCodec *codec) {
333   _codecForServer = codec;
334   emit codecForServerSet(codecForServer());
335 }
336
337 QByteArray Network::codecForEncoding() const {
338   if(_codecForEncoding)
339     return _codecForEncoding->name();
340   return QByteArray();
341 }
342
343 void Network::setCodecForEncoding(const QByteArray &name) {
344   setCodecForEncoding(QTextCodec::codecForName(name));
345 }
346
347 void Network::setCodecForEncoding(QTextCodec *codec) {
348   _codecForEncoding = codec;
349   emit codecForEncodingSet(codecForEncoding());
350 }
351
352 QByteArray Network::codecForDecoding() const {
353   if(_codecForDecoding)
354     return _codecForDecoding->name();
355   else return QByteArray();
356 }
357
358 void Network::setCodecForDecoding(const QByteArray &name) {
359   setCodecForDecoding(QTextCodec::codecForName(name));
360 }
361
362 void Network::setCodecForDecoding(QTextCodec *codec) {
363   _codecForDecoding = codec;
364   emit codecForDecodingSet(codecForDecoding());
365 }
366
367 // FIXME use server encoding if appropriate
368 QString Network::decodeString(const QByteArray &text) const {
369   if(_codecForDecoding)
370     return ::decodeString(text, _codecForDecoding);
371   else return ::decodeString(text, _defaultCodecForDecoding);
372 }
373
374 QByteArray Network::encodeString(const QString &string) const {
375   if(_codecForEncoding) {
376     return _codecForEncoding->fromUnicode(string);
377   }
378   if(_defaultCodecForEncoding) {
379     return _defaultCodecForEncoding->fromUnicode(string);
380   }
381   return string.toAscii();
382 }
383
384 QString Network::decodeServerString(const QByteArray &text) const {
385   if(_codecForServer)
386     return ::decodeString(text, _codecForServer);
387   else
388     return ::decodeString(text, _defaultCodecForServer);
389 }
390
391 QByteArray Network::encodeServerString(const QString &string) const {
392   if(_codecForServer) {
393     return _codecForServer->fromUnicode(string);
394   }
395   if(_defaultCodecForServer) {
396     return _defaultCodecForServer->fromUnicode(string);
397   }
398   return string.toAscii();
399 }
400
401 /*** Handle networks.ini ***/
402
403 QStringList Network::presetNetworks(bool onlyDefault) {
404   // lazily find the file, make sure to not call one of the other preset functions first (they'll fail else)
405   if(_networksIniPath.isNull()) {
406     _networksIniPath = Quassel::findDataFilePath("networks.ini");
407     if(_networksIniPath.isNull()) {
408       _networksIniPath = ""; // now we won't check again, as it's not null anymore
409       return QStringList();
410     }
411   }
412   if(!_networksIniPath.isEmpty()) {
413     QSettings s(_networksIniPath, QSettings::IniFormat);
414     QStringList networks = s.childGroups();
415     if(!networks.isEmpty()) {
416       // we sort the list case-insensitive
417       QMap<QString, QString> sorted;
418       foreach(QString net, networks) {
419         if(onlyDefault && !s.value(QString("%1/Default").arg(net)).toBool())
420           continue;
421         sorted[net.toLower()] = net;
422       }
423       return sorted.values();
424     }
425   }
426   return QStringList();
427 }
428
429 QStringList Network::presetDefaultChannels(const QString &networkName) {
430   if(_networksIniPath.isEmpty())  // be sure to have called presetNetworks() first, else this always fails
431     return QStringList();
432   QSettings s(_networksIniPath, QSettings::IniFormat);
433   return s.value(QString("%1/DefaultChannels").arg(networkName)).toStringList();
434 }
435
436 NetworkInfo Network::networkInfoFromPreset(const QString &networkName) {
437   NetworkInfo info;
438   if(!_networksIniPath.isEmpty()) {
439     info.networkName = networkName;
440     QSettings s(_networksIniPath, QSettings::IniFormat);
441     s.beginGroup(info.networkName);
442     foreach(QString server, s.value("Servers").toStringList()) {
443       bool ssl = false;
444       QStringList splitserver = server.split(':', QString::SkipEmptyParts);
445       if(splitserver.count() != 2) {
446         qWarning() << "Invalid server entry in networks.conf:" << server;
447         continue;
448       }
449       if(splitserver[1].at(0) == '+')
450         ssl = true;
451       uint port = splitserver[1].toUInt();
452       if(!port) {
453         qWarning() << "Invalid port entry in networks.conf:" << server;
454         continue;
455       }
456       info.serverList << Network::Server(splitserver[0].trimmed(), port, QString(), ssl);
457     }
458   }
459   return info;
460 }
461
462
463 // ====================
464 //  Public Slots:
465 // ====================
466 void Network::setNetworkName(const QString &networkName) {
467   _networkName = networkName;
468   emit networkNameSet(networkName);
469 }
470
471 void Network::setCurrentServer(const QString &currentServer) {
472   _currentServer = currentServer;
473   emit currentServerSet(currentServer);
474 }
475
476 void Network::setConnected(bool connected) {
477   if(_connected == connected)
478     return;
479
480   _connected = connected;
481   if(!connected) {
482     setMyNick(QString());
483     setCurrentServer(QString());
484     removeChansAndUsers();
485   }
486   emit connectedSet(connected);
487 }
488
489 //void Network::setConnectionState(ConnectionState state) {
490 void Network::setConnectionState(int state) {
491   _connectionState = (ConnectionState)state;
492   //qDebug() << "netstate" << networkId() << networkName() << state;
493   emit connectionStateSet(state);
494   emit connectionStateSet(_connectionState);
495 }
496
497 void Network::setMyNick(const QString &nickname) {
498   _myNick = nickname;
499   if(!_myNick.isEmpty() && !ircUser(myNick())) {
500     newIrcUser(myNick());
501   }
502   emit myNickSet(nickname);
503 }
504
505 void Network::setLatency(int latency) {
506   if(_latency == latency)
507     return;
508   _latency = latency;
509   emit latencySet(latency);
510 }
511
512 void Network::setIdentity(IdentityId id) {
513   _identity = id;
514   emit identitySet(id);
515 }
516
517 void Network::setServerList(const QVariantList &serverList) {
518   _serverList = fromVariantList<Server>(serverList);
519   emit serverListSet(serverList);
520 }
521
522 void Network::setUseRandomServer(bool use) {
523   _useRandomServer = use;
524   emit useRandomServerSet(use);
525 }
526
527 void Network::setPerform(const QStringList &perform) {
528   _perform = perform;
529   emit performSet(perform);
530 }
531
532 void Network::setUseAutoIdentify(bool use) {
533   _useAutoIdentify = use;
534   emit useAutoIdentifySet(use);
535 }
536
537 void Network::setAutoIdentifyService(const QString &service) {
538   _autoIdentifyService = service;
539   emit autoIdentifyServiceSet(service);
540 }
541
542 void Network::setAutoIdentifyPassword(const QString &password) {
543   _autoIdentifyPassword = password;
544   emit autoIdentifyPasswordSet(password);
545 }
546
547 void Network::setUseAutoReconnect(bool use) {
548   _useAutoReconnect = use;
549   emit useAutoReconnectSet(use);
550 }
551
552 void Network::setAutoReconnectInterval(quint32 interval) {
553   _autoReconnectInterval = interval;
554   emit autoReconnectIntervalSet(interval);
555 }
556
557 void Network::setAutoReconnectRetries(quint16 retries) {
558   _autoReconnectRetries = retries;
559   emit autoReconnectRetriesSet(retries);
560 }
561
562 void Network::setUnlimitedReconnectRetries(bool unlimited) {
563   _unlimitedReconnectRetries = unlimited;
564   emit unlimitedReconnectRetriesSet(unlimited);
565 }
566
567 void Network::setRejoinChannels(bool rejoin) {
568   _rejoinChannels = rejoin;
569   emit rejoinChannelsSet(rejoin);
570 }
571
572 void Network::addSupport(const QString &param, const QString &value) {
573   if(!_supports.contains(param)) {
574     _supports[param] = value;
575     emit supportAdded(param, value);
576   }
577 }
578
579 void Network::removeSupport(const QString &param) {
580   if(_supports.contains(param)) {
581     _supports.remove(param);
582     emit supportRemoved(param);
583   }
584 }
585
586 QVariantMap Network::initSupports() const {
587   QVariantMap supports;
588   QHashIterator<QString, QString> iter(_supports);
589   while(iter.hasNext()) {
590     iter.next();
591     supports[iter.key()] = iter.value();
592   }
593   return supports;
594 }
595
596 QVariantMap Network::initIrcUsersAndChannels() const {
597   QVariantMap usersAndChannels;
598   QVariantMap users;
599   QVariantMap channels;
600
601   QHash<QString, IrcUser *>::const_iterator userIter = _ircUsers.constBegin();
602   QHash<QString, IrcUser *>::const_iterator userIterEnd = _ircUsers.constEnd();
603   while(userIter != userIterEnd) {
604     users[userIter.value()->hostmask()] = userIter.value()->toVariantMap();
605     userIter++;
606   }
607   usersAndChannels["users"] = users;
608
609   QHash<QString, IrcChannel *>::const_iterator channelIter = _ircChannels.constBegin();
610   QHash<QString, IrcChannel *>::const_iterator channelIterEnd = _ircChannels.constEnd();
611   while(channelIter != channelIterEnd) {
612     channels[channelIter.value()->name()] = channelIter.value()->toVariantMap();
613     channelIter++;
614   }
615   usersAndChannels["channels"] = channels;
616
617   return usersAndChannels;
618 }
619
620 void Network::initSetIrcUsersAndChannels(const QVariantMap &usersAndChannels) {
621   Q_ASSERT(proxy());
622   if(isInitialized()) {
623     qWarning() << "Network" << networkId() << "received init data for users and channels allthough there allready are known users or channels!";
624     return;
625   }
626
627   QVariantMap users = usersAndChannels.value("users").toMap();
628   QVariantMap::const_iterator userIter = users.constBegin();
629   QVariantMap::const_iterator userIterEnd = users.constEnd();
630   while(userIter != userIterEnd) {
631     newIrcUser(userIter.key(), userIter.value().toMap());
632     userIter++;
633   }
634
635   QVariantMap channels = usersAndChannels.value("channels").toMap();
636   QVariantMap::const_iterator channelIter = channels.constBegin();
637   QVariantMap::const_iterator channelIterEnd = channels.constEnd();
638   while(channelIter != channelIterEnd) {
639     newIrcChannel(channelIter.key(), channelIter.value().toMap());
640     channelIter++;
641   }
642 }
643
644 void Network::initSetSupports(const QVariantMap &supports) {
645   QMapIterator<QString, QVariant> iter(supports);
646   while(iter.hasNext()) {
647     iter.next();
648     addSupport(iter.key(), iter.value().toString());
649   }
650 }
651
652 IrcUser *Network::updateNickFromMask(const QString &mask) {
653   QString nick(nickFromMask(mask).toLower());
654   IrcUser *ircuser;
655
656   if(_ircUsers.contains(nick)) {
657     ircuser = _ircUsers[nick];
658     ircuser->updateHostmask(mask);
659   } else {
660     ircuser = newIrcUser(mask);
661   }
662   return ircuser;
663 }
664
665 void Network::ircUserNickChanged(QString newnick) {
666   QString oldnick = _ircUsers.key(qobject_cast<IrcUser*>(sender()));
667
668   if(oldnick.isNull())
669     return;
670
671   if(newnick.toLower() != oldnick) _ircUsers[newnick.toLower()] = _ircUsers.take(oldnick);
672
673   if(myNick().toLower() == oldnick)
674     setMyNick(newnick);
675 }
676
677 void Network::emitConnectionError(const QString &errorMsg) {
678   emit connectionError(errorMsg);
679 }
680
681 // ====================
682 //  Private:
683 // ====================
684 void Network::determinePrefixes() {
685   // seems like we have to construct them first
686   QString prefix = support("PREFIX");
687
688   if(prefix.startsWith("(") && prefix.contains(")")) {
689     _prefixes = prefix.section(")", 1);
690     _prefixModes = prefix.mid(1).section(")", 0, 0);
691   } else {
692     QString defaultPrefixes("~&@%+");
693     QString defaultPrefixModes("qaohv");
694
695     if(prefix.isEmpty()) {
696       _prefixes = defaultPrefixes;
697       _prefixModes = defaultPrefixModes;
698       return;
699     }
700
701     // we just assume that in PREFIX are only prefix chars stored
702     for(int i = 0; i < defaultPrefixes.size(); i++) {
703       if(prefix.contains(defaultPrefixes[i])) {
704         _prefixes += defaultPrefixes[i];
705         _prefixModes += defaultPrefixModes[i];
706       }
707     }
708     // check for success
709     if(!_prefixes.isNull())
710       return;
711
712     // well... our assumption was obviously wrong...
713     // check if it's only prefix modes
714     for(int i = 0; i < defaultPrefixes.size(); i++) {
715       if(prefix.contains(defaultPrefixModes[i])) {
716         _prefixes += defaultPrefixes[i];
717         _prefixModes += defaultPrefixModes[i];
718       }
719     }
720     // now we've done all we've could...
721   }
722 }
723
724 /************************************************************************
725  * NetworkInfo
726  ************************************************************************/
727
728 NetworkInfo::NetworkInfo()
729 : networkId(0),
730   identity(1),
731   useRandomServer(false),
732   useAutoIdentify(false),
733   autoIdentifyService("NickServ"),
734   useAutoReconnect(true),
735   autoReconnectInterval(60),
736   autoReconnectRetries(20),
737   unlimitedReconnectRetries(false),
738   rejoinChannels(true)
739 {
740
741 }
742
743 bool NetworkInfo::operator==(const NetworkInfo &other) const {
744   if(networkId != other.networkId) return false;
745   if(networkName != other.networkName) return false;
746   if(identity != other.identity) return false;
747   if(codecForServer != other.codecForServer) return false;
748   if(codecForEncoding != other.codecForEncoding) return false;
749   if(codecForDecoding != other.codecForDecoding) return false;
750   if(serverList != other.serverList) return false;
751   if(useRandomServer != other.useRandomServer) return false;
752   if(perform != other.perform) return false;
753   if(useAutoIdentify != other.useAutoIdentify) return false;
754   if(autoIdentifyService != other.autoIdentifyService) return false;
755   if(autoIdentifyPassword != other.autoIdentifyPassword) return false;
756   if(useAutoReconnect != other.useAutoReconnect) return false;
757   if(autoReconnectInterval != other.autoReconnectInterval) return false;
758   if(autoReconnectRetries != other.autoReconnectRetries) return false;
759   if(unlimitedReconnectRetries != other.unlimitedReconnectRetries) return false;
760   if(rejoinChannels != other.rejoinChannels) return false;
761   return true;
762 }
763
764 bool NetworkInfo::operator!=(const NetworkInfo &other) const {
765   return !(*this == other);
766 }
767
768 QDataStream &operator<<(QDataStream &out, const NetworkInfo &info) {
769   QVariantMap i;
770   i["NetworkId"] = QVariant::fromValue<NetworkId>(info.networkId);
771   i["NetworkName"] = info.networkName;
772   i["Identity"] = QVariant::fromValue<IdentityId>(info.identity);
773   i["CodecForServer"] = info.codecForServer;
774   i["CodecForEncoding"] = info.codecForEncoding;
775   i["CodecForDecoding"] = info.codecForDecoding;
776   i["ServerList"] = toVariantList(info.serverList);
777   i["UseRandomServer"] = info.useRandomServer;
778   i["Perform"] = info.perform;
779   i["UseAutoIdentify"] = info.useAutoIdentify;
780   i["AutoIdentifyService"] = info.autoIdentifyService;
781   i["AutoIdentifyPassword"] = info.autoIdentifyPassword;
782   i["UseAutoReconnect"] = info.useAutoReconnect;
783   i["AutoReconnectInterval"] = info.autoReconnectInterval;
784   i["AutoReconnectRetries"] = info.autoReconnectRetries;
785   i["UnlimitedReconnectRetries"] = info.unlimitedReconnectRetries;
786   i["RejoinChannels"] = info.rejoinChannels;
787   out << i;
788   return out;
789 }
790
791 QDataStream &operator>>(QDataStream &in, NetworkInfo &info) {
792   QVariantMap i;
793   in >> i;
794   info.networkId = i["NetworkId"].value<NetworkId>();
795   info.networkName = i["NetworkName"].toString();
796   info.identity = i["Identity"].value<IdentityId>();
797   info.codecForServer = i["CodecForServer"].toByteArray();
798   info.codecForEncoding = i["CodecForEncoding"].toByteArray();
799   info.codecForDecoding = i["CodecForDecoding"].toByteArray();
800   info.serverList = fromVariantList<Network::Server>(i["ServerList"].toList());
801   info.useRandomServer = i["UseRandomServer"].toBool();
802   info.perform = i["Perform"].toStringList();
803   info.useAutoIdentify = i["UseAutoIdentify"].toBool();
804   info.autoIdentifyService = i["AutoIdentifyService"].toString();
805   info.autoIdentifyPassword = i["AutoIdentifyPassword"].toString();
806   info.useAutoReconnect = i["UseAutoReconnect"].toBool();
807   info.autoReconnectInterval = i["AutoReconnectInterval"].toUInt();
808   info.autoReconnectRetries = i["AutoReconnectRetries"].toInt();
809   info.unlimitedReconnectRetries = i["UnlimitedReconnectRetries"].toBool();
810   info.rejoinChannels = i["RejoinChannels"].toBool();
811   return in;
812 }
813
814 QDebug operator<<(QDebug dbg, const NetworkInfo &i) {
815   dbg.nospace() << "(id = " << i.networkId << " name = " << i.networkName << " identity = " << i.identity
816                 << " codecForServer = " << i.codecForServer << " codecForEncoding = " << i.codecForEncoding << " codecForDecoding = " << i.codecForDecoding
817                 << " serverList = " << i.serverList << " useRandomServer = " << i.useRandomServer << " perform = " << i.perform
818                 << " useAutoIdentify = " << i.useAutoIdentify << " autoIdentifyService = " << i.autoIdentifyService << " autoIdentifyPassword = " << i.autoIdentifyPassword
819                 << " useAutoReconnect = " << i.useAutoReconnect << " autoReconnectInterval = " << i.autoReconnectInterval
820                 << " autoReconnectRetries = " << i.autoReconnectRetries << " unlimitedReconnectRetries = " << i.unlimitedReconnectRetries
821                 << " rejoinChannels = " << i.rejoinChannels << ")";
822   return dbg.space();
823 }
824
825 QDataStream &operator<<(QDataStream &out, const Network::Server &server) {
826   QVariantMap serverMap;
827   serverMap["Host"] = server.host;
828   serverMap["Port"] = server.port;
829   serverMap["Password"] = server.password;
830   serverMap["UseSSL"] = server.useSsl;
831   serverMap["sslVersion"] = server.sslVersion;
832   serverMap["UseProxy"] = server.useProxy;
833   serverMap["ProxyType"] = server.proxyType;
834   serverMap["ProxyHost"] = server.proxyHost;
835   serverMap["ProxyPort"] = server.proxyPort;
836   serverMap["ProxyUser"] = server.proxyUser;
837   serverMap["ProxyPass"] = server.proxyPass;
838   out << serverMap;
839   return out;
840 }
841
842 QDataStream &operator>>(QDataStream &in, Network::Server &server) {
843   QVariantMap serverMap;
844   in >> serverMap;
845   server.host = serverMap["Host"].toString();
846   server.port = serverMap["Port"].toUInt();
847   server.password = serverMap["Password"].toString();
848   server.useSsl = serverMap["UseSSL"].toBool();
849   server.sslVersion = serverMap["sslVersion"].toInt();
850   server.useProxy = serverMap["UseProxy"].toBool();
851   server.proxyType = serverMap["ProxyType"].toInt();
852   server.proxyHost = serverMap["ProxyHost"].toString();
853   server.proxyPort = serverMap["ProxyPort"].toUInt();
854   server.proxyUser = serverMap["ProxyUser"].toString();
855   server.proxyPass = serverMap["ProxyPass"].toString();
856   return in;
857 }
858
859
860 bool Network::Server::operator==(const Server &other) const {
861   if(host != other.host) return false;
862   if(port != other.port) return false;
863   if(password != other.password) return false;
864   if(useSsl != other.useSsl) return false;
865   if(sslVersion != other.sslVersion) return false;
866   if(useProxy != other.useProxy) return false;
867   if(proxyType != other.proxyType) return false;
868   if(proxyHost != other.proxyHost) return false;
869   if(proxyPort != other.proxyPort) return false;
870   if(proxyUser != other.proxyUser) return false;
871   if(proxyPass != other.proxyPass) return false;
872   return true;
873 }
874
875 bool Network::Server::operator!=(const Server &other) const {
876   return !(*this == other);
877 }
878
879 QDebug operator<<(QDebug dbg, const Network::Server &server) {
880   dbg.nospace() << "Server(host = " << server.host << ":" << server.port << ", useSsl = " << server.useSsl << ")";
881   return dbg.space();
882 }