summaryrefslogtreecommitdiffstats
path: root/ksirc/servercontroller.cpp
blob: c525ec65793f6e870321f4701db874fafba9b557 (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
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
 /**********************************************************************

 Server Controller

 $$Id$$

 Main Server Controller.  Displays server connection window, and makes
 new server connection on demand.

 Signals: NONE

 Slots:

   new_connection(): Creates popup asking for new connection

   new_ksircprocess(TQString):
      Args:
         TQString: new server name or IP to connect to.
      Action:
	 Creates a new sirc process and window !default connected to the
	 server.  Does nothing if a server connection already exists.

   add_toplevel(TQString tqparent, TQString child):
      Args:
	   tqparent: the server name that the new channel is being joined on
	   child: the new channel name
      Action:
         Adds "child" to the list of joined channles in the main
	 window.  Always call this on new window creation!

   delete_toplevel(TQString tqparent, TQString child):
      Args:
         tqparent: the server name of which channel is closing
	         child: the channle that is closing. IFF Emtpy, tqparent is
		 deleted.
      Action:
	 Deletes the "child" window from the list of connections.  If
	 the child is Empty the whole tree is removed since it is assumed
         the tqparent has disconnected and is closing.

   new_channel:  Creates popup asking for new channel name

   new_toplevel(TQString str):
      Args:
         str: name of the new channel to be created
      Action:
         Sends a signal to the currently selected server in the tree
         list and join the requested channel.  Does nothing if nothing
         is selected in the tree list.

   recvChangeChanel(TQString tqparent, TQString old, TQString new):
      Args:
         tqparent: tqparent server connection
         old: the old name for the window
         new: the new name for the window
      Action:
          Changes the old window name to the new window name in the tree
          list box.  Call for all name change!

 *********************************************************************/

#include <stdio.h>
#include <unistd.h>

#include "servercontroller.h"
#include "KSOpenkSirc/open_ksirc.h"
#include "NewWindowDialog.h"
#include "ksopts.h"
#include "control_message.h"
#include "FilterRuleEditor.h"
#include "../config.h"
#include "version.h"
#include "KSPrefs/ksprefs.h"
#include "toplevel.h"
#include "ksircserver.h"
#include "nickColourMaker.h"

#include <stdlib.h>

#include "objFinder.h"
#include <tqlabel.h>
#include <tqregexp.h>

#include <kmenubar.h>
#include <kconfig.h>
#include <kfontdialog.h>
#include <kiconloader.h>
#include <kwin.h>
#include <kdebug.h>
#include <kstdaccel.h>
#include <kstandarddirs.h>
#include <khelpmenu.h>
#include <kstdaction.h>
#include <kaction.h>
#include <knotifydialog.h>
#include <netwm.h>
#include <kpassivepopup.h>
#include <kglobalaccel.h>
#include <kstdguiitem.h>

#include <tqfile.h>

#include "displayMgrSDI.h"
#include "displayMgrMDI.h"

#include "dockservercontroller.h"

#ifdef HAVE_PATHS_H
#include <paths.h>
#endif
#include <klocale.h>
#include <kapplication.h>
#include <kpopupmenu.h>

DisplayMgr *displayMgr;

servercontroller *servercontroller::s_self = 0;

servercontroller::servercontroller( TQWidget*, const char* name )
    : KMainWindow( 0, name )
{
  we_are_exiting = false;
  m_notificationCount = 0;

  m_ncm = new nickColourMaker();

  MenuBar = menuBar();
  KWin::setIcons( winId(), kapp->icon(), kapp->miniIcon() );

  s_self = this;

  switch (ksopts->displayMode)
  {
    case KSOptions::SDI:
        displayMgr = new DisplayMgrSDI();
        break;
    case KSOptions::MDI:
        displayMgr = new DisplayMgrMDI();
        break;
  }

  sci = new scInside(this, TQCString(name) + "_mainview");
  setCentralWidget(sci);

  sci->setFrameStyle(TQFrame::Box | TQFrame::Raised);
  ConnectionTree = sci->ConnectionTree;

  connect(ConnectionTree, TQT_SIGNAL(clicked( TQListViewItem * )),
	  this, TQT_SLOT(WindowSelected(TQListViewItem *)));

  setFrameBorderWidth(5);

  TQPopupMenu *file = new TQPopupMenu(this, TQCString(name) + "_menu_file");
  KStdAction::quit(TQT_TQOBJECT(this), TQT_SLOT(endksirc()), actionCollection())->plug(file);
#ifndef NDEBUG
  file->insertItem(i18n("Dump Object Tree"), this, TQT_SLOT(dump_obj()));
  file->insertItem(i18n("Server Debug Window"), this, TQT_SLOT(server_debug()));
#endif
  MenuBar->insertItem(i18n("&File"), file);

  connections = new TQPopupMenu(this, TQCString(name) + "_menu_connections");

  server_id = connections->insertItem(i18n("&New Server..."), this, TQT_SLOT(new_connection()), Key_F2 );
  join_id = connections->insertItem(i18n("&Join Channel..."), this, TQT_SLOT(new_channel()), Key_F3 );
  connections->insertSeparator();
  connections->insertItem(i18n("&Do Autoconnect..."), this, TQT_SLOT(start_autoconnect_check()));
  connections->setItemEnabled(join_id, FALSE);
  MenuBar->insertItem(i18n("&Connections"), connections);

  options = new TQPopupMenu(this, TQCString(name) + "_menu_options");
  options->setCheckable(TRUE);

  options->insertItem(SmallIcon( "filter" ), i18n("&Filter Rule Editor..."),
		      this, TQT_SLOT(filter_rule_editor()));
  options->insertSeparator();
  KStdAction::configureNotifications(TQT_TQOBJECT(this), TQT_SLOT(notification_prefs()), actionCollection())->plug(options);

  KStdAction::preferences(TQT_TQOBJECT(this), TQT_SLOT(general_prefs()), actionCollection())->plug(options);

  MenuBar->insertItem(i18n("&Settings"), options);

  KHelpMenu *help = new KHelpMenu( this, kapp->aboutData() );
  MenuBar->insertItem( KStdGuiItem::help().text(), help->menu() );

  m_kga = new KGlobalAccel(TQT_TQOBJECT(this), "globalAccess");
  m_kga->insert("New Server", i18n("New Server"),
		i18n("This action allows you to open a new server more easily "
		     "when in docked mode, since you don't need to click on the "
		     "dock icon."),
		ALT+CTRL+Key_C, KKey::QtWIN+CTRL+Key_C, TQT_TQOBJECT(this),
		TQT_SLOT(new_connection()));

  open_toplevels = 0;

  pic_server = UserIcon("server");
  pic_gf = UserIcon("ksirc_a");
  pic_run = UserIcon("mini-run");
  pic_ppl = UserIcon("channels");
  pic_icon = UserIcon("ksirc_b");

  setCaption( i18n("Server Control") );
  KWin::setIcons(winId(), pic_icon, pic_server);

  resize( 450,200 );

  dockWidget = new dockServerController(this, 0x0, "servercontroller_dock");
  KWin::setSystemTrayWindowFor( dockWidget->winId(), winId() );

  m_kga->readSettings();
  m_kga->updateConnections();

  checkDocking();
}


servercontroller::~servercontroller()
{
  kdDebug(5008) << "~servercontroller in" << endl;
  s_self = 0;
  delete m_ncm;
  kdDebug(5008) << "~servercontroller out" << endl;
}

void servercontroller::checkDocking()
{
    if(ksopts->runDocked == true){
	dockWidget->show();
	hide();
        m_kga->setEnabled(true);
    }
    else {
        dockWidget->hide();
	show();
	m_kga->setEnabled(false);
    }

}

void servercontroller::new_connection()
{
  open_ksirc *w = new open_ksirc(); // Create new ksirc popup
  connect(w, TQT_SIGNAL(open_ksircprocess(KSircServer &)), // connected ok to process
          this, TQT_SLOT(new_ksircprocess(KSircServer &))); // start
  w->exec();                                       // show the sucker!
  delete w;
}

void servercontroller::new_ksircprocess(KSircServer &kss)
{
  TQString server_id;
  int id = 1;
  if(kss.server().isEmpty())  // nothing entered, nothing done
    return;
  server_id = kss.server();
  while(proc_list[server_id]){   // if it already exists, quit
    server_id = TQString("%1 %2").tqarg(kss.server()).tqarg(id++);
  }

  // Insert new base
  TQListViewItem *rootItem = new TQListViewItem( ConnectionTree, server_id );
  rootItem->setPixmap( 0, pic_server );
  rootItem->setOpen( true );

  // We do no_channel here since proc emits the signal in the
  // constructor, and we can't connect to before then, so we have to
  // do the dirty work here.
  ProcMessage(server_id, ProcCommand::addTopLevel, TQString("no_channel"));

  KSircProcess *proc = new KSircProcess(server_id, kss, 0, (TQString(name()) + "_" + server_id + "_ksp").ascii() ); // Create proc
  //this->insertChild(proc);                           // Add it to out inheritance tree so we can retreive child widgets from it.
  objFinder::insert(proc);
  proc_list.insert(server_id, proc);                      // Add proc to hash
  connect(proc, TQT_SIGNAL(ProcMessage(TQString, int, TQString)),
	  this, TQT_SLOT(ProcMessage(TQString, int, TQString)));
  connect(this, TQT_SIGNAL(ServMessage(TQString, int, TQString)),
	  proc, TQT_SLOT(ServMessage(TQString, int, TQString)));

  if(!ConnectionTree->currentItem()){   // If nothing's highlighted
    ConnectionTree->setCurrentItem(rootItem);     // highlight it.
  }

  connections->setItemEnabled(join_id, TRUE);

  dockWidget->serverOpen(server_id);
}

void servercontroller::new_channel()
{
  TQString server;
  TQListViewItem *citem = ConnectionTree->currentItem(); // get item
  if(citem){ // if it exist, ie something is highlighted, continue
    if(proc_list[citem->text(0)]){ // If it's a match with a server, ok
      server = citem->text(0);
    }
    // Otherwise, check the tqparent to see it's perhaps a server.
    else if ( citem->tqparent() ) {
      if(proc_list[citem->tqparent()->text(0)]){
        server = citem->tqparent()->text(0);
      }
    }
  }

  if(server.isEmpty())
    return;

  KSircChannel ci(server, TQString());
  NewWindowDialog w(ci);
  connect(&w, TQT_SIGNAL(openTopLevel(const KSircChannel &)),
	  this, TQT_SLOT(new_toplevel(const KSircChannel &)));
  w.exec();
}

void servercontroller::new_toplevel(const KSircChannel &channelInfo)
{
  new_toplevel(channelInfo, false);
}

void servercontroller::new_toplevel(const KSircChannel &channelInfo, bool safe)
{
    if(proc_list[channelInfo.server()]){ // If it's a match with a server, ok
        proc_list[channelInfo.server()]->new_toplevel(channelInfo, safe);
    }
}

void servercontroller::ToggleAutoCreate()
{
    ksopts->autoCreateWin = !ksopts->autoCreateWin;
}

void servercontroller::general_prefs()
{
  KSPrefs *kp = new KSPrefs();
  connect(kp, TQT_SIGNAL(update(int)),
          this, TQT_SLOT(configChange()));
  kp->resize(550, 450);
  kp->show();
}

void servercontroller::notification_prefs()
{
  KNotifyDialog::configure(this, "Notification Configuration Dialog");
}

void servercontroller::dump_obj()
{

	objFinder::dumpTree();

}
void servercontroller::server_debug()
{
  TQListViewItem *citem = ConnectionTree->currentItem(); // get item
  if(citem){ // if it exist, ie something is highlighted, continue
      TQString server;
      if(proc_list[citem->text(0)]){ // If it's a match with a server, ok
          server = citem->text(0);
      }
      else if ( citem->tqparent() ) {
	  if(proc_list[citem->tqparent()->text(0)]){
	      server = citem->tqparent()->text(0);
	  }
      }

      if( !server.isNull() ){
          bool sh = proc_list[server]->getIOController()->isDebugTraffic();
          proc_list[server]->getIOController()->showDebugTraffic(!sh);
      }
  }


}

void servercontroller::filter_rule_editor()
{
  FilterRuleEditor *fe = new FilterRuleEditor();
  connect(fe, TQT_SIGNAL(destroyed()),
	  this, TQT_SLOT(slot_filters_update()));
  fe->show();
}

void servercontroller::font_update(const TQFont &font)
{
  ksopts->defaultFont = font;
/*  configChange(); */

  KConfig *kConfig = kapp->config();
  kConfig->setGroup("GlobalOptions");
  kConfig->sync();
  TQApplication::tqsetFont( font, true, "KSirc::TextView" );
}

void servercontroller::configChange()
{
  TQDictIterator<KSircProcess> it( proc_list );
  while(it.current()){
    it.current()->filters_update();
    it.current()->getWindowList()["!all"]->control_message(REREAD_CONFIG, "");
    ++it;
  }
  m_kga->readSettings();
  m_kga->updateConnections();
}

void servercontroller::ProcMessage(TQString server, int command, TQString args)
{
  TQListViewItem *serverItem = 0L;
  TQListViewItem *item = ConnectionTree->firstChild();
  while ( item ) {
      if ( !item->tqparent() && item->text(0) == server ) {
	  serverItem = item;
	  break;
      }
      item = item->nextSibling();
  }

  if ( !serverItem ) {
      kdDebug(5008) << "* ProcMessage for non-existant server?! - " << server<< endl;
      return;
  }


  switch(command){


    // Nick offline and online both remove the nick first.
    // We remove the nick in case of an online so that we don't get
    // duplicates.
    // Args == nick comming on/offline.
  case ProcCommand::nickOffline:
      {
          TQListViewItem *online_item = findChild(serverItem, i18n("Online"));
          if(online_item){
              item = findChild(online_item, args);
              delete item;
              if(online_item->childCount() == 0)
                  delete online_item;
              if(ksopts->runDocked && ksopts->dockPopups)
                  KPassivePopup::message(i18n("%1 just went offline on %2").tqarg(args).tqarg(server), dockWidget);
          }
          dockWidget->nickOffline(server, args);
          break;
      }
  case ProcCommand::nickOnline:
      {
          TQListViewItem *online_item = findChild(serverItem, i18n("Online"));
          if(!online_item){
              online_item = new TQListViewItem(serverItem, i18n("Online"));
              online_item->setPixmap( 0, pic_gf );
              online_item->setOpen( true );
          }
          else {
              item = findChild(online_item, args);
              if( item ){
                  delete item;
              }
          }
          item = new TQListViewItem(online_item, args);
	  item->setPixmap( 0, pic_run );
	  if(ksopts->runDocked && ksopts->dockPopups)
	      KPassivePopup::message(i18n("%1 just came online on %2").tqarg(args).tqarg(server), dockWidget);
          dockWidget->nickOnline(server, args);
          break;
      }
      /*
    // Add new channel, first add the tqparent to the path
    path.push(&server);
    path.push(&online);
    path.push(&args);
    // Remove old one if it's there
    ConnectionTree->removeItem(&path); // Remove the item
    path.pop();
    // add a new child item with tqparent as its tqparent
    ConnectionTree->addChildItem(args, pic_run, &path);
    if (kSircConfig->BeepNotify) {
      KNotifyClient::beep();
    }
    break;
    */

    /**
      *  Args:
      *	   tqparent: the server name that the new channel is being joined on
      *    child:  the new channel name
      *  Action:
      *    Adds "child" to the list of joined channles in the main
      *    window.  Always call this on new window creation!
      */
  case ProcCommand::addTopLevel:
    // Add new channel
    if(args[0] == '!')
      args.remove(0, 1); // If the first char is !, it's control, remove it
    // add a new child item with tqparent as it's tqparent
    item = new TQListViewItem( serverItem, args );
    item->setPixmap( 0, pic_ppl );

    open_toplevels++;
    break;
    /**
      *  Args:
      *    tqparent: the server name of which channel is closing
      *	   child: the channle that is closing. IFF Emtpy, tqparent is
      *	   deleted.
      *  Action:
      *	   Deletes the "child" window from the list of connections.  If
      *	   the child is Empty the whole tree is removed since it is assumed
      *    the tqparent has disconnected and is closing.
      */
  case ProcCommand::deleteTopLevel:
    // If the child is emtpy, delete the whole tree, otherwise just the child
    if(args[0] == '!')
      args.remove(0, 1); // If the first char is !, it's control, remove it

    item = findChild( serverItem, args );
    delete item;
    if ( serverItem->childCount() == 0 )
	delete serverItem;

    open_toplevels--;
    break;

  /**
      *  Args:
      *    tqparent: tqparent server connection
      *    old: the old name for the window
      *    new: the new name for the window
      *  Action:
      *    Changes the old window name to the new window name in the tree
      *    list box.  Call for all name change!
      */
  case ProcCommand::changeChannel:
    {
      char *new_s, *old_s;
      new_s = new char[args.length()+1];
      old_s = new char[args.length()+1];
      sscanf(args.ascii(), "%s %s", old_s, new_s);
      //  If the channel has a !, it's a control channel, remove the !
      if(old_s[0] == '!')
        // Even though, we want strlen() -1 characters, strlen doesn't
        // include the \0, so we need to copy one more. -1 + 1 = 0.
	memmove(old_s, old_s+1, strlen(old_s));
      if(new_s[0] == '!')
	memmove(new_s, new_s+1, strlen(new_s)); // See above for strlen()

      item = findChild( serverItem, old_s );
      delete item;
      item = new TQListViewItem( serverItem, new_s );
      item->setPixmap( 0, pic_ppl );

      delete[] new_s;
      delete[] old_s;
    }
    break;
  case ProcCommand::procClose:
    dockWidget->serverClose(server);
    delete serverItem;
    proc_list.remove(server); // Remove process entry while we are at it
    if(proc_list.count() == 0){
      ConnectionTree->clear();
      connections->setItemEnabled(join_id, FALSE);
    }
    break;
  case ProcCommand::turnOffAutoCreate:
    if (ksopts->autoCreateWin) {
      ToggleAutoCreate();
    }
    break;
  case ProcCommand::turnOnAutoCreate:
    if (!ksopts->autoCreateWin) {
      ToggleAutoCreate();
    }
    break;
  default:
    kdDebug(5008) << "Unkown command: [" << command << "] from "
              << server
              << " " << args << endl;
  }
}

void servercontroller::slot_filters_update()
{
  emit ServMessage(TQString(), ServCommand::updateFilters, TQString());
}

void servercontroller::saveGlobalProperties(KConfig *ksc)
{
  // ksc hos the K Session config
  // ksp == current KSircProcess
  // ksm == current KSircMessageReceiver

  // Ignore all !<name> windows

  TQString group = ksc->group();

  ksc->setGroup( "KSircSession" );
  SessionConfigMap::ConstIterator it = m_sessionConfig.begin();
  for (; it != m_sessionConfig.end(); ++it ) {

      ChannelSessionInfoList infoList = *it;

      TQStringList channels;
      TQString port = "6667";
      TQStringList desktops;

      for ( ChannelSessionInfoList::ConstIterator sessionInfoIt = infoList.begin();
          sessionInfoIt != infoList.end(); ++sessionInfoIt ) {
	  channels << ( *sessionInfoIt ).name;
	  port = ( *sessionInfoIt ).port;
	  desktops << TQString::number( ( *sessionInfoIt ).desktop );
      }

      KConfigGroup( ksc, "KSircSession" ).writeEntry( it.key(), channels );
      KConfigGroup( ksc, "KSircSessionPort" ).writeEntry( it.key(), port );
      KConfigGroup( ksc, "KSircSessionDesktopNumbers" ).writeEntry( it.key(), desktops );
  }

  ksc->setGroup("ServerController");
//  ksc->writeEntry("Docked", !isVisible());
  ksc->writeEntry("Size", tqgeometry());
  ksc->setGroup(group);
}

void servercontroller::readGlobalProperties(KConfig *ksc)
{
    TQString group = ksc->group();

    // ksc == K Session Config

    // KMainWindow silently disables our menubar, when we quit in a docked
    // state, so we have to force showing it here.
    menuBar()->show();

    // commented in for testing...
    ksc->setGroup( "KSircSession" );
    TQMap<TQString,TQString> keyMap = ksc->entryMap( ksc->group() );
    TQMap<TQString,TQString>::Iterator it = keyMap.begin();

    while(it != keyMap.end()) {
	TQString server = it.key();
	TQString port = KConfigGroup( ksc, "KSircSessionPort" ).readEntry( server );
	//	debug("%s", it.key().latin1());
        KSircServer kss(server, port);
	new_ksircprocess( kss ); // sets up proc_list
	TQStringList channels = ksc->readListEntry( server );

	TQStringList desktops = KConfigGroup( ksc, "KSircSessionDesktopNumbers" ).readListEntry( server );

	for(uint i = 0; i < channels.count(); i++){

	    TQString channel = channels[ i ];

	    proc_list[ server ]->new_toplevel( KSircChannel(server, channel), true );

	    KSircTopLevel *topLevel = dynamic_cast<KSircTopLevel *>( proc_list[ server ]->getWindowList()[ channel ] );
	    if ( !topLevel || !topLevel->isTopLevel() )
		continue;

	    TQStringList::ConstIterator desktopNumberIt = desktops.at( i );
	    if ( desktopNumberIt == desktops.end() )
		continue;

	    int desktop = ( *desktopNumberIt ).toInt();
	    if ( desktop == -1 )
		continue;
#ifdef TQ_WS_X11
	    NETWinInfo winInfo( qt_xdisplay(), topLevel->winId(), qt_xrootwin(), NET::WMDesktop );
	    winInfo.setDesktop( desktop );
#endif
	}
	++it;
    }

    TQRect geom;

//    ksc->setGroup("ServerController");
//    bool docked = ksc->readBoolEntry("Docked", FALSE);
//    if ( !docked )
    //      show();
    if(ksopts->runDocked == false)
        show();

    geom = ksc->readRectEntry("Size");
    if(! geom.isEmpty())
    	setGeometry(geom);

    ksc->setGroup(group);
}

void servercontroller::saveSessionConfig()
{
    TQDictIterator<KSircProcess> ksp(proc_list);
    for (; ksp.current(); ++ksp ) {
	ChannelSessionInfoList channels;

	TQDictIterator<KSircMessageReceiver> ksm(ksp.current()->getWindowList());
	for (; ksm.current(); ++ksm )
	    if(ksm.currentKey()[0] != '!') { // Ignore !ksm's (system created)
		ChannelSessionInfo sessionInfo;

		sessionInfo.name = ksm.currentKey();
		sessionInfo.port = ksp.current()->serverPort();
		KSircTopLevel *topLev = dynamic_cast<KSircTopLevel *>( ksm.current() );
		if ( topLev && topLev->isTopLevel() ) {
#ifdef TQ_WS_X11
		    NETWinInfo winInfo( qt_xdisplay(), topLev->winId(), qt_xrootwin(), NET::WMDesktop );
		    sessionInfo.desktop = winInfo.desktop();
#endif
		}

		channels << sessionInfo;
	    }

	if ( !channels.isEmpty() )
	    m_sessionConfig[ ksp.currentKey() ] = channels;
    }
}

void servercontroller::showEvent( TQShowEvent *e )
{
  TQWidget::showEvent( e );
  if ( !e->spontaneous() )
    saveDockingtqStatus();
}

void servercontroller::hideEvent( TQHideEvent * )
{
    /*
  TQWidget::hideEvent( e );
  if ( !e->spontaneous() )
    saveDockingtqStatus();
  if(TQWidget::isMinimized()){
    hide();
    KWin::setState(winId(), NET::SkipTaskbar);
    }
    */
}

void servercontroller::saveDockingtqStatus()
{
    if ( we_are_exiting ) // we are hidden by closeEvent
	return;

//    KConfig *kConfig = kapp->config();
//    KConfigGroupSaver s( kConfig, "ServerController" );
//    kConfig->writeEntry("Docked", !isVisible());
//    kConfig->sync();
}

void servercontroller::endksirc(){
    kapp->config()->sync();
    exit(0);
}

void servercontroller::closeEvent( TQCloseEvent *e )
{
    we_are_exiting = true;
    saveSessionConfig();
    KMainWindow::closeEvent( e );
}

void servercontroller::WindowSelected(TQListViewItem *item)
{
    if ( !item )
	return;

  TQListViewItem *parent_server = item->tqparent();
  if(!parent_server)
    return;

  TQString txt = TQString(parent_server->text(0)) + "_" + item->text(0) + "_toplevel";
  TQWidget *obj = dynamic_cast<TQWidget *>( objFinder::tqfind(txt.utf8(), "KSircTopLevel"));
  if(obj == 0x0){
    txt =TQString(parent_server->text(0)) + "_!" + item->text(0) + "_toplevel";
    obj = dynamic_cast<TQWidget *>( objFinder::tqfind(txt.utf8(), "KSircTopLevel"));
  }

  if(obj != 0x0){
    displayMgr->raise(obj);
  }
  else {
    kdWarning() << "Did not find widget ptr to raise it" << endl;
  }
}


TQListViewItem * servercontroller::findChild( TQListViewItem *tqparent,
					     const TQString& text )
{
    if ( !tqparent || tqparent->childCount() == 0 ) {
	return 0L;
    }

    TQListViewItem *item = tqparent->firstChild();
    while ( item ) {
	if ( item->text(0) == text ) {
	    return item;
	}
	item = item->nextSibling();
    }

    return 0L;
}

void servercontroller::increaseNotificationCount(const TQString& reason, const TQString& text)
{
    dockWidget->startBlink(reason, text);
    m_notificationCount++;
}

void servercontroller::decreaseNotificationCount(TQString reason)
{
    m_notificationCount--;
    if ( m_notificationCount == 0 )
    {
        dockWidget->stopBlink(reason, true);
    }
    else {
        dockWidget->stopBlink(reason, false);
    }
}

void servercontroller::resetNotification()
{
    m_notificationCount = 0;
    dockWidget->stopBlink(TQString(), true);
    TQDictIterator<KSircProcess> it( proc_list );
    while(it.current()){
	it.current()->filters_update();
	it.current()->getWindowList()["!all"]->control_message(RESET_NOTIF, "");
	++it;
    }
}

void servercontroller::do_autoconnect()
{
    static int stime = 0;
    static int ctime = 0;
    int loop;

    kdDebug(5008) << "Doing AUTOCONNECT" << endl;

    KConfig *conf = kapp->config();
    conf->setGroup("AutoConnect");
    TQStringList servers = conf->readListEntry("Servers");
    servers.sort();
    TQStringList::ConstIterator ser = servers.begin();

    loop = 0;

    for( ; ser != servers.end(); ser++){
        if(loop++ == stime){
		stime++;
		TQString server = *ser;
		TQString port = "6667";
		bool usessl = false;
		TQString pass = TQString();

		TQRegExp rx("(.+) \\(SSL\\)(.*)");
		if(rx.search(server) >= 0){
		    server = rx.cap(1) + rx.cap(3);
                    usessl = true;
		}
		rx.setPattern("(.+) \\(pass: (\\S+)\\)(.*)");
		if(rx.search(server) >= 0){
		    server = rx.cap(1) + rx.cap(3);
		    pass = rx.cap(2);
		}
		rx.setPattern("([^: ]+):(\\d+)");
		if(rx.search(server) >= 0){
		    server = rx.cap(1);
		    port = rx.cap(2);
		}
		kdDebug(5008) << server << ": Done " << port << " " << usessl << " " << pass << endl;
                KSircServer kss(server, port, "", pass, usessl);
		new_ksircprocess(kss);
                return;
        }
    }

    loop = 0;

    ser = servers.begin();
    for( ; ser != servers.end(); ser++){
        TQStringList channels = conf->readListEntry(*ser);
        if(channels.empty() == FALSE){
            channels.sort();
            TQStringList::ConstIterator chan = channels.begin();
            for(; chan != channels.end(); chan++){
                if(loop++ == ctime){
		    ctime++;
		    TQString channel = *chan;
		    TQString key = TQString();
		    TQRegExp crx("(.+) \\(key: (\\S+)\\)");
		    if(crx.search(channel) >= 0){
			channel = crx.cap(1);
			key = crx.cap(2);
		    }
		    TQString server = *ser;

		    TQRegExp rx("^([^ :]+)");
		    if(rx.search(server) >= 0){
			server = rx.cap(1);
		    }
		    kdDebug(5008) << server << ": Channed: " << channel << " key: " << key << endl;
		    new_toplevel(KSircChannel(server, channel, key), true);
		    return;
		}
            }
        }
    }

    ctime = 0;
    stime = 0;
    at->stop();
    delete at;

}

void servercontroller::start_autoconnect() {
    at = new TQTimer(this);
    connect(at, TQT_SIGNAL(timeout()), this, TQT_SLOT(do_autoconnect()));
    at->start(250, FALSE);
}

void servercontroller::start_autoconnect_check() {

    KConfig *conf = kapp->config();
    conf->setGroup("AutoConnect");
    TQStringList servers = conf->readListEntry("Servers");

    if(servers.count() == 0){
	KSPrefs *kp = new KSPrefs();
	connect(kp, TQT_SIGNAL(update(int)),
		this, TQT_SLOT(configChange()));
	kp->resize(550, 450);
        kp->showPage(7); /* Show auto connect page */
	kp->show();
    }
    else {
	at = new TQTimer(this);
	connect(at, TQT_SIGNAL(timeout()), this, TQT_SLOT(do_autoconnect()));
	at->start(250, FALSE);
    }

}


scInside::scInside ( TQWidget * tqparent, const char * name, WFlags
		     f )
  : TQFrame(tqparent, name, f)
{
  ASConn = new TQLabel(i18n("Active server connections:"), this, "servercontroller_label");
  TQFont asfont = ASConn->font();
  asfont.setBold(TRUE);
  ASConn->setFont(asfont);

  ConnectionTree = new KListView(this, "connectiontree");
  ConnectionTree->addColumn(TQString());
  ConnectionTree->setRootIsDecorated( true );
  ConnectionTree->setSorting( 0 );
  ConnectionTree->header()->hide();
}

scInside::~scInside()
{
  delete ASConn;
  delete ConnectionTree;
}

void scInside::resizeEvent ( TQResizeEvent *e )
{
  TQFrame::resizeEvent(e);
  ASConn->setGeometry(10,10, width() - 20,
		      ASConn->fontMetrics().height()+5);
  ConnectionTree->setGeometry(10, 10 + ASConn->height(),
                              width() - 20, height() - 20 - ASConn->height());
}

#include "servercontroller.moc"