summaryrefslogtreecommitdiffstats
path: root/konsole/konsole/konsole_part.cpp
blob: 64fe3a7be2de1077272cf587dfd4de19dedf6947 (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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
/*
    This file is part of the KDE system
    Copyright (C)  1999,2000 Boloni Laszlo <lboloni@cpe.ucf.edu>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.

 */

#include "konsole_part.h"

#include <assert.h>

#include <tqfile.h>
#include <tqlayout.h>
#include <tqwmatrix.h>

#include <tdeaboutdata.h>
#include <kcharsets.h>
#include <kdebug.h>
#include <tdefontdialog.h>
#include <kglobalsettings.h>
#include <kiconloader.h>
#include <kinputdialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <krun.h>
#include <kstdaction.h>
#include <tqlabel.h>
#include <kprocctrl.h>

#include <tqcheckbox.h>
#include <tqspinbox.h>
#include <tqpushbutton.h>
#include <tdepopupmenu.h>
#include <krootpixmap.h>
#include <tdeconfig.h>
#include <tdeaction.h>

// We can't use the ARGB32 visual when embedded in another application
bool argb_visual = false;

K_EXPORT_COMPONENT_FACTORY( libkonsolepart, konsoleFactory )

/**
 * We need one static instance of the factory for our C 'main' function
 */
TDEInstance *konsoleFactory::s_instance = 0L;
TDEAboutData *konsoleFactory::s_aboutData = 0;

konsoleFactory::konsoleFactory()
{
}

konsoleFactory::~konsoleFactory()
{
  if (s_instance)
    delete s_instance;

  if ( s_aboutData )
    delete s_aboutData;

  s_instance = 0;
  s_aboutData = 0;
}

KParts::Part *konsoleFactory::createPartObject(TQWidget *parentWidget, const char *widgetName,
                                         TQObject *parent, const char *name, const char *classname,
                                         const TQStringList&)
{
//  kdDebug(1211) << "konsoleFactory::createPart parentWidget=" << parentWidget << " parent=" << parent << endl;
  KParts::Part *obj = new konsolePart(parentWidget, widgetName, parent, name, classname);
  return obj;
}

TDEInstance *konsoleFactory::instance()
{
  if ( !s_instance )
    {
      s_aboutData = new TDEAboutData("konsole", I18N_NOOP("Konsole"), "1.5");
      s_instance = new TDEInstance( s_aboutData );
    }
  return s_instance;
}

#define DEFAULT_HISTORY_SIZE 1000

konsolePart::konsolePart(TQWidget *_parentWidget, const char *widgetName, TQObject *parent, const char *name, const char *classname)
  : KParts::ReadOnlyPart(parent, name)
,te(0)
,se(0)
,colors(0)
,rootxpm(0)
,blinkingCursor(0)
,showFrame(0)
,m_useKonsoleSettings(0)
,selectBell(0)
,selectLineSpacing(0)
,selectScrollbar(0)
,m_keytab(0)
,m_schema(0)
,m_signals(0)
,m_options(0)
,m_popupMenu(0)
,b_useKonsoleSettings(false)
,b_autoDestroy(true)
,b_autoStartShell(true)
,m_histSize(DEFAULT_HISTORY_SIZE)
,m_runningShell( false )
{
  parentWidget=_parentWidget;
  setInstance(konsoleFactory::instance());

  m_extension = new konsoleBrowserExtension(this);

  // This is needed since only konsole.cpp does it
  // Without this -> crash on keypress... (David)
  KeyTrans::loadAll();

  m_streamEnabled = ( classname && strcmp( classname, "TerminalEmulator" ) == 0 );

  TQStrList eargs;


  const char* shell = getenv("SHELL");
  if (shell == NULL || *shell == '\0') shell = "/bin/sh";
  eargs.append(shell);
  te = new TEWidget(parentWidget,widgetName);
  te->setMinimumSize(150,70);    // allow resizing, cause resize in TEWidget

  setWidget(TQT_TQWIDGET(te));
  te->setFocus();
  connect( te,TQT_SIGNAL(configureRequest(TEWidget*,int,int,int)),
           this,TQT_SLOT(configureRequest(TEWidget*,int,int,int)) );

  colors = new ColorSchemaList();
  colors->checkSchemas();
  colors->sort();

  // Check to see which config file we use: konsolepartrc or konsolerc
  TDEConfig* config = new TDEConfig("konsolepartrc", true);
  config->setDesktopGroup();
  b_useKonsoleSettings = config->readBoolEntry("use_konsole_settings", false);
  delete config;

  readProperties();

  makeGUI();

  if (m_schema)
  {
     updateSchemaMenu();

     ColorSchema *sch=colors->find(s_schema);
     if (sch)
        curr_schema=sch->numb();
     else
        curr_schema = 0;

     for (uint i=0; i<m_schema->count(); i++)
        m_schema->setItemChecked(i,false);

     m_schema->setItemChecked(curr_schema,true);
  }

  // insert keymaps into menu
  if (m_keytab)
  {
     m_keytab->clear();

     TQStringList kt_titles;
     typedef TQMap<TQString,KeyTrans*> QStringKeyTransMap;
     QStringKeyTransMap kt_map;

     for (int i = 0; i < KeyTrans::count(); i++)
     {
        KeyTrans* ktr = KeyTrans::find(i);
        assert( ktr );
        TQString title=ktr->hdr().lower();
        kt_titles << title;
        kt_map[title] = ktr;
     }
     kt_titles.sort();
     for ( TQStringList::Iterator it = kt_titles.begin(); it != kt_titles.end(); ++it ) {
        KeyTrans* ktr = kt_map[*it];
        assert( ktr );
        TQString title=ktr->hdr();
        m_keytab->insertItem(title.replace('&',"&&"),ktr->numb());
     }
  }

  applySettingsToGUI();

  TQTimer::singleShot( 0, this, TQT_SLOT( autoShowShell() ) );
}

void konsolePart::autoShowShell()
{
    // possibly clear the screen?
    if (b_autoStartShell)
        showShell();
}

void konsolePart::setAutoDestroy( bool enabled )
{
    b_autoDestroy = enabled;
}

void konsolePart::setAutoStartShell( bool enabled )
{
    b_autoStartShell = enabled;
}

void konsolePart::doneSession(TESession*)
{
  // see doneSession in konsole.cpp
  if (se && b_autoDestroy)
  {
//    kdDebug(1211) << "doneSession - disconnecting done" << endl;
    disconnect( se,TQT_SIGNAL(done(TESession*)),
                this,TQT_SLOT(doneSession(TESession*)) );
    se->setConnect(false);
    //TQTimer::singleShot(100,se,TQT_SLOT(terminate()));
//    kdDebug(1211) << "se->terminate()" << endl;
    se->terminate();
  }
}

void konsolePart::sessionDestroyed()
{
//  kdDebug(1211) << "sessionDestroyed()" << endl;
  disconnect( se, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( sessionDestroyed() ) );
  se = 0;
  if (b_autoDestroy)
      delete this;
}

void konsolePart::configureRequest(TEWidget*_te,int,int x,int y)
{
  if (m_popupMenu)
     m_popupMenu->popup(_te->mapToGlobal(TQPoint(x,y)));
}

konsolePart::~konsolePart()
{
//  kdDebug(1211) << "konsolePart::~konsolePart() this=" << this << endl;
  if ( se ) {
    setAutoDestroy(false);
    se->closeSession();

    // Wait a bit for all childs to clean themselves up.
    while(se && TDEProcessController::theTDEProcessController->waitForProcessExit(1))
        ;

    disconnect( se, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( sessionDestroyed() ) );
//    kdDebug(1211) << "Deleting se session" << endl;
    delete se;
    se=0;
  }

  if (colors) delete colors;
  colors=0;

  //te is deleted by the framework
}

bool konsolePart::openURL( const KURL & url )
{
  //kdDebug(1211) << "konsolePart::openURL " << url.prettyURL() << endl;

  if (currentURL==url) {
    emit completed();
    return true;
  }

  m_url = url;
  emit setWindowCaption( url.prettyURL() );
//  kdDebug(1211) << "Set Window Caption to " << url.prettyURL() << "\n";
  emit started( 0 );

  if ( url.isLocalFile() ) {
      struct stat buff;
      stat( TQFile::encodeName( url.path() ), &buff );
      TQString text = ( S_ISDIR( buff.st_mode ) ? url.path() : url.directory() );
      showShellInDir( text );
  }

  emit completed();
  return true;
}

void konsolePart::emitOpenURLRequest(const TQString &cwd)
{
  KURL url;
  url.setPath(cwd);
  if (url==currentURL)
    return;
  currentURL=url;
  m_extension->emitOpenURLRequest(url);
}


void konsolePart::makeGUI()
{
  if (!kapp->authorizeTDEAction("konsole_rmb"))
     return;

  actions = new TDEActionCollection( (TDEMainWindow*)parentWidget );
  settingsActions = new TDEActionCollection( (TDEMainWindow*)parentWidget );

  // Send Signal Menu -------------------------------------------------------------
  if (kapp->authorizeTDEAction("send_signal"))
  {
     m_signals = new TDEPopupMenu((TDEMainWindow*)parentWidget);
     m_signals->insertItem( i18n( "&Suspend Task" )   + " (STOP)", SIGSTOP);
     m_signals->insertItem( i18n( "&Continue Task" )  + " (CONT)", SIGCONT);
     m_signals->insertItem( i18n( "&Hangup" )         + " (HUP)",   SIGHUP);
     m_signals->insertItem( i18n( "&Interrupt Task" ) + " (INT)",   SIGINT);
     m_signals->insertItem( i18n( "&Terminate Task" ) + " (TERM)", SIGTERM);
     m_signals->insertItem( i18n( "&Kill Task" )      + " (KILL)",  SIGKILL);
     m_signals->insertItem( i18n( "User Signal &1")   + " (USR1)", SIGUSR1);
     m_signals->insertItem( i18n( "User Signal &2")   + " (USR2)", SIGUSR2);
     connect(m_signals, TQT_SIGNAL(activated(int)), TQT_SLOT(sendSignal(int)));
  }

  // Settings Menu ----------------------------------------------------------------
  if (kapp->authorizeTDEAction("settings"))
  {
     m_options = new TDEPopupMenu((TDEMainWindow*)parentWidget);

     // Scrollbar
     selectScrollbar = new TDESelectAction(i18n("Sc&rollbar"), 0, this,
                                      TQT_SLOT(slotSelectScrollbar()), settingsActions);

     TQStringList scrollitems;
     scrollitems << i18n("&Hide") << i18n("&Left") << i18n("&Right");
     selectScrollbar->setItems(scrollitems);
     selectScrollbar->plug(m_options);

     // Select Bell
     m_options->insertSeparator();
     selectBell = new TDESelectAction(i18n("&Bell"), SmallIconSet( "bell"), 0 , this,
                                 TQT_SLOT(slotSelectBell()), settingsActions, "bell");

     TQStringList bellitems;
     bellitems << i18n("System &Bell")
            << i18n("System &Notification")
            << i18n("&Visible Bell")
            << i18n("N&one");
     selectBell->setItems(bellitems);
     selectBell->plug(m_options);

      m_fontsizes = new TDEActionMenu( i18n( "Font" ), SmallIconSet( "text" ), settingsActions, 0L );
      m_fontsizes->insert( new TDEAction( i18n( "&Enlarge Font" ), SmallIconSet( "viewmag+" ), 0, this, TQT_SLOT( biggerFont() ), settingsActions, "enlarge_font" ) );
      m_fontsizes->insert( new TDEAction( i18n( "&Shrink Font" ), SmallIconSet( "viewmag-" ), 0, this, TQT_SLOT( smallerFont() ), settingsActions, "shrink_font" ) );
      m_fontsizes->insert( new TDEAction( i18n( "Se&lect..." ), SmallIconSet( "font" ), 0, this, TQT_SLOT( slotSelectFont() ), settingsActions, "select_font" ) );
      m_fontsizes->plug(m_options);

      // encoding menu, start with default checked !
      selectSetEncoding = new TDESelectAction( i18n( "&Encoding" ), SmallIconSet("charset" ), 0, this, TQT_SLOT(slotSetEncoding()), settingsActions, "set_encoding" );
      TQStringList list = TDEGlobal::charsets()->descriptiveEncodingNames();
      list.prepend( i18n( "Default" ) );
      selectSetEncoding->setItems(list);
      selectSetEncoding->setCurrentItem (0);
      selectSetEncoding->plug(m_options);

     // Keyboard Options Menu ---------------------------------------------------
     if (kapp->authorizeTDEAction("keyboard"))
     {
        m_keytab = new TDEPopupMenu((TDEMainWindow*)parentWidget);
        m_keytab->setCheckable(true);
        connect(m_keytab, TQT_SIGNAL(activated(int)), TQT_SLOT(keytab_menu_activated(int)));
        m_options->insertItem( SmallIconSet( "key_bindings" ), i18n( "&Keyboard" ), m_keytab );
     }

     // Schema Options Menu -----------------------------------------------------
     if (kapp->authorizeTDEAction("schema"))
     {
        m_schema = new TDEPopupMenu((TDEMainWindow*)parentWidget);
        m_schema->setCheckable(true);
        connect(m_schema, TQT_SIGNAL(activated(int)), TQT_SLOT(schema_menu_activated(int)));
        connect(m_schema, TQT_SIGNAL(aboutToShow()), TQT_SLOT(schema_menu_check()));
        m_options->insertItem( SmallIconSet( "colorize" ), i18n( "Sch&ema" ), m_schema);
     }


     TDEAction *historyType = new TDEAction(i18n("&History..."), "history", 0, this,
                                        TQT_SLOT(slotHistoryType()), settingsActions, "history");
     historyType->plug(m_options);
     m_options->insertSeparator();

     // Select line spacing
     selectLineSpacing = new TDESelectAction(i18n("Li&ne Spacing"),
        SmallIconSet("leftjust"), 0, this,
        TQT_SLOT(slotSelectLineSpacing()), settingsActions );

     TQStringList lineSpacingList;
     lineSpacingList
       << i18n("&0")
       << i18n("&1")
       << i18n("&2")
       << i18n("&3")
       << i18n("&4")
       << i18n("&5")
       << i18n("&6")
       << i18n("&7")
       << i18n("&8");
     selectLineSpacing->setItems(lineSpacingList);
     selectLineSpacing->plug(m_options);

     // Blinking Cursor
     blinkingCursor = new TDEToggleAction (i18n("Blinking &Cursor"),
                                      0, this,TQT_SLOT(slotBlinkingCursor()), settingsActions);
     blinkingCursor->plug(m_options);

     // Frame on/off
     showFrame = new TDEToggleAction(i18n("Show Fr&ame"), 0,
                                this, TQT_SLOT(slotToggleFrame()), settingsActions);
     showFrame->setCheckedState(i18n("Hide Fr&ame"));
     showFrame->plug(m_options);

     // Word Connectors
     TDEAction *WordSeps = new TDEAction(i18n("Wor&d Connectors..."), 0, this,
                                  TQT_SLOT(slotWordSeps()), settingsActions);
     WordSeps->plug(m_options);

     // Use Konsole's Settings
     m_options->insertSeparator();
     m_useKonsoleSettings = new TDEToggleAction( i18n("&Use Konsole's Settings"),
                          0, this, TQT_SLOT(slotUseKonsoleSettings()), 0, "use_konsole_settings" );
     m_useKonsoleSettings->plug(m_options);

     // Save Settings
     m_options->insertSeparator();
     TDEAction *saveSettings = new TDEAction(i18n("&Save as Default"), "filesave", 0, this, 
                    TQT_SLOT(saveProperties()), actions, "save_default");
     saveSettings->plug(m_options);
     if (TDEGlobalSettings::insertTearOffHandle())
        m_options->insertTearOffHandle();
  }

  // Popup Menu -------------------------------------------------------------------
  m_popupMenu = new TDEPopupMenu((TDEMainWindow*)parentWidget);
  TDEAction* selectionEnd = new TDEAction(i18n("Set Selection End"), 0, TQT_TQOBJECT(te),
                               TQT_SLOT(setSelectionEnd()), actions, "selection_end");
  selectionEnd->plug(m_popupMenu);

  TDEAction *copyClipboard = new TDEAction(i18n("&Copy"), "editcopy", 0,
                                        TQT_TQOBJECT(te), TQT_SLOT(copyClipboard()), actions, "edit_copy");
  copyClipboard->plug(m_popupMenu);

  TDEAction *pasteClipboard = new TDEAction(i18n("&Paste"), "editpaste", 0,
                                        TQT_TQOBJECT(te), TQT_SLOT(pasteClipboard()), actions, "edit_paste");
  pasteClipboard->plug(m_popupMenu);

  if (m_signals)
  {
     m_popupMenu->insertItem(i18n("&Send Signal"), m_signals);
     m_popupMenu->insertSeparator();
  }

  if (m_options)
  {
     m_popupMenu->insertItem(i18n("S&ettings"), m_options);
     m_popupMenu->insertSeparator();
  }

  TDEAction *closeSession = new TDEAction(i18n("&Close Terminal Emulator"), "fileclose", 0, this,
                                      TQT_SLOT(closeCurrentSession()), actions, "close_session");
  closeSession->plug(m_popupMenu);
  if (TDEGlobalSettings::insertTearOffHandle())
    m_popupMenu->insertTearOffHandle();
}

void konsolePart::applySettingsToGUI()
{
  m_useKonsoleSettings->setChecked( b_useKonsoleSettings );
  setSettingsMenuEnabled( !b_useKonsoleSettings );

  applyProperties();

  if ( b_useKonsoleSettings )
    return; // Don't change Settings menu items

  if (showFrame)
     showFrame->setChecked( b_framevis );
  if (selectScrollbar)
     selectScrollbar->setCurrentItem(n_scroll);
  updateKeytabMenu();
  if (selectBell)
     selectBell->setCurrentItem(n_bell);
  if (selectLineSpacing)
     selectLineSpacing->setCurrentItem(te->lineSpacing());
  if (blinkingCursor)
     blinkingCursor->setChecked(te->blinkingCursor());
  if (m_schema)
     m_schema->setItemChecked(curr_schema,true);
  if (selectSetEncoding)
     selectSetEncoding->setCurrentItem(n_encoding);
}

void konsolePart::applyProperties()
{
   if ( !se ) return;

   if ( b_histEnabled && m_histSize )
      se->setHistory( HistoryTypeBuffer(m_histSize ) );
   else if ( b_histEnabled && !m_histSize )
      se->setHistory(HistoryTypeFile() );
   else
     se->setHistory( HistoryTypeNone() );
   se->setKeymapNo( n_keytab );

   // FIXME:  Move this somewhere else...
   TDEConfig* config = new TDEConfig("konsolerc",true);
   config->setGroup("UTMP");
   se->setAddToUtmp( config->readBoolEntry("AddToUtmp",true));
   delete config;

   se->widget()->setVTFont( defaultFont );
   se->setSchemaNo( curr_schema );
   slotSetEncoding();
}

void konsolePart::setSettingsMenuEnabled( bool enable )
{
   uint count = settingsActions->count();
   for ( uint i = 0; i < count; i++ )
   {
      settingsActions->action( i )->setEnabled( enable );
   }

   // FIXME: These are not in settingsActions.
   //  When disabled, the icons are not 'grey-ed' out.
   m_keytab->setEnabled( enable );
   m_schema->setEnabled( enable );
}

void konsolePart::readProperties()
{
  TDEConfig* config;

  if ( b_useKonsoleSettings )
    config = new TDEConfig( "konsolerc", true );
  else
    config = new TDEConfig( "konsolepartrc", true );

  config->setDesktopGroup();

  b_framevis = config->readBoolEntry("has frame",false);
  b_histEnabled = config->readBoolEntry("historyenabled",true);
  n_bell = TQMIN(config->readUnsignedNumEntry("bellmode",TEWidget::BELLSYSTEM),3);
  n_keytab=config->readNumEntry("keytab",0); // act. the keytab for this session
  n_scroll = TQMIN(config->readUnsignedNumEntry("scrollbar",TEWidget::SCRRIGHT),2);
  m_histSize = config->readNumEntry("history",DEFAULT_HISTORY_SIZE);
  s_word_seps= config->readEntry("wordseps",":@-./_~");

  n_encoding = config->readNumEntry("encoding",0);

  TQFont tmpFont = TDEGlobalSettings::fixedFont();
  defaultFont = config->readFontEntry("defaultfont", &tmpFont);

  TQString schema = config->readEntry("Schema");

  s_tdeconfigSchema=config->readEntry("schema");
  ColorSchema* sch = colors->find(schema.isEmpty() ? s_tdeconfigSchema : schema);
  if (!sch) {
    sch=(ColorSchema*)colors->at(0);  //the default one
  }
  if (sch->hasSchemaFileChanged()) sch->rereadSchemaFile();
  s_schema = sch->relPath();
  curr_schema = sch->numb();
  pmPath = sch->imagePath();
  te->setColorTable(sch->table()); //FIXME: set twice here to work around a bug

  if (sch->useTransparency()) {
    if (!argb_visual) {
      if (!rootxpm)
        rootxpm = new KRootPixmap(TQT_TQWIDGET(te));
      rootxpm->setFadeEffect(sch->tr_x(), TQColor(sch->tr_r(), sch->tr_g(), sch->tr_b()));
      rootxpm->start();
      rootxpm->repaint(true);
    }
    else {
      te->setBlendColor(tqRgba(sch->tr_r(), sch->tr_g(), sch->tr_b(), int(sch->tr_x() * 255)));
      te->setErasePixmap( TQPixmap() ); // make sure any background pixmap is unset
    }
  }
  else {
    if (rootxpm) {
      rootxpm->stop();
      delete rootxpm;
      rootxpm=0;
    }
    pixmap_menu_activated(sch->alignment());
  }

  te->setBellMode(n_bell);
  te->setBlinkingCursor(config->readBoolEntry("BlinkingCursor",false));
  te->setFrameStyle( b_framevis?(TQFrame::WinPanel|TQFrame::Sunken):TQFrame::NoFrame );
  te->setLineSpacing( config->readUnsignedNumEntry( "LineSpacing", 0 ) );
  te->setScrollbarLocation(n_scroll);
  te->setWordCharacters(s_word_seps);

  delete config;

  config = new TDEConfig("konsolerc",true);
  config->setDesktopGroup();
  te->setTerminalSizeHint( config->readBoolEntry("TerminalSizeHint",true) );
  delete config;
}

void konsolePart::saveProperties()
{
  TDEConfig* config = new TDEConfig("konsolepartrc");
  config->setDesktopGroup();

  if ( b_useKonsoleSettings ) { // Don't save Settings if using konsolerc
    config->writeEntry("use_konsole_settings", m_useKonsoleSettings->isChecked());
  } else {
    config->writeEntry("bellmode",n_bell);
    config->writeEntry("BlinkingCursor", te->blinkingCursor());
    config->writeEntry("defaultfont", (se->widget())->getVTFont());
    config->writeEntry("history", se->history().getSize());
    config->writeEntry("historyenabled", b_histEnabled);
    config->writeEntry("keytab",n_keytab);
    config->writeEntry("has frame",b_framevis);
    config->writeEntry("LineSpacing", te->lineSpacing());
    config->writeEntry("schema",s_tdeconfigSchema);
    config->writeEntry("scrollbar",n_scroll);
    config->writeEntry("wordseps",s_word_seps);
    config->writeEntry("encoding",n_encoding);
    config->writeEntry("use_konsole_settings",m_useKonsoleSettings->isChecked());
  }

  config->sync();
  delete config;
}

void konsolePart::sendSignal(int sn)
{
  if (se) se->sendSignal(sn);
}

void konsolePart::closeCurrentSession()
{
  if ( se ) se->closeSession();
}

void konsolePart::slotToggleFrame()
{
  b_framevis = showFrame->isChecked();
  te->setFrameStyle( b_framevis?(TQFrame::WinPanel|TQFrame::Sunken):TQFrame::NoFrame);
}

void konsolePart::slotSelectScrollbar()
{
  if ( ! se ) return;
  n_scroll = selectScrollbar->currentItem();
  te->setScrollbarLocation(n_scroll);
}

void konsolePart::slotSelectFont() {
   if ( !se ) return;

   TQFont font = se->widget()->getVTFont();
   if ( TDEFontDialog::getFont( font, true ) != TQDialog::Accepted )
      return;

   se->widget()->setVTFont( font );
}

void konsolePart::biggerFont(void) {
    if ( !se ) return;

    TQFont f = te->getVTFont();
    f.setPointSize( f.pointSize() + 1 );
    te->setVTFont( f );
}

void konsolePart::smallerFont(void) {
    if ( !se ) return;

    TQFont f = te->getVTFont();
    if ( f.pointSize() < 6 ) return;      // A minimum size
    f.setPointSize( f.pointSize() - 1 );
    te->setVTFont( f );
}

void konsolePart::updateKeytabMenu()
{
  if ( se && m_keytab ) {
    m_keytab->setItemChecked(n_keytab,false);
    m_keytab->setItemChecked(se->keymapNo(),true);
    n_keytab = se->keymapNo();
  } else if ( m_keytab ) {    // no se yet, happens at startup
    m_keytab->setItemChecked(n_keytab, true);
  }
}

void konsolePart::keytab_menu_activated(int item)
{
  if ( ! se ) return;
  se->setKeymapNo(item);
  updateKeytabMenu();
}

void konsolePart::schema_menu_activated(int item)
{
  setSchema(item);
  s_tdeconfigSchema = s_schema; // This is the new default
}

void konsolePart::schema_menu_check()
{
  if (colors->checkSchemas()) {
    colors->sort();
    updateSchemaMenu();
  }
}

void konsolePart::updateSchemaMenu()
{
  if (!m_schema) return;

  m_schema->clear();
  for (int i = 0; i < (int) colors->count(); i++)  {
    ColorSchema* s = (ColorSchema*)colors->at(i);
    TQString title=s->title();
    m_schema->insertItem(title.replace('&',"&&"),s->numb(),0);
  }

  if (te && se) {
    m_schema->setItemChecked(se->schemaNo(),true);
  }
}

void konsolePart::setSchema(int numb)
{
  ColorSchema* s = colors->find(numb);
  if (!s) {
    kdWarning() << "No schema found. Using default." << endl;
    s=(ColorSchema*)colors->at(0);
  }
  if (s->numb() != numb)  {
    kdWarning() << "No schema with number " << numb << endl;
  }

  if (s->hasSchemaFileChanged()) {
    const_cast<ColorSchema *>(s)->rereadSchemaFile();
  }
  if (s) setSchema(s);
}

void konsolePart::setSchema(ColorSchema* s)
{
  if (!se) return;
  if (!s) return;

  if (m_schema) {
    m_schema->setItemChecked(curr_schema,false);
    m_schema->setItemChecked(s->numb(),true);
  }

  s_schema = s->relPath();
  curr_schema = s->numb();
  pmPath = s->imagePath();
  te->setColorTable(s->table()); //FIXME: set twice here to work around a bug

  if (s->useTransparency()) {
    if (!argb_visual) {
      if (!rootxpm)
        rootxpm = new KRootPixmap(TQT_TQWIDGET(te));
      rootxpm->setFadeEffect(s->tr_x(), TQColor(s->tr_r(), s->tr_g(), s->tr_b()));
      rootxpm->start();
      rootxpm->repaint(true);
    }
    else {
      te->setBlendColor(tqRgba(s->tr_r(), s->tr_g(), s->tr_b(), int(s->tr_x() * 255)));
      te->setErasePixmap( TQPixmap() ); // make sure any background pixmap is unset
    }
  }
  else {
    if (rootxpm) {
      rootxpm->stop();
      delete rootxpm;
      rootxpm=0;
    }
    pixmap_menu_activated(s->alignment());
  }

  te->setColorTable(s->table());
  se->setSchemaNo(s->numb());
}

void konsolePart::notifySize(int /* columns */, int /* lines */)
{
  ColorSchema *sch=colors->find(s_schema);

  if (sch && sch->alignment() >= 3)
    pixmap_menu_activated(sch->alignment());
}

void konsolePart::pixmap_menu_activated(int item)
{
  if (item <= 1) pmPath = "";
  TQPixmap pm(pmPath);
  if (pm.isNull()) {
    pmPath = "";
    item = 1;
    te->setBackgroundColor(te->getDefaultBackColor());
    return;
  }
  // FIXME: respect scrollbar (instead of te->size)
  n_render= item;
  switch (item) {
    case 1: // none
    case 2: // tile
            te->setBackgroundPixmap(pm);
    break;
    case 3: // center
            { TQPixmap bgPixmap;
              bgPixmap.resize(te->size());
              bgPixmap.fill(te->getDefaultBackColor());
              bitBlt( &bgPixmap, ( te->size().width() - pm.width() ) / 2,
                                ( te->size().height() - pm.height() ) / 2,
                      &pm, 0, 0,
                      pm.width(), pm.height() );

              te->setBackgroundPixmap(bgPixmap);
            }
    break;
    case 4: // full
            {
              float sx = (float)te->size().width() / pm.width();
              float sy = (float)te->size().height() / pm.height();
              TQWMatrix matrix;
              matrix.scale( sx, sy );
              te->setBackgroundPixmap(pm.xForm( matrix ));
            }
    break;
    default: // oops
             n_render = 1;
  }
}

void konsolePart::slotHistoryType()
{
  if ( ! se ) return;
  HistoryTypeDialog dlg(se->history(), m_histSize, (TDEMainWindow*)parentWidget);
  if (dlg.exec()) {
    if (dlg.isOn()) {
      if (dlg.nbLines() > 0) {
        se->setHistory(HistoryTypeBuffer(dlg.nbLines()));
        m_histSize = dlg.nbLines();
        b_histEnabled = true;
      }
      else {
        se->setHistory(HistoryTypeFile());
        m_histSize = 0;
        b_histEnabled = true;
      }
    }
    else {
      se->setHistory(HistoryTypeNone());
      m_histSize = dlg.nbLines();
      b_histEnabled = false;
    }
  }
}

void konsolePart::slotSelectBell() {
  n_bell = selectBell->currentItem();
  te->setBellMode(n_bell);
}

void konsolePart::slotSetEncoding()
{
  if (!se) return;

  bool found;
  TQString enc = TDEGlobal::charsets()->encodingForName(selectSetEncoding->currentText());
  TQTextCodec * qtc = TDEGlobal::charsets()->codecForName(enc, found);
  if(!found)
  {
    kdDebug() << "Codec " << selectSetEncoding->currentText() << " not found!" << endl;
    qtc = TQTextCodec::codecForLocale();
  }

  n_encoding = selectSetEncoding->currentItem();
  se->setEncodingNo(selectSetEncoding->currentItem());
  se->getEmulation()->setCodec(qtc);
}

void konsolePart::slotSelectLineSpacing()
{
  te->setLineSpacing( selectLineSpacing->currentItem() );
}

void konsolePart::slotBlinkingCursor()
{
  te->setBlinkingCursor(blinkingCursor->isChecked());
}

void konsolePart::slotUseKonsoleSettings()
{
   b_useKonsoleSettings = m_useKonsoleSettings->isChecked();

   setSettingsMenuEnabled( !b_useKonsoleSettings );

   readProperties();

   applySettingsToGUI();
}

void konsolePart::slotWordSeps() {
  bool ok;

  TQString seps = KInputDialog::getText( i18n( "Word Connectors" ),
      i18n( "Characters other than alphanumerics considered part of a word when double clicking:" ), s_word_seps, &ok, parentWidget );
  if ( ok )
  {
    s_word_seps = seps;
    te->setWordCharacters(s_word_seps);
  }
}

void konsolePart::enableMasterModeConnections()
{
  if ( se ) se->setListenToKeyPress(true);
}

void konsolePart::updateTitle(TESession *)
{
  if ( se ) emit setWindowCaption( se->fullTitle() );
}

void konsolePart::guiActivateEvent( KParts::GUIActivateEvent * )
{
    // Don't let ReadOnlyPart::guiActivateEvent reset the window caption
}

bool konsolePart::doOpenStream( const TQString& )
{
	return m_streamEnabled;
}

bool konsolePart::doWriteStream( const TQByteArray& data )
{
	if ( m_streamEnabled )
	{
		TQString cmd = TQString::fromLocal8Bit( data.data(), data.size() );
		se->sendSession( cmd );
		return true;
	}
	return false;
}

bool konsolePart::doCloseStream()
{
	return m_streamEnabled;
}

//////////////////////////////////////////////////////////////////////

HistoryTypeDialog::HistoryTypeDialog(const HistoryType& histType,
                                     unsigned int histSize,
                                     TQWidget *parent)
  : KDialogBase(Plain, i18n("History Configuration"),
                Help | Default | Ok | Cancel, Ok,
                parent)
{
  TQFrame *mainFrame = plainPage();

  TQHBoxLayout *hb = new TQHBoxLayout(mainFrame);

  m_btnEnable    = new TQCheckBox(i18n("&Enable"), mainFrame);

  TQObject::connect(m_btnEnable, TQT_SIGNAL(toggled(bool)),
                   this,      TQT_SLOT(slotHistEnable(bool)));

  m_size = new TQSpinBox(0, 10 * 1000 * 1000, 100, mainFrame);
  m_size->setValue(histSize);
  m_size->setSpecialValueText(i18n("Unlimited (number of lines)", "Unlimited"));

  m_setUnlimited = new TQPushButton(i18n("&Set Unlimited"), mainFrame);
  connect( m_setUnlimited,TQT_SIGNAL(clicked()), this,TQT_SLOT(slotSetUnlimited()) );

  hb->addWidget(m_btnEnable);
  hb->addSpacing(10);
  hb->addWidget(new TQLabel(i18n("Number of lines:"), mainFrame));
  hb->addWidget(m_size);
  hb->addSpacing(10);
  hb->addWidget(m_setUnlimited);

  if ( ! histType.isOn()) {
    m_btnEnable->setChecked(false);
    slotHistEnable(false);
  } else {
    m_btnEnable->setChecked(true);
    m_size->setValue(histType.getSize());
    slotHistEnable(true);
  }
  setHelp("configure-history");
}

void HistoryTypeDialog::slotDefault()
{
  m_btnEnable->setChecked(true);
  m_size->setValue(DEFAULT_HISTORY_SIZE);
  slotHistEnable(true);
}

void HistoryTypeDialog::slotHistEnable(bool b)
{
  m_size->setEnabled(b);
  m_setUnlimited->setEnabled(b);
  if (b) m_size->setFocus();
}

void HistoryTypeDialog::slotSetUnlimited()
{
  m_size->setValue(0);
}

unsigned int HistoryTypeDialog::nbLines() const
{
  return m_size->value();
}

bool HistoryTypeDialog::isOn() const
{
  return m_btnEnable->isChecked();
}

konsoleBrowserExtension::konsoleBrowserExtension(konsolePart *parent)
  : KParts::BrowserExtension(parent, "konsoleBrowserExtension")
{
}

konsoleBrowserExtension::~konsoleBrowserExtension()
{
}

void konsoleBrowserExtension::emitOpenURLRequest(const KURL &url)
{
  emit openURLRequest(url);
}

const char* sensibleShell()
{
  const char* shell = getenv("SHELL");
  if (shell == NULL || *shell == '\0') shell = "/bin/sh";
  return shell;
}

void konsolePart::startProgram( const TQString& program,
                                const TQStrList& args )
{
//    kdDebug(1211) << "konsolePart::startProgram for " << program << endl;
    if ( !se )
        newSession();
    se->setProgram( program, args );
    se->run();
}

bool konsolePart::setPtyFd( int master_pty )
{
   kdDebug(1211) << "konsolePart::setPtyFd " << master_pty << endl;
   TEPty *pty = new TEPty();
   pty->setPtyFd(master_pty);
   if ( !se )
      newSession();
   se->setPty(pty);
}

void konsolePart::newSession()
{
  if ( se ) delete se;
  se = new TESession(te, "xterm", parentWidget->winId());
  connect( se,TQT_SIGNAL(done(TESession*)),
           this,TQT_SLOT(doneSession(TESession*)) );
  connect( se,TQT_SIGNAL(openURLRequest(const TQString &)),
           this,TQT_SLOT(emitOpenURLRequest(const TQString &)) );
  connect( se, TQT_SIGNAL( updateTitle(TESession*) ),
           this, TQT_SLOT( updateTitle(TESession*) ) );
  connect( se, TQT_SIGNAL(enableMasterModeConnections()),
           this, TQT_SLOT(enableMasterModeConnections()) );
  connect( se, TQT_SIGNAL( processExited(TDEProcess *) ),
           this, TQT_SIGNAL( processExited(TDEProcess *) ) );
  connect( se, TQT_SIGNAL( receivedData( const TQString& ) ),
           this, TQT_SIGNAL( receivedData( const TQString& ) ) );
  connect( se, TQT_SIGNAL( forkedChild() ),
           this, TQT_SIGNAL( forkedChild() ));

  // We ignore the following signals
  //connect( se, TQT_SIGNAL(renameSession(TESession*,const TQString&)),
  //         this, TQT_SLOT(slotRenameSession(TESession*, const TQString&)) );
  //connect( se->getEmulation(), TQT_SIGNAL(changeColumns(int)),
  //         this, TQT_SLOT(changeColumns(int)) );
  //connect( se, TQT_SIGNAL(disableMasterModeConnections()),
  //        this, TQT_SLOT(disableMasterModeConnections()) );

  applyProperties();

  se->setConnect(true);
  // se->run();
  connect( se, TQT_SIGNAL( destroyed() ), this, TQT_SLOT( sessionDestroyed() ) );
//  setFont( n_font ); // we do this here, to make TEWidget recalculate
                     // its geometry..
}

void konsolePart::showShellInDir( const TQString& dir )
{
  if ( ! m_runningShell )
  {
    const char* s = sensibleShell();
    TQStrList args;
    args.append( s );
    startProgram( s, args );
    m_runningShell = true;
  };

  if ( ! dir.isNull() )
  {
      TQString text = dir;
      KRun::shellQuote(text);
      text = TQString::fromLatin1("cd ") + text + '\n';
      te->emitText( text );
  };
}

void konsolePart::showShell()
{
    if ( ! se ) showShellInDir( TQString::null );
}

void konsolePart::sendInput( const TQString& text )
{
    te->emitText( text );
}

#include "konsole_part.moc"