summaryrefslogtreecommitdiffstats
path: root/konversation/src/konversationapplication.cpp
blob: befecf70c3dca798081f50cecae4e925f6659447 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
/*
  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.
*/

/*
  Copyright (C) 2002 Dario Abatianni <eisfuchs@tigress.com>
  Copyright (C) 2005 Ismail Donmez <ismail@kde.org>
  Copyright (C) 2005 Peter Simonsson <psn@linux.se>
  Copyright (C) 2005 John Tapsell <johnflux@gmail.com>
  Copyright (C) 2005-2008 Eike Hein <hein@kde.org>
*/

#include "konversationapplication.h"
#include "konversationmainwindow.h"
#include "connectionmanager.h"
#include "awaymanager.h"
#include "dcctransfermanager.h"
#include "viewcontainer.h"
#include "highlight.h"
#include "server.h"
#include "konversationsound.h"
#include "quickconnectdialog.h"
#include "servergroupsettings.h"
#include "serversettings.h"
#include "channel.h"
#include "images.h"
#include "notificationhandler.h"
#include "commit.h"
#include "version.h"

#include <tqtextcodec.h>
#include <tqregexp.h>
#include <tqfileinfo.h>

#include <kdebug.h>
#include <tdecmdlineargs.h>
#include <tdeconfig.h>
#include <dcopclient.h>
#include <tdeversion.h>
#include <kstandarddirs.h>
#include <tdelocale.h>
#include <tdemessagebox.h>
#include <kiconloader.h>


KonversationApplication::KonversationApplication()
: KUniqueApplication(true, true, true)
{
    mainWindow = 0;
    m_connectionManager = 0;
    m_awayManager = 0;
    quickConnectDialog = 0;
    osd = 0;
}

KonversationApplication::~KonversationApplication()
{
    kdDebug() << k_funcinfo << endl;
    Server::_stashRates();
    Preferences::writeConfig();
    saveOptions(false);

    delete m_images;
    delete dcopObject;
    //delete prefsDCOP;
    delete identDCOP;
    delete osd;
    osd = 0;
}

int KonversationApplication::newInstance()
{
    TDECmdLineArgs* args = TDECmdLineArgs::parsedArgs();
    TQCString url;
    if (args->count() > 0) url = args->arg(0);

    if (!mainWindow)
    {
        connect(this, TQT_SIGNAL(shutDown()), this, TQT_SLOT(prepareShutdown()));

        m_connectionManager = new ConnectionManager(TQT_TQOBJECT(this));

        m_awayManager = new AwayManager(TQT_TQOBJECT(this));

        connect(m_connectionManager, TQT_SIGNAL(identityOnline(int)), m_awayManager, TQT_SLOT(identityOnline(int)));
        connect(m_connectionManager, TQT_SIGNAL(identityOffline(int)), m_awayManager, TQT_SLOT(identityOffline(int)));
        connect(m_connectionManager, TQT_SIGNAL(identityOffline(int)), m_awayManager, TQT_SLOT(identityOffline(int)));
        connect(m_connectionManager, TQT_SIGNAL(connectionChangedAwayState(bool)), m_awayManager, TQT_SLOT(updateGlobalAwayAction(bool)));

        // an instance of DccTransferManager needs to be created before GUI class instances' creation.
        m_dccTransferManager = new DccTransferManager(TQT_TQOBJECT(this));

        // make sure all vars are initialized properly
        quickConnectDialog = 0;

        // Sound object used to play sound...
        m_sound = new Konversation::Sound(TQT_TQOBJECT(this));

        // initialize OSD display here, so we can read the Preferences::properly
        osd = new OSDWidget( "Konversation" );

        Preferences::self();
        readOptions();

        // Images object providing LEDs, NickIcons
        m_images = new Images();
        connect(this, TQT_SIGNAL(iconChanged(int)), m_images, TQT_SLOT(updateIcons()));

        // Auto-alias scripts.  This adds any missing aliases
        TQStringList aliasList(Preferences::aliasList());
        TQStringList scripts(Preferences::defaultAliasList());
        bool changed = false;
        for ( TQStringList::ConstIterator it = scripts.begin(); it != scripts.end(); ++it )
        {
            if(!aliasList.contains(*it)) {
                changed = true;
                aliasList.append(*it);
            }
        }
        if(changed)
            Preferences::setAliasList(aliasList);

        // Setup system codec
        // TODO: check if this works now as intended
        //    TQTextCodec::setCodecForCStrings(TQTextCodec::codecForLocale());

        // open main window
        mainWindow = new KonversationMainWindow();
        setMainWidget(mainWindow);

        connect(mainWindow, TQT_SIGNAL(showQuickConnectDialog()), this, TQT_SLOT(openQuickConnectDialog()) );
        connect(Preferences::self(), TQT_SIGNAL(updateTrayIcon()), mainWindow, TQT_SLOT(updateTrayIcon()) );
        connect(osd, TQT_SIGNAL(hidden()), mainWindow, TQT_SIGNAL(endNotification()));
        // take care of user style changes, setting back colors and stuff

        // apply GUI settings
        emit appearanceChanged();

        if (Preferences::showTrayIcon() && (Preferences::hiddenToTray() || Preferences::hideToTrayOnStartup()))
            mainWindow->hide();
        else
            mainWindow->show();

        bool openServerList = Preferences::showServerList();

        // handle autoconnect on startup
        Konversation::ServerGroupList serverGroups = Preferences::serverGroupList();

        if (url.isEmpty() && !args->isSet("server"))
        {
            for (Konversation::ServerGroupList::iterator it = serverGroups.begin(); it != serverGroups.end(); ++it)
            {
                if ((*it)->autoConnectEnabled())
                {
                    openServerList = false;
                    m_connectionManager->connectTo(Konversation::CreateNewConnection, (*it)->id());
                }
            }
        }

        if (openServerList) mainWindow->openServerList();

        connect(this, TQT_SIGNAL(serverGroupsChanged(const Konversation::ServerGroupSettings*)), this, TQT_SLOT(saveOptions()));

        // prepare dcop interface
        dcopObject = new KonvDCOP;
        kapp->dcopClient()->setDefaultObject(dcopObject->objId());
        identDCOP = new KonvIdentDCOP;

        if (dcopObject)
        {
            connect(dcopObject,TQT_SIGNAL (dcopMultiServerRaw(const TQString&)),
                this,TQT_SLOT (dcopMultiServerRaw(const TQString&)) );
            connect(dcopObject,TQT_SIGNAL (dcopRaw(const TQString&,const TQString&)),
                this,TQT_SLOT (dcopRaw(const TQString&,const TQString&)) );
            connect(dcopObject,TQT_SIGNAL (dcopSay(const TQString&,const TQString&,const TQString&)),
                this,TQT_SLOT (dcopSay(const TQString&,const TQString&,const TQString&)) );
            connect(dcopObject,TQT_SIGNAL (dcopInfo(const TQString&)),
                this,TQT_SLOT (dcopInfo(const TQString&)) );
            connect(dcopObject,TQT_SIGNAL (dcopInsertMarkerLine()),
                mainWindow,TQT_SIGNAL(insertMarkerLine()));
            connect(dcopObject, TQT_SIGNAL(connectTo(Konversation::ConnectionFlag, const TQString&, const TQString&, const TQString&, const TQString&, const TQString&, bool)),
                m_connectionManager, TQT_SLOT(connectTo(Konversation::ConnectionFlag, const TQString&, const TQString&, const TQString&, const TQString&, const TQString&, bool)));
        }

        m_notificationHandler = new Konversation::NotificationHandler(this);
    }

    if (!url.isEmpty())
        getConnectionManager()->connectTo(Konversation::SilentlyReuseConnection, TQString(url));
    else if (args->isSet("server"))
    {
        getConnectionManager()->connectTo(Konversation::SilentlyReuseConnection,
                                          args->getOption("server"),
                                          args->getOption("port"),
                                          args->getOption("password"),
                                          args->getOption("nick"),
                                          args->getOption("channel"),
                                          args->isSet("ssl"));
    }

    return KUniqueApplication::newInstance();
}

KonversationApplication* KonversationApplication::instance()
{
    return static_cast<KonversationApplication*>(TDEApplication::kApplication());
}

void KonversationApplication::prepareShutdown()
{
    if (mainWindow->isHidden() && Preferences::showTrayIcon())
        Preferences::setHiddenToTray(true);
    else
        Preferences::setHiddenToTray(false);

    mainWindow->getViewContainer()->prepareShutdown();

    m_awayManager->blockSignals(true);
    delete m_awayManager;

    m_connectionManager->quitServers();
    m_connectionManager->blockSignals(true);
    delete m_connectionManager;
}

void KonversationApplication::showQueueTuner(bool p)
{
    getMainWindow()->getViewContainer()->showQueueTuner(p);
}

void KonversationApplication::dcopMultiServerRaw(const TQString &command)
{
    sendMultiServerCommand(command.section(' ', 0,0), command.section(' ', 1));
}

void KonversationApplication::dcopRaw(const TQString& connection, const TQString &command)
{
    Server* server = 0;

    bool conversion = false;
    int connectionId = connection.toInt(&conversion);

    if (conversion) server = getConnectionManager()->getServerByConnectionId(connectionId);

    if (!server) server = getConnectionManager()->getServerByName(connection);

    if (server) server->dcopRaw(command);
}


void KonversationApplication::dcopSay(const TQString& connection, const TQString& target, const TQString& command)
{
    Server* server = 0;

    bool conversion = false;
    int connectionId = connection.toInt(&conversion);

    if (conversion) server = getConnectionManager()->getServerByConnectionId(connectionId);

    if (!server) server = getConnectionManager()->getServerByName(connection);

    if (server) server->dcopSay(target, command);
}

void KonversationApplication::dcopInfo(const TQString& string)
{
    mainWindow->getViewContainer()->appendToFrontmost(i18n("DCOP"), string, 0);
}

void KonversationApplication::readOptions()
{
    // get standard config file
    TDEConfig* config=kapp->config();

    // read nickname sorting order for channel nick lists
    config->setGroup("Sort Nicknames");
    TQString sortOrder=config->readEntry("SortOrder");
    TQStringList sortOrderList=TQStringList::split("",sortOrder);
    sortOrderList.sort();
    if (sortOrderList.join("")!="-hopqv")
    {
      sortOrder=Preferences::defaultNicknameSortingOrder();
      Preferences::setSortOrder(sortOrder);
    }

    // Identity list
    TQStringList identityList=config->groupList().grep(TQRegExp("Identity [0-9]+"));
    if(!identityList.isEmpty())
    {
        Preferences::clearIdentityList();

        for(unsigned int index=0;index<identityList.count();index++)
        {
            IdentityPtr newIdentity=new Identity();

            config->setGroup(identityList[index]);

            newIdentity->setName(config->readEntry("Name"));

            newIdentity->setIdent(config->readEntry("Ident"));
            newIdentity->setRealName(config->readEntry("Realname"));

            newIdentity->setNicknameList(config->readListEntry("Nicknames"));

            newIdentity->setBot(config->readEntry("Bot"));
            newIdentity->setPassword(config->readEntry("Password"));

            newIdentity->setInsertRememberLineOnAway(config->readBoolEntry("InsertRememberLineOnAway"));
            newIdentity->setShowAwayMessage(config->readBoolEntry("ShowAwayMessage"));
            newIdentity->setAwayMessage(config->readEntry("AwayMessage"));
            newIdentity->setReturnMessage(config->readEntry("ReturnMessage"));
            newIdentity->setAutomaticAway(config->readBoolEntry("AutomaticAway", false));
            newIdentity->setAwayInactivity(config->readNumEntry("AwayInactivity", 10));
            newIdentity->setAutomaticUnaway(config->readBoolEntry("AutomaticUnaway", false));

            newIdentity->setQuitReason(config->readEntry("QuitReason"));
            newIdentity->setPartReason(config->readEntry("PartReason"));
            newIdentity->setKickReason(config->readEntry("KickReason"));

            newIdentity->setShellCommand(config->readEntry("PreShellCommand"));

            newIdentity->setCodecName(config->readEntry("Codec"));

            newIdentity->setAwayNick(config->readEntry("AwayNick"));

            Preferences::addIdentity(newIdentity);

        }

    }

    osd->setEnabled(Preferences::useOSD());

    //How to load the font from the text?
    osd->setFont(Preferences::oSDFont());

    osd->setDuration(Preferences::oSDDuration());
    osd->setScreen(Preferences::oSDScreen());
    osd->setShadow(Preferences::oSDDrawShadow());

    osd->setOffset(Preferences::oSDOffsetX(), Preferences::oSDOffsetY());
    osd->setAlignment((OSDWidget::Alignment)Preferences::oSDAlignment());

    if(Preferences::oSDUseCustomColors())
    {
        osd->setTextColor(Preferences::oSDTextColor());
        osd->setBackgroundColor(Preferences::oSDBackgroundColor());
    }

    // Check if there is old server list config
    config->setGroup("Server List");

    // Read the new server settings
    TQStringList groups = config->groupList().grep(TQRegExp("ServerGroup [0-9]+"));
    TQMap<int,TQStringList> notifyList;

    if(!groups.isEmpty())
    {
        Konversation::ServerGroupList serverGroups;
        TQStringList::iterator it;
        TQStringList tmp1;
        TQStringList::iterator it2;
        Konversation::ChannelList channelHistory;
        Konversation::ServerSettings server;
        Konversation::ChannelSettings channel;

        for(it = groups.begin(); it != groups.end(); ++it)
        {
            config->setGroup((*it));
            Konversation::ServerGroupSettingsPtr serverGroup = new Konversation::ServerGroupSettings;
            serverGroup->setName(config->readEntry("Name"));
            serverGroup->setIdentityId(Preferences::identityByName(config->readEntry("Identity"))->id());
            serverGroup->setConnectCommands(config->readEntry("ConnectCommands"));
            serverGroup->setAutoConnectEnabled(config->readBoolEntry("AutoConnect"));
            serverGroup->setNotificationsEnabled(config->readBoolEntry("EnableNotifications", true));
            serverGroup->setExpanded(config->readBoolEntry("Expanded", false));

            notifyList.insert((*serverGroup).id(),TQStringList::split(' ',config->readEntry("NotifyList")));

            tmp1 = config->readListEntry("ServerList");
            for(it2 = tmp1.begin(); it2 != tmp1.end(); ++it2)
            {
                config->setGroup((*it2));
                server.setHost(config->readEntry("Server"));
                server.setPort(config->readNumEntry("Port"));
                server.setPassword(config->readEntry("Password"));
                server.setSSLEnabled(config->readBoolEntry("SSLEnabled"));
                serverGroup->addServer(server);
            }

            config->setGroup((*it));
            tmp1 = config->readListEntry("AutoJoinChannels");

            for(it2 = tmp1.begin(); it2 != tmp1.end(); ++it2)
            {
                config->setGroup((*it2));

                if(!config->readEntry("Name").isEmpty())
                {
                    channel.setName(config->readEntry("Name"));
                    channel.setPassword(config->readEntry("Password"));
                    serverGroup->addChannel(channel);
                }
            }

            config->setGroup((*it));
            tmp1 = config->readListEntry("ChannelHistory");
            channelHistory.clear();

            for(it2 = tmp1.begin(); it2 != tmp1.end(); ++it2)
            {
                config->setGroup((*it2));

                if(!config->readEntry("Name").isEmpty())
                {
                    channel.setName(config->readEntry("Name"));
                    channel.setPassword(config->readEntry("Password"));
                    channel.setNotificationsEnabled(config->readBoolEntry("EnableNotifications", true));
                    channelHistory.append(channel);
                }
            }

            serverGroup->setChannelHistory(channelHistory);

            serverGroups.append(serverGroup);
        }

        Preferences::setServerGroupList(serverGroups);
    }

    // Notify Settings and lists.  Must follow Server List.
    Preferences::setNotifyList(notifyList);
    Preferences::setNotifyDelay(Preferences::notifyDelay());
    Preferences::setUseNotify(Preferences::useNotify());

    // Quick Buttons List

    // if there are button definitions in the config file, remove default buttons
    if(config->hasGroup("Button List")) Preferences::clearQuickButtonList();
    config->setGroup("Button List");
    // Read all default buttons
    TQStringList buttonList(Preferences::quickButtonList());
    // Read all quick buttons
    int index=0;
    while(config->hasKey(TQString("Button%1").arg(index)))
    {
      buttonList.append(config->readEntry(TQString("Button%1").arg(index++)));
    } // while
    // Put back the changed button list
    Preferences::setQuickButtonList(buttonList);

    // Autoreplace List

    // if there are autoreplace definitions in the config file, remove default entries
    if(config->hasGroup("Autoreplace List")) Preferences::clearAutoreplaceList();
    config->setGroup("Autoreplace List");
    // Read all default entries
    TQStringList autoreplaceList(Preferences::autoreplaceList());
    // Read all entries
    index=0;
    while(config->hasKey(TQString("Autoreplace%1").arg(index)))
    {
      // read entry and get length of the string
      TQString entry=config->readEntry(TQString("Autoreplace%1").arg(index++));
      unsigned int length=entry.length()-1;
      // if there's a "#" in the end, strip it (used to preserve blanks at the end of the replacement text)
      // there should always be one, but older versions did not do it, so we check first
      if(entry.at(length)=='#') entry=entry.left(length);
      // add entry to internal list
      autoreplaceList.append(entry);
    } // while
    // Put back the changed autoreplace list
    Preferences::setAutoreplaceList(autoreplaceList);

    // Highlight List
    if(config->hasKey("Highlight"))               // Stay compatible with versions < 0.14
    {
        TQString highlight=config->readEntry("Highlight");
        TQStringList hiList=TQStringList::split(' ',highlight);

        unsigned int hiIndex;
        for(hiIndex=0;hiIndex<hiList.count();hiIndex+=2)
        {
            Preferences::addHighlight(hiList[hiIndex],false,'#'+hiList[hiIndex+1],TQString(),TQString());
        }

        config->deleteEntry("Highlight");
    }
    else
    {
        int i = 0;

        while(config->hasGroup(TQString("Highlight%1").arg(i)))
        {
            config->setGroup(TQString("Highlight%1").arg(i));
            Preferences::addHighlight(config->readEntry("Pattern"),
                config->readBoolEntry("RegExp"),
                config->readColorEntry("Color"),
                config->readPathEntry("Sound"),
                config->readEntry("AutoText"));
            i++;
        }
    }

    // Ignore List
    config->setGroup("Ignore List");
    // Remove all default entries if there is at least one Ignore in the Preferences::file
    if(config->hasKey("Ignore0")) Preferences::clearIgnoreList();
    // Read all ignores
    index=0;
    while(config->hasKey(TQString("Ignore%1").arg(index)))
    {
        Preferences::addIgnore(config->readEntry(TQString("Ignore%1").arg(index++)));
    }

    // Aliases
    config->setGroup("Aliases");
    TQStringList newList=config->readListEntry("AliasList");
    if(!newList.isEmpty()) Preferences::setAliasList(newList);

    // Channel Encodings
    TQMap<TQString,TQString> channelEncodingEntries=config->entryMap("Channel Encodings");
    TQRegExp re("^(.+) ([^\\s]+)$");
    TQStringList channelEncodingEntryKeys=channelEncodingEntries.keys();
    TQStringList::iterator itStr=channelEncodingEntryKeys.begin();
    for(; itStr != channelEncodingEntryKeys.end(); ++itStr)
    {
        if(re.search(*itStr) > -1)
        {
            int serverGroupId = Preferences::serverGroupIdByName(re.cap(1));
            if(serverGroupId != -1)
                Preferences::setChannelEncoding(serverGroupId,re.cap(2),channelEncodingEntries[*itStr]);
        }
    }

    // O, what a tangled web
    Server::_fetchRates();
}

void KonversationApplication::saveOptions(bool updateGUI)
{
    TDEConfig* config=kapp->config();

//    Should be handled in NicklistBehaviorConfigController now
//    config->setGroup("Sort Nicknames");

    // Clean up identity list
    TQStringList identities=config->groupList().grep(TQRegExp("Identity [0-9]+"));
    if(identities.count())
    {
        // remove old identity list from Preferences::file to keep numbering under control
        for(unsigned int index=0;index<identities.count();index++)
            config->deleteGroup(identities[index]);
    }

    IdentityList identityList = Preferences::identityList();
    int index = 0;

    for(IdentityList::ConstIterator it = identityList.begin(); it != identityList.end(); ++it)
    {
        IdentityPtr identity = (*it);
        config->setGroup(TQString("Identity %1").arg(index));

        config->writeEntry("Name",identity->getName());
        config->writeEntry("Ident",identity->getIdent());
        config->writeEntry("Realname",identity->getRealName());
        config->writeEntry("Nicknames",identity->getNicknameList());
        config->writeEntry("Bot",identity->getBot());
        config->writeEntry("Password",identity->getPassword());
        config->writeEntry("InsertRememberLineOnAway", identity->getInsertRememberLineOnAway());
        config->writeEntry("ShowAwayMessage",identity->getShowAwayMessage());
        config->writeEntry("AwayMessage",identity->getAwayMessage());
        config->writeEntry("ReturnMessage",identity->getReturnMessage());
        config->writeEntry("AutomaticAway", identity->getAutomaticAway());
        config->writeEntry("AwayInactivity", identity->getAwayInactivity());
        config->writeEntry("AutomaticUnaway", identity->getAutomaticUnaway());
        config->writeEntry("QuitReason",identity->getQuitReason());
        config->writeEntry("PartReason",identity->getPartReason());
        config->writeEntry("KickReason",identity->getKickReason());
        config->writeEntry("PreShellCommand",identity->getShellCommand());
        config->writeEntry("Codec",identity->getCodecName());
        config->writeEntry("AwayNick", identity->getAwayNick());
        index++;
    }                                             // endfor

    // Remove the old servergroups from the config
    TQStringList groups = config->groupList().grep(TQRegExp("ServerGroup [0-9]+"));
    if(groups.count())
    {
        TQStringList::iterator it;
        for(it = groups.begin(); it != groups.end(); ++it)
        {
            config->deleteGroup((*it));
        }
    }

    // Remove the old servers from the config
    groups = config->groupList().grep(TQRegExp("Server [0-9]+"));
    if(groups.count())
    {
        TQStringList::iterator it;
        for(it = groups.begin(); it != groups.end(); ++it)
        {
            config->deleteGroup((*it));
        }
    }

    // Remove the old channels from the config
    groups = config->groupList().grep(TQRegExp("Channel [0-9]+"));
    if(groups.count())
    {
        TQStringList::iterator it;
        for(it = groups.begin(); it != groups.end(); ++it)
        {
            config->deleteGroup((*it));
        }
    }

    // Add the new servergroups to the config
    Konversation::ServerGroupList serverGroupList = Preferences::serverGroupList();
    Konversation::ServerGroupList::iterator it;
    index = 0;
    int index2 = 0;
    int index3 = 0;
    int width = TQString::number(serverGroupList.count()).length();
    TQString groupName;
    TQStringList servers;
    Konversation::ServerList::iterator it2;
    Konversation::ServerList serverlist;
    Konversation::ChannelList channelList;
    Konversation::ChannelList::iterator it3;
    TQStringList channels;
    TQStringList channelHistory;

    for(it = serverGroupList.begin(); it != serverGroupList.end(); ++it)
    {
        serverlist = (*it)->serverList();
        servers.clear();

        for(it2 = serverlist.begin(); it2 != serverlist.end(); ++it2)
        {
            groupName = TQString("Server %1").arg(index2);
            servers.append(groupName);
            config->setGroup(groupName);
            config->writeEntry("Server", (*it2).host());
            config->writeEntry("Port", (*it2).port());
            config->writeEntry("Password", (*it2).password());
            config->writeEntry("SSLEnabled", (*it2).SSLEnabled());
            index2++;
        }

        channelList = (*it)->channelList();
        channels.clear();

        for(it3 = channelList.begin(); it3 != channelList.end(); ++it3)
        {
            groupName = TQString("Channel %1").arg(index3);
            channels.append(groupName);
            config->setGroup(groupName);
            config->writeEntry("Name", (*it3).name());
            config->writeEntry("Password", (*it3).password());
            index3++;
        }

        channelList = (*it)->channelHistory();
        channelHistory.clear();

        for(it3 = channelList.begin(); it3 != channelList.end(); ++it3)
        {
            groupName = TQString("Channel %1").arg(index3);
            channelHistory.append(groupName);
            config->setGroup(groupName);
            config->writeEntry("Name", (*it3).name());
            config->writeEntry("Password", (*it3).password());
            config->writeEntry("EnableNotifications", (*it3).enableNotifications());
            index3++;
        }

        config->setGroup(TQString("ServerGroup %1").arg(TQString::number(index).rightJustify(width,'0')));
        config->writeEntry("Name", (*it)->name());
        config->writeEntry("Identity", (*it)->identity()->getName());
        config->writeEntry("ServerList", servers);
        config->writeEntry("AutoJoinChannels", channels);
        config->writeEntry("ConnectCommands", (*it)->connectCommands());
        config->writeEntry("AutoConnect", (*it)->autoConnectEnabled());
        config->writeEntry("ChannelHistory", channelHistory);
        config->writeEntry("EnableNotifications", (*it)->enableNotifications());
        config->writeEntry("Expanded", (*it)->expanded());
        config->writeEntry("NotifyList",Preferences::notifyStringByGroupName((*it)->name()));
        index++;
    }

    config->deleteGroup("Server List");

    // Ignore List
    config->deleteGroup("Ignore List");
    config->setGroup("Ignore List");
    TQPtrList<Ignore> ignoreList=Preferences::ignoreList();
    Ignore* item=ignoreList.first();
    index=0;
    while(item)
    {
        config->writeEntry(TQString("Ignore%1").arg(index),TQString("%1,%2").arg(item->getName()).arg(item->getFlags()));
        item=ignoreList.next();
        index++;
    }

    // Channel Encodings
    // remove all entries once
    config->deleteGroup("Channel Encodings");
    config->setGroup("Channel Encodings");
    TQValueList<int> encServers=Preferences::channelEncodingsServerGroupIdList();
    //i have no idea these would need to be sorted //encServers.sort();
    TQValueList<int>::iterator encServer;
    for ( encServer = encServers.begin(); encServer != encServers.end(); ++encServer )
    {
        Konversation::ServerGroupSettingsPtr sgsp = Preferences::serverGroupById(*encServer);
        if ( sgsp )  // sgsp == 0 when the entry is of QuickConnect or something?
        {
            TQStringList encChannels=Preferences::channelEncodingsChannelList(*encServer);
            //ditto //encChannels.sort();
            TQStringList::iterator encChannel;
            for ( encChannel = encChannels.begin(); encChannel != encChannels.end(); ++encChannel )
            {
                TQString enc = Preferences::channelEncoding(*encServer, *encChannel);
                TQString key = sgsp->name() + ' ' + (*encChannel);
                config->writeEntry(key, enc);
            }
        }
    }

    config->sync();

    if(updateGUI)
        emit appearanceChanged();
}

// FIXME: use KURL maybe?
void KonversationApplication::storeUrl(const TQString& who,const TQString& newUrl)
{
    TQString url(newUrl);
    // clean up URL to help KRun() in URL catcher interface
    if(url.startsWith("www.")) url="http://"+url;
    else if(url.startsWith("ftp.")) url="ftp://"+url;

    url=url.replace("&amp;","&");

    // check that we don't add the same URL twice
    deleteUrl(who,url);
    urlList.append(who+' '+url);
    emit catchUrl(who,url);
}

const TQStringList& KonversationApplication::getUrlList()
{
    return urlList;
}

void KonversationApplication::deleteUrl(const TQString& who,const TQString& url)
{
    urlList.remove(who+' '+url);
}

void KonversationApplication::clearUrlList()
{
    urlList.clear();
}

void KonversationApplication::openQuickConnectDialog()
{
    quickConnectDialog = new QuickConnectDialog(mainWindow);
    connect(quickConnectDialog, TQT_SIGNAL(connectClicked(Konversation::ConnectionFlag, const TQString&, const TQString&,
        const TQString&, const TQString&, const TQString&, bool)),
        m_connectionManager, TQT_SLOT(connectTo(Konversation::ConnectionFlag, const TQString&, const TQString&,
        const TQString&, const TQString&, const TQString&, bool)));
    quickConnectDialog->show();
}

void KonversationApplication::sendMultiServerCommand(const TQString& command, const TQString& parameter)
{
    TQPtrList<Server> serverList = getConnectionManager()->getServerList();

    for (Server* server = serverList.first(); server; server = serverList.next())
        server->executeMultiServerCommand(command, parameter);
}

void KonversationApplication::splitNick_Server(const TQString& nick_server, TQString &ircnick, TQString &serverOrGroup)
{
    //kaddresbook uses the utf separator 0xE120, so treat that as a separator as well
    TQString nickServer = nick_server;
    nickServer.replace(TQChar(0xE120), "@");
    ircnick = nickServer.section("@",0,0);
    serverOrGroup = nickServer.section("@",1);
}

NickInfoPtr KonversationApplication::getNickInfo(const TQString &ircnick, const TQString &serverOrGroup)
{
    TQPtrList<Server> serverList = getConnectionManager()->getServerList();
    NickInfoPtr nickInfo;
    TQString lserverOrGroup = serverOrGroup.lower();
    for(Server* lookServer = serverList.first(); lookServer; lookServer = serverList.next())
    {
        if(lserverOrGroup.isEmpty()
            || lookServer->getServerName().lower()==lserverOrGroup
            || lookServer->getDisplayName().lower()==lserverOrGroup)
        {
            nickInfo = lookServer->getNickInfo(ircnick);
            if(nickInfo) return nickInfo;         //If we found one
        }
    }
    return 0;
}

// auto replace on input/output
TQString KonversationApplication::doAutoreplace(const TQString& text,bool output)
{
    // get autoreplace list
    TQStringList autoreplaceList=Preferences::autoreplaceList();
    // working copy
    TQString line=text;

    // loop through the list of replacement patterns
    for(unsigned int index=0;index<autoreplaceList.count();index++)
    {
        // get autoreplace definition
        TQString definition=autoreplaceList[index];
        // split definition in parts
        TQString regex=definition.section(',',0,0);
        TQString direction=definition.section(',',1,1);
        TQString pattern=definition.section(',',2,2);
        TQString replacement=definition.section(',',3);

        TQString isDirection=output ? "o" : "i";

        // only replace if this pattern is for the specific direction or both directions
        if(direction==isDirection || direction=="io")
        {
            // regular expression pattern?
            if(regex=="1")
            {
                // create regex from pattern
                TQRegExp needleReg=pattern;
                // set pattern case insensitive
                needleReg.setCaseSensitive(true);
                int index = 0;

                do {
                    replacement = definition.section(',',3);
                    // find matches
                    index = line.find(needleReg, index);

                    if(index != -1)
                    {
                        // remember captured patterns
                        TQStringList captures = needleReg.capturedTexts();

                        // replace %0 - %9 in regex groups
                        for(unsigned int capture=0;capture<captures.count();capture++)
                        {
                            replacement.replace(TQString("%%1").arg(capture),captures[capture]);
                        }
                        replacement.replace(TQRegExp("%[0-9]"),TQString());
                        // replace input with replacement
                        line.replace(index, captures[0].length(), replacement);
                        index += replacement.length();
                    }
                } while(index >= 0 && index < (int)line.length());
            }
            else
            {
                TQRegExp needleReg("\\b" + TQRegExp::escape(pattern) + "\\b");
                needleReg.setCaseSensitive(false);
                line.replace(needleReg,replacement);
            }
        }
    }

  return line;
}

#include "konversationapplication.moc"

// kate: space-indent on; tab-width 4; indent-width 4; mixed-indent off; replace-tabs on;
// vim: set et sw=4 ts=4 cino=l1,cs,U1: