summaryrefslogtreecommitdiffstats
path: root/parts/snippet/snippet_widget.cpp
blob: 6a83681e961c0171772966a3448e8a315936a074 (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
/*
 *  File : snippet_widget.cpp
 *
 *  Author: Robert Gruber <rgruber@users.sourceforge.net>
 *
 *  Copyright: See COPYING file that comes with this distribution
 */

#include <kparts/part.h>
#include <klibloader.h>
#include <kurl.h>
#include <kdebug.h>
#include <klocale.h>
#include <tqlayout.h>
#include <kpushbutton.h>
#include <klistview.h>
#include <tqheader.h>
#include <klineedit.h>
#include <ktextedit.h>
#include <kmessagebox.h>
#include <tqsplitter.h>
#include <ktexteditor/editinterface.h>
#include <ktexteditor/editor.h>
#include <ktexteditor/viewcursorinterface.h>
#include <ktexteditor/document.h>
#include <kconfig.h>
#include <tqtooltip.h>
#include <kpopupmenu.h>
#include <tqregexp.h>
#include <tqinputdialog.h>
#include <tqlabel.h>
#include <tqcheckbox.h>
#include <tqwhatsthis.h>
#include <tqdragobject.h>
#include <tqtimer.h>
#include <kcombobox.h>
#include <kdeversion.h>

#include <kdevcore.h>
#include <kdevproject.h>
#include <kdevpartcontroller.h>

#include "snippetdlg.h"
#include "snippetitem.h"

#include "snippet_part.h"
#include "snippet_widget.h"

SnippetWidget::SnippetWidget(SnippetPart *part)
		: KListView(0, "snippet widget"), TQToolTip( viewport() ),
		m_part( part )
{
    // init the TQPtrList
    _list.setAutoDelete(TRUE);

    // init the KListView
    setSorting( -1 );
    addColumn( "" );
    setFullWidth(true);
    header()->hide();
    setAcceptDrops(true);
    setDragEnabled(false);
    setDropVisualizer(false);
    setRootIsDecorated(true);

    //connect the signals
    connect( this, TQT_SIGNAL( contextMenuRequested ( TQListViewItem *, const TQPoint & , int ) ),
             this, TQT_SLOT( showPopupMenu(TQListViewItem *, const TQPoint & , int ) ) );

    connect( this, TQT_SIGNAL( executed (TQListViewItem *) ),
             this, TQT_SLOT( slotExecuted( TQListViewItem *) ) );
    connect( this, TQT_SIGNAL( returnPressed (TQListViewItem *) ),
             this, TQT_SLOT( slotExecuted( TQListViewItem *) ) );

    connect( this, TQT_SIGNAL( dropped(TQDropEvent *, TQListViewItem *) ),
             this, TQT_SLOT( slotDropped(TQDropEvent *, TQListViewItem *) ) );

    _cfg = 0;

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

SnippetWidget::~SnippetWidget()
{
  writeConfig();
  delete _cfg;

  /* We need to delete the child items before the tqparent items
     otherwise KDevelop would crash on exiting */
  SnippetItem * item;
  while (_list.count() > 0) {
    for (item=_list.first(); item; item=_list.next()) {
      if (item->childCount() == 0)
          _list.remove(item);
    }
  }
}


/*!
    \fn SnippetWidget::slotAdd()
    Opens the didalog to add a snippet
 */
void SnippetWidget::slotAdd()
{
  kdDebug(9035) << "Ender slotAdd()" << endl;
  SnippetDlg dlg(this, "SnippetDlg", true);

  /*check if the user clicked a SnippetGroup
    If not, we set the group variable to the SnippetGroup
    which the selected item is a child of*/
  SnippetGroup * group = dynamic_cast<SnippetGroup*>(selectedItem());
  if (!group)
    group = dynamic_cast<SnippetGroup*>(selectedItem()->tqparent());

  /*fill the combobox with the names of all SnippetGroup entries*/
  for (SnippetItem *it=_list.first(); it; it=_list.next()) {
    if (dynamic_cast<SnippetGroup*>(it)) {
      dlg.cbGroup->insertItem(it->getName());
    }
  }
  dlg.cbGroup->setCurrentText(group->getName());

  if (dlg.exec() == TQDialog::Accepted) {
      group = dynamic_cast<SnippetGroup*>(SnippetItem::findItemByName(dlg.cbGroup->currentText(), _list));
      _list.append( new SnippetItem(group, dlg.snippetName->text(), dlg.snippetText->text()) );
  }
}


/*!
    \fn SnippetWidget::slotAddGroup()
    Opens the didalog to add a snippet
 */
void SnippetWidget::slotAddGroup()
{
  kdDebug(9035) << "Ender slotAddGroup()" << endl;
  SnippetDlg dlg(this, "SnippetDlg", true);
  dlg.snippetText->setEnabled(false);
  dlg.snippetText->setText("GROUP");
  dlg.setCaption(i18n("Add Group"));
  dlg.cbGroup->insertItem(i18n("All"));
  dlg.cbGroup->insertStringList(m_part->getAllLanguages());
  dlg.cbGroup->setCurrentText(i18n("All"));
  dlg.textLabelGroup->setText(i18n("Language:"));

  if (dlg.exec() == TQDialog::Accepted) {
    _list.append( new SnippetGroup(this, dlg.snippetName->text(), SnippetGroup::getMaxId(), dlg.cbGroup->currentText()) );
  }
}


/*!
    \fn SnippetWidget::slotRemove()
    Removes the selected snippet
 */
void SnippetWidget::slotRemove()
{
  //get current data
  TQListViewItem * item = currentItem();
  SnippetItem *snip = dynamic_cast<SnippetItem*>( item );
  SnippetGroup *group = dynamic_cast<SnippetGroup*>( item );
  if (!snip)
    return;

  if (group) {
    if (group->childCount() > 0 &&
        KMessageBox::warningContinueCancel(this, i18n("Do you really want to remove this group and all its snippets?"),TQString(),KStdGuiItem::del())
        == KMessageBox::Cancel)
      return;

    for (SnippetItem *it=_list.first(); it; it=_list.next()) {
      if (it->getParent() == group->getId()) {
        kdDebug(9035) << "remove " << it->getName() << endl;
        _list.remove(it);
      }
    }
  }

  kdDebug(9035) << "remove " << snip->getName() << endl;
  _list.remove(snip);
}



/*!
    \fn SnippetWidget::slotEdit()
    Opens the dialog of editing the selected snippet
 */
void SnippetWidget::slotEdit()
{
  //get current data
  TQListViewItem * item = currentItem();

  SnippetGroup *pGroup = dynamic_cast<SnippetGroup*>(item);
  SnippetItem *pSnippet = dynamic_cast<SnippetItem*>( item );
  if (!pSnippet || pGroup) /*selected item must be a SnippetItem but MUST not be a SnippetGroup*/
    return;

  //init the dialog
  SnippetDlg dlg(this, "SnippetDlg", true);
  dlg.snippetName->setText(pSnippet->getName());
  dlg.snippetText->setText(pSnippet->getText());
  dlg.btnAdd->setText(i18n("&Apply"));

  dlg.setCaption(i18n("Edit Snippet"));
  /*fill the combobox with the names of all SnippetGroup entries*/
  for (SnippetItem *it=_list.first(); it; it=_list.next()) {
    if (dynamic_cast<SnippetGroup*>(it)) {
      dlg.cbGroup->insertItem(it->getName());
    }
  }
  dlg.cbGroup->setCurrentText(SnippetItem::findGroupById(pSnippet->getParent(), _list)->getName());

  if (dlg.exec() == TQDialog::Accepted) {
    //update the KListView and the SnippetItem
    item->setText( 0, dlg.snippetName->text() );
    pSnippet->setName( dlg.snippetName->text() );
    pSnippet->setText( dlg.snippetText->text() );

    /* if the user changed the tqparent we need to move the snippet */
    if ( SnippetItem::findGroupById(pSnippet->getParent(), _list)->getName() != dlg.cbGroup->currentText() ) {
      SnippetGroup * newGroup = dynamic_cast<SnippetGroup*>(SnippetItem::findItemByName(dlg.cbGroup->currentText(), _list));
      pSnippet->tqparent()->takeItem(pSnippet);
      newGroup->insertItem(pSnippet);
      pSnippet->resetParent();
    }

    setSelected(item, TRUE);
  }
}

/*!
    \fn SnippetWidget::slotEditGroup()
    Opens the dialog of editing the selected snippet-group
 */
void SnippetWidget::slotEditGroup()
{
  //get current data
  TQListViewItem * item = currentItem();

  SnippetGroup *pGroup = dynamic_cast<SnippetGroup*>( item );
  if (!pGroup) /*selected item MUST be a SnippetGroup*/
    return;

  //init the dialog
  SnippetDlg dlg(this, "SnippetDlg", true);
  dlg.snippetName->setText(pGroup->getName());
  dlg.snippetText->setText(pGroup->getText());
  dlg.btnAdd->setText(i18n("&Apply"));
  dlg.snippetText->setEnabled(FALSE);
  dlg.setCaption(i18n("Edit Group"));
  dlg.cbGroup->insertItem(i18n("All"));
  dlg.cbGroup->insertStringList(m_part->getAllLanguages());
  dlg.cbGroup->setCurrentText(pGroup->getLanguage());
  dlg.textLabelGroup->setText(i18n("Language:"));

  if (dlg.exec() == TQDialog::Accepted) {
    //update the KListView and the SnippetGroup
    item->setText( 0, dlg.snippetName->text() );
    pGroup->setName( dlg.snippetName->text() );
    pGroup->setLanguage(dlg.cbGroup->currentText());

    setSelected(item, TRUE);
  }
}

void SnippetWidget::slotExecuted(TQListViewItem * item)
{
  SnippetItem *pSnippet = dynamic_cast<SnippetItem*>( item );
  if (!pSnippet || dynamic_cast<SnippetGroup*>(item))
      return;

  //process variables if any, then insert into the active view
  insertIntoActiveView( parseText(pSnippet->getText(), _SnippetConfig.getDelimiter()) );
}


/*!
    \fn SnippetWidget::insertIntoActiveView(TQString text)
    Inserts the parameter text into the activ view
 */
void SnippetWidget::insertIntoActiveView(TQString text)
{
  //get the interfaces for the KTexteditor parts
  KTextEditor::ViewCursorInterface *cursorIface
	= dynamic_cast<KTextEditor::ViewCursorInterface*>(m_part->partController()->activeWidget());

  if (!cursorIface)
    return;

  KTextEditor::EditInterface* editIface
	= dynamic_cast<KTextEditor::EditInterface*>( m_part->partController()->activePart() );

  if (!editIface)
    return;

  uint line, col;
  cursorIface->cursorPositionReal(&line, &col);

  editIface->insertText( line, col , text );
}


/*!
    \fn SnippetWidget::writeConfig()
    Write the cofig file
 */
void SnippetWidget::writeConfig()
{
  if( !_cfg )
    return;
  _cfg->deleteGroup("SnippetPart");  //this is neccessary otherwise delete entries will stay in list until
                                     //they get overwritten by a more recent entry
  _cfg->setGroup("SnippetPart");

  SnippetItem *item;
  TQString strKeyName="";
  TQString strKeyText="";
  TQString strKeyId="";

  int iSnipCount = 0;
  int iGroupCount = 0;

  for ( item = _list.first(); item; item = _list.next() ) {  //write the snippet-list
    kdDebug(9035) << "SnippetWidget::writeConfig() " << item->getName() << endl;
    SnippetGroup * group = dynamic_cast<SnippetGroup*>(item);
    if (group) {
      kdDebug(9035) << "-->GROUP " << item->getName() << group->getId() << " " << iGroupCount<< endl;
      strKeyName=TQString("snippetGroupName_%1").tqarg(iGroupCount);
      strKeyId=TQString("snippetGroupId_%1").tqarg(iGroupCount);
      strKeyText=TQString("snippetGroupLang_%1").tqarg(iGroupCount);

      _cfg->writeEntry(strKeyName, group->getName());
      _cfg->writeEntry(strKeyId, group->getId());
      _cfg->writeEntry(strKeyText, group->getLanguage());
      iGroupCount++;
    } else if (dynamic_cast<SnippetItem*>(item)) {
      kdDebug(9035) << "-->ITEM " << item->getName() << item->getParent() << " " << iSnipCount << endl;
      strKeyName=TQString("snippetName_%1").tqarg(iSnipCount);
      strKeyText=TQString("snippetText_%1").tqarg(iSnipCount);
      strKeyId=TQString("snippetParent_%1").tqarg(iSnipCount);

      _cfg->writeEntry(strKeyName, item->getName());
      _cfg->writeEntry(strKeyText, item->getText());
      _cfg->writeEntry(strKeyId, item->getParent());
      iSnipCount++;
    } else {
      kdDebug(9035) << "-->ERROR " << item->getName() << endl;
    }
  }
  _cfg->writeEntry("snippetCount", iSnipCount);
  _cfg->writeEntry("snippetGroupCount", iGroupCount);

  int iCount = 1;
  TQMap<TQString, TQString>::Iterator it;
  for ( it = _mapSaved.begin(); it != _mapSaved.end(); ++it ) {  //write the saved variable values
    if (it.data().length()<=0) continue;  //is the saved value has no length -> no need to save it

    strKeyName=TQString("snippetSavedName_%1").tqarg(iCount);
    strKeyText=TQString("snippetSavedVal_%1").tqarg(iCount);

    _cfg->writeEntry(strKeyName, it.key());
    _cfg->writeEntry(strKeyText, it.data());

    iCount++;
  }
  _cfg->writeEntry("snippetSavedCount", iCount-1);


  _cfg->writeEntry( "snippetDelimiter", _SnippetConfig.getDelimiter() );
  _cfg->writeEntry( "snippetVarInput", _SnippetConfig.getInputMethod() );
  _cfg->writeEntry( "snippetToolTips", _SnippetConfig.useToolTips() );
  _cfg->writeEntry( "snippetGroupAutoOpen", _SnippetConfig.getAutoOpenGroups() );

  _cfg->writeEntry("snippetSingleRect", _SnippetConfig.getSingleRect() );
  _cfg->writeEntry("snippetMultiRect", _SnippetConfig.getMultiRect() );

  _cfg->sync();
}


/*!
    This function was introduced together with the grouping-feature.
    As far as some guys might have some snippets stored in the "old" way
    we need to create a "DEFAULT" group into which we can import all snippets
 */
void SnippetWidget::initConfigOldVersion(KConfig *cfg)
{
  SnippetGroup * group = new SnippetGroup(this, "DEFAULT", 1);
  _list.append(group);

  int iCount = cfg->readNumEntry("snippetCount", 0);
  TQString strKeyName="";
  TQString strKeyText="";
  for ( int i=0; i<iCount; i++) {  //read the snippet-list
    strKeyName=TQString("snippetName_%1").tqarg(i);
    strKeyText=TQString("snippetText_%1").tqarg(i);

    TQString strNameVal="";
    TQString strTextVal="";

    strNameVal = cfg->readEntry(strKeyName, "");
    strTextVal = cfg->readEntry(strKeyText, "");

    if (strNameVal != "" && strTextVal != "") {
      SnippetItem * item = new SnippetItem(group, strNameVal, strTextVal);
      _list.append(item);
    }
  }
}


/*!
    \fn SnippetWidget::initConfig()
    Initial read the cofig file
 */
void SnippetWidget::initConfig()
{
  if (_cfg == NULL)
    _cfg = new KConfig("kdevsnippetrc", false, false);

  _cfg->setGroup("SnippetPart");

  TQString strKeyName="";
  TQString strKeyText="";
  TQString strKeyId="";
  SnippetItem *item;
  SnippetGroup *group;

  kdDebug(9035) << "SnippetWidget::initConfig() " << endl;

  //if entry doesn't get found, this will return -1 which we will need a bit later
  int iCount = _cfg->readNumEntry("snippetGroupCount", -1);

  for ( int i=0; i<iCount; i++) {  //read the group-list
    strKeyName=TQString("snippetGroupName_%1").tqarg(i);
    strKeyId=TQString("snippetGroupId_%1").tqarg(i);
    strKeyText=TQString("snippetGroupLang_%1").tqarg(i);

    TQString strNameVal="";
    int iIdVal=-1;
    TQString strLangVal="";

    strNameVal = _cfg->readEntry(strKeyName, "");
    iIdVal = _cfg->readNumEntry(strKeyId, -1);
    strLangVal = _cfg->readEntry(strKeyText, i18n("All"));
    kdDebug(9035) << "Read group " << strNameVal << " " << iIdVal << endl;

    if (strNameVal != "" && iIdVal != -1 && strLangVal != "") {
      group = new SnippetGroup(this, strNameVal, iIdVal, strLangVal);
      kdDebug(9035) << "Created group " << group->getName() << " " << group->getId() << endl;
      _list.append(group);
      if (group->getLanguage() == i18n("All"))
        group->setOpen(TRUE);
      else
        group->setOpen(FALSE); //groups assigned to certain languages get handled later
    }
  }

  /* Check if the snippetGroupCount property has been found
     if iCount is -1 this means, that the user has his snippets
     stored without groups. Therefore we will call the
     initConfigOldVersion() function below */
  if (iCount != -1) {
    iCount = _cfg->readNumEntry("snippetCount", 0);
    for ( int i=0; i<iCount; i++) {  //read the snippet-list
        strKeyName=TQString("snippetName_%1").tqarg(i);
        strKeyText=TQString("snippetText_%1").tqarg(i);
        strKeyId=TQString("snippetParent_%1").tqarg(i);

        TQString strNameVal="";
        TQString strTextVal="";
        int iParentVal = -1;

        strNameVal = _cfg->readEntry(strKeyName, "");
        strTextVal = _cfg->readEntry(strKeyText, "");
        iParentVal = _cfg->readNumEntry(strKeyId, -1);
        kdDebug(9035) << "Read item " << strNameVal << " " << iParentVal << endl;

        if (strNameVal != "" && strTextVal != "" && iParentVal != -1) {
        item = new SnippetItem(SnippetItem::findGroupById(iParentVal, _list), strNameVal, strTextVal);
        kdDebug(9035) << "Created item " << item->getName() << " " << item->getParent() << endl;
        _list.append(item);
        }
    }
  } else {
    kdDebug(9035) << "found old version of snippet-configfile" << endl;
    initConfigOldVersion(_cfg);
  }

  iCount = _cfg->readNumEntry("snippetSavedCount", 0);

  for ( int i=1; i<=iCount; i++) {  //read the saved-values and store in TQMap
    strKeyName=TQString("snippetSavedName_%1").tqarg(i);
    strKeyText=TQString("snippetSavedVal_%1").tqarg(i);

    TQString strNameVal="";
    TQString strTextVal="";

    strNameVal = _cfg->readEntry(strKeyName, "");
    strTextVal = _cfg->readEntry(strKeyText, "");

    if (strNameVal != "" && strTextVal != "") {
      _mapSaved[strNameVal] = strTextVal;
    }
  }


  _SnippetConfig.setDelimiter( _cfg->readEntry("snippetDelimiter", "$") );
  _SnippetConfig.setInputMethod( _cfg->readNumEntry("snippetVarInput", 0) );
  _SnippetConfig.setToolTips( _cfg->readBoolEntry("snippetToolTips", true) );
  _SnippetConfig.setAutoOpenGroups( _cfg->readNumEntry("snippetGroupAutoOpen", 1) );

  _SnippetConfig.setSingleRect( _cfg->readRectEntry("snippetSingleRect", 0L) );
  _SnippetConfig.setMultiRect( _cfg->readRectEntry("snippetMultiRect", 0L) );
}

/*!
    \fn SnippetWidget::maybeTip( const TQPoint & p )
    Shows the Snippet-Text as ToolTip
 */
void SnippetWidget::maybeTip( const TQPoint & p )
{
	SnippetItem * item = dynamic_cast<SnippetItem*>( itemAt( p ) );
	if (!item)
	  return;

	TQRect r = tqitemRect( item );

	if (r.isValid() &&
        _SnippetConfig.useToolTips() )
	{
        if (dynamic_cast<SnippetGroup*>(item)) {
		    tip( r, i18n("Language:")+((SnippetGroup*)item)->getLanguage() );  //show the group's language
        } else {
		    tip( r, item->getText() );  //show the snippet's text
        }
	}
}

/*!
    \fn SnippetWidget::showPopupMenu( TQListViewItem * item, const TQPoint & p, int )
    Shows the Popup-Menu depending item is a valid pointer
*/
void SnippetWidget::showPopupMenu( TQListViewItem * item, const TQPoint & p, int )
{
	KPopupMenu popup;

	SnippetItem * selectedItem = static_cast<SnippetItem *>(item);
	if ( item ) {
		popup.insertTitle( selectedItem->getName() );

		popup.insertItem( i18n("Add Item..."), this, TQT_SLOT( slotAdd() ) );
		popup.insertItem( i18n("Add Group..."), this, TQT_SLOT( slotAddGroup() ) );
        if (dynamic_cast<SnippetGroup*>(item)) {
            popup.insertItem( i18n("Edit..."), this, TQT_SLOT( slotEditGroup() ) );
        } else {
            popup.insertItem( i18n("Edit..."), this, TQT_SLOT( slotEdit() ) );
        }
		popup.insertItem( i18n("Remove"), this, TQT_SLOT( slotRemove() ) );

	} else {
		popup.insertTitle(i18n("Code Snippets"));

		popup.insertItem( i18n("Add Group..."), this, TQT_SLOT( slotAddGroup() ) );
	}

	popup.exec(p);
}


//  fn SnippetWidget::parseText(TQString text, TQString del)
/*!
    This function is used to parse the given TQString for variables. If found the user will be prompted
    for a replacement value. It returns the string text with all replacements made
 */
TQString SnippetWidget::parseText(TQString text, TQString del)
{
  TQString str = text;
  TQString strName = "";
  TQString strNew = "";
  TQString strMsg="";
  int iFound = -1;
  int iEnd = -1;
  TQMap<TQString, TQString> mapVar;
  int iInMeth = _SnippetConfig.getInputMethod();
  TQRect rSingle = _SnippetConfig.getSingleRect();
  TQRect rMulti = _SnippetConfig.getMultiRect();

  do {
    iFound = text.tqfind(TQRegExp("\\"+del+"[A-Za-z-_0-9\\s]*\\"+del), iEnd+1);  //find the next variable by this TQRegExp
    if (iFound >= 0) {
      iEnd = text.tqfind(del, iFound+1)+1;
      strName = text.mid(iFound, iEnd-iFound);

      if ( strName != del+del  ) {  //if not doubel-delimiter 
        if (iInMeth == 0) { //if input-method "single" is selected
          if ( mapVar[strName].length() <= 0 ) {  // and not already in map
            strMsg=i18n("Please enter the value for <b>%1</b>:").tqarg(strName);
            strNew = showSingleVarDialog( strName, &_mapSaved, rSingle );
            if (strNew=="")
              return ""; //user clicked Cancle
          } else {
            continue; //we have already handled this variable
          }
        } else {
          strNew = ""; //for inputmode "multi" just reset new valaue
        }
      } else {
        strNew = del; //if double-delimiter -> replace by single character
      }

      if (iInMeth == 0) {  //if input-method "single" is selected
        str.tqreplace(strName, strNew);
      }

      mapVar[strName] = strNew;
    }
  } while (iFound != -1);

  if (iInMeth == 1) {  //check config, if input-method "multi" is selected
    int w, bh, oh;
    w = rMulti.width();
    bh = rMulti.height();
    oh = rMulti.top();
    if (showMultiVarDialog( &mapVar, &_mapSaved, w, bh, oh )) {  //generate and show the dialog
      TQMap<TQString, TQString>::Iterator it;
      for ( it = mapVar.begin(); it != mapVar.end(); ++it ) {  //walk through the map and do the replacement
        str.tqreplace(it.key(), it.data());
      }
    } else {
      return "";
    }

    rMulti.setWidth(w);   //this is a hack to save the dialog's dimensions in only one TQRect
    rMulti.setHeight(bh);
    rMulti.setTop(oh);
    rMulti.setLeft(0);
     _SnippetConfig.setMultiRect(rMulti);
  }

  _SnippetConfig.setSingleRect(rSingle);

  return str;
}


//  fn SnippetWidget::showMultiVarDialog()
/*!
    This function constructs a dialog which contains a label and a linedit for every
    variable that is stored in the given map except the double-delimiter entry
    It return true if everything was ok and false if the user hit cancel
 */
bool SnippetWidget::showMultiVarDialog(TQMap<TQString, TQString> * map, TQMap<TQString, TQString> * mapSave,
                                       int & iWidth, int & iBasicHeight, int & iOneHeight)
{
  //if no var -> no need to show
  if (map->count() == 0)
    return true;

  //if only var is the double-delimiter -> no need to show
  TQMap<TQString, TQString>::Iterator it = map->begin();
  if ( map->count() == 1 && it.data()==_SnippetConfig.getDelimiter()+_SnippetConfig.getDelimiter() )
    return true;

  TQMap<TQString, KTextEdit *> mapVar2Te;  //this map will help keeping track which TEXTEDIT goes with which variable
  TQMap<TQString, TQCheckBox *> mapVar2Cb;  //this map will help keeping track which CHECKBOX goes with which variable

  // --BEGIN-- building a dynamic dialog
  TQDialog dlg(this);
  dlg.setCaption(i18n("Enter Values for Variables"));

  TQGridLayout * tqlayout = new TQGridLayout( &dlg, 1, 1, 11, 6, "tqlayout");
  TQGridLayout * layoutTop = new TQGridLayout( 0, 1, 1, 0, 6, "layoutTop");
  TQGridLayout * layoutVar = new TQGridLayout( 0, 1, 1, 0, 6, "layoutVar");
  TQGridLayout * layoutBtn = new TQGridLayout( 0, 1, 1, 0, 6, "layoutBtn");

  KTextEdit *te = NULL;
  TQLabel * labTop = NULL;
  TQCheckBox * cb = NULL;

  labTop = new TQLabel( &dlg, "label" );
  labTop->tqsetSizePolicy( TQSizePolicy( (TQSizePolicy::SizeType)1, (TQSizePolicy::SizeType)0, 0, 0,
                         labTop->sizePolicy().hasHeightForWidth() ) );
  labTop->setText(i18n("Enter the replacement values for these variables:"));
  layoutTop->addWidget(labTop, 0, 0);
  tqlayout->addMultiCellLayout( layoutTop, 0, 0, 0, 1 );


  int i = 0;                                           //walk through the variable map and add
  for ( it = map->begin(); it != map->end(); ++it ) {  //a checkbox, a lable and a lineedit to the main tqlayout
    if (it.key() == _SnippetConfig.getDelimiter() + _SnippetConfig.getDelimiter())
      continue;

    cb = new TQCheckBox( &dlg, "cbVar" );
    cb->setChecked( FALSE );
    cb->setText(it.key());
    layoutVar->addWidget( cb, i ,0, TQt::AlignTop );

    te = new KTextEdit( &dlg, "teVar" );
    layoutVar->addWidget( te, i, 1, TQt::AlignTop );

    if ((*mapSave)[it.key()].length() > 0) {
      cb->setChecked( TRUE );
      te->setText((*mapSave)[it.key()]);
    }

    mapVar2Te[it.key()] = te;
    mapVar2Cb[it.key()] = cb;

    TQToolTip::add( cb, i18n("Enable this to save the value entered to the right as the default value for this variable") );
    TQWhatsThis::add( cb, i18n("If you enable this option, the value entered to the right will be saved. "
                              "If you use the same variable later, even in another snippet, the value entered to the right "
			      "will be the default value for that variable.") );

    i++;
  }
  tqlayout->addMultiCellLayout( layoutVar, 1, 1, 0, 1 );

  KPushButton * btn1 = new KPushButton( &dlg, "pushButton1" );
  btn1->setText(i18n("&Cancel"));
  btn1->tqsetSizePolicy( TQSizePolicy( (TQSizePolicy::SizeType)1, (TQSizePolicy::SizeType)0, 0, 0,
                         btn1->sizePolicy().hasHeightForWidth() ) );
  layoutBtn->addWidget( btn1, 0, 0 );

  KPushButton * btn2 = new KPushButton( &dlg, "pushButton2" );
  btn2->setText(i18n("&Apply"));
  btn2->setDefault( TRUE );
  btn2->tqsetSizePolicy( TQSizePolicy( (TQSizePolicy::SizeType)1, (TQSizePolicy::SizeType)0, 0, 0,
                         btn2->sizePolicy().hasHeightForWidth() ) );
  layoutBtn->addWidget( btn2, 0, 1 );

  tqlayout->addMultiCellLayout( layoutBtn, 2, 2, 0, 1 );
  // --END-- building a dynamic dialog

  //connect the buttons to the TQDialog default slots
  connect(btn1, TQT_SIGNAL(clicked()), &dlg, TQT_SLOT(reject()) );
  connect(btn2, TQT_SIGNAL(clicked()), &dlg, TQT_SLOT(accept()) );

  //prepare to execute the dialog
  bool bReturn = false;
  //resize the textedits
  if (iWidth > 1) {
    TQRect r = dlg.tqgeometry();
    r.setHeight(iBasicHeight + iOneHeight*mapVar2Te.count());
    r.setWidth(iWidth);
    dlg.setGeometry(r);
  }
  if ( i > 0 && // only if there are any variables
    dlg.exec() == TQDialog::Accepted ) {

    TQMap<TQString, KTextEdit *>::Iterator it2;
    for ( it2 = mapVar2Te.begin(); it2 != mapVar2Te.end(); ++it2 ) {
      if (it2.key() == _SnippetConfig.getDelimiter() + _SnippetConfig.getDelimiter())
        continue;
      (*map)[it2.key()] = it2.data()->text();    //copy the entered values back to the given map

      if (mapVar2Cb[it2.key()]->isChecked())     //if the checkbox is on; save the values for later
        (*mapSave)[it2.key()] = it2.data()->text();
      else
        (*mapSave).erase(it2.key());
    }
    bReturn = true;

    iBasicHeight = dlg.tqgeometry().height() - layoutVar->tqgeometry().height();
    iOneHeight = layoutVar->tqgeometry().height() / mapVar2Te.count();
    iWidth = dlg.tqgeometry().width();
  }

  //do some cleanup
  TQMap<TQString, KTextEdit *>::Iterator it1;
  for (it1 = mapVar2Te.begin(); it1 != mapVar2Te.end(); ++it1)
    delete it1.data();
  mapVar2Te.clear();
  TQMap<TQString, TQCheckBox *>::Iterator it2;
  for (it2 = mapVar2Cb.begin(); it2 != mapVar2Cb.end(); ++it2)
    delete it2.data();
  mapVar2Cb.clear();
  delete layoutTop;
  delete layoutVar;
  delete layoutBtn;
  delete tqlayout;

  if (i==0) //if nothing happened this means, that there are no variables to translate
    return true; //.. so just return OK

  return bReturn;
}


//  fn SnippetWidget::showSingleVarDialog(TQString var, TQMap<TQString, TQString> * mapSave)
/*!
    This function constructs a dialog which contains a label and a linedit for the given variable
    It return either the entered value or an empty string if the user hit cancel
 */
TQString SnippetWidget::showSingleVarDialog(TQString var, TQMap<TQString, TQString> * mapSave, TQRect & dlgSize)
{
  // --BEGIN-- building a dynamic dialog
  TQDialog dlg(this);
  dlg.setCaption(i18n("Enter Values for Variables"));

  TQGridLayout * tqlayout = new TQGridLayout( &dlg, 1, 1, 11, 6, "tqlayout");
  TQGridLayout * layoutTop = new TQGridLayout( 0, 1, 1, 0, 6, "layoutTop");
  TQGridLayout * layoutVar = new TQGridLayout( 0, 1, 1, 0, 6, "layoutVar");
  TQGridLayout * layoutBtn = new TQGridLayout( 0, 2, 1, 0, 6, "layoutBtn");

  KTextEdit *te = NULL;
  TQLabel * labTop = NULL;
  TQCheckBox * cb = NULL;

  labTop = new TQLabel( &dlg, "label" );
  layoutTop->addWidget(labTop, 0, 0);
  labTop->setText(i18n("Enter the replacement values for %1:").tqarg( var ));
  tqlayout->addMultiCellLayout( layoutTop, 0, 0, 0, 1 );


  cb = new TQCheckBox( &dlg, "cbVar" );
  cb->setChecked( FALSE );
  cb->setText(i18n( "Make value &default" ));

  te = new KTextEdit( &dlg, "teVar" );
  layoutVar->addWidget( te, 0, 1, TQt::AlignTop);
  layoutVar->addWidget( cb, 1, 1, TQt::AlignTop);
  if ((*mapSave)[var].length() > 0) {
    cb->setChecked( TRUE );
    te->setText((*mapSave)[var]);
  }

  TQToolTip::add( cb, i18n("Enable this to save the value entered to the right as the default value for this variable") );
  TQWhatsThis::add( cb, i18n("If you enable this option, the value entered to the right will be saved. "
                            "If you use the same variable later, even in another snippet, the value entered to the right "
                            "will be the default value for that variable.") );

  tqlayout->addMultiCellLayout( layoutVar, 1, 1, 0, 1 );

  KPushButton * btn1 = new KPushButton( &dlg, "pushButton1" );
  btn1->setText(i18n("&Cancel"));
  layoutBtn->addWidget( btn1, 0, 0 );

  KPushButton * btn2 = new KPushButton( &dlg, "pushButton2" );
  btn2->setText(i18n("&Apply"));
  btn2->setDefault( TRUE );
  layoutBtn->addWidget( btn2, 0, 1 );

  tqlayout->addMultiCellLayout( layoutBtn, 2, 2, 0, 1 );
  te->setFocus();
  // --END-- building a dynamic dialog

  //connect the buttons to the TQDialog default slots
  connect(btn1, TQT_SIGNAL(clicked()), &dlg, TQT_SLOT(reject()) );
  connect(btn2, TQT_SIGNAL(clicked()), &dlg, TQT_SLOT(accept()) );

  //execute the dialog
  TQString strReturn = "";
  if (dlgSize.isValid())
    dlg.setGeometry(dlgSize);
  if ( dlg.exec() == TQDialog::Accepted ) {
    if (cb->isChecked())     //if the checkbox is on; save the values for later
      (*mapSave)[var] = te->text();
    else
      (*mapSave).erase(var);

    strReturn = te->text();    //copy the entered values back the the given map

    dlgSize = dlg.tqgeometry();
  }

  //do some cleanup
  delete cb;
  delete te;
  delete labTop;
  delete btn1;
  delete btn2;
  delete layoutTop;
  delete layoutVar;
  delete layoutBtn;
  delete tqlayout;

  return strReturn;
}

//  fn SnippetWidget::acceptDrag (TQDropEvent *event) const
/*!
    Reimplementation from KListView.
    Check here if the data the user is about to drop fits our restrictions.
    We only accept dropps of plaintext, because from the dropped text
    we will create a snippet.
 */
bool SnippetWidget::acceptDrag (TQDropEvent *event) const
{
  kdDebug(9035) << "Format: " << event->format() << "" << event->pos() << endl;

  TQListViewItem * item = itemAt(event->pos());

  if (item &&
      TQString(event->format()).startsWith("text/plain") &&
      static_cast<SnippetWidget *>(event->source()) != this) {
    kdDebug(9035) << "returning TRUE " << endl;
    return TRUE;
  } else {
    kdDebug(9035) << "returning FALSE" << endl;
    event->acceptAction(FALSE);
    return FALSE;
  }
}

//  fn SnippetWidget::slotDropped(TQDropEvent *e, TQListViewItem *after)
/*!
    This slot is connected to the dropped signal.
    If it is emitted, we need to construct a new snippet entry with
    the data given
 */
void SnippetWidget::slotDropped(TQDropEvent *e, TQListViewItem *)
{
  TQListViewItem * item2 = itemAt(e->pos());
  
  SnippetGroup *group = dynamic_cast<SnippetGroup *>(item2);
  if (!group)
    group = dynamic_cast<SnippetGroup *>(item2->tqparent());

  TQCString dropped;
  TQByteArray data = e->tqencodedData("text/plain");
  if ( e->provides("text/plain") && data.size()>0 ) {
    //get the data from the event...
    TQString encData(data.data());
    kdDebug(9035) << "encData: " << encData << endl;

    //... then fill the dialog with the given data
    SnippetDlg dlg(this, "SnippetDlg", true);
    dlg.snippetName->clear();
    dlg.snippetText->setText(encData);

    /*fill the combobox with the names of all SnippetGroup entries*/
    for (SnippetItem *it=_list.first(); it; it=_list.next()) {
      if (dynamic_cast<SnippetGroup*>(it)) {
        dlg.cbGroup->insertItem(it->getName());
      }
    }
    dlg.cbGroup->setCurrentText(group->getName());

    if (dlg.exec() == TQDialog::Accepted) {
      /* get the group that the user selected with the combobox */
      group = dynamic_cast<SnippetGroup*>(SnippetItem::findItemByName(dlg.cbGroup->currentText(), _list));
      _list.append( new SnippetItem(group, dlg.snippetName->text(), dlg.snippetText->text()) );
    }
  }
}


/*!
    \fn SnippetWidget::languageChanged()
 */
void SnippetWidget::languageChanged()
{
  TQStringList langs = m_part->getProjectLanguages();

  for (SnippetItem *it=_list.first(); it; it=_list.next()) {
    SnippetGroup * group = dynamic_cast<SnippetGroup*>(it);
    if (group) {
      if (group->getLanguage() == i18n("All") || langs.tqcontains(group->getLanguage())) {
        group->setOpen(TRUE);
      } else {
        group->setOpen(FALSE);
      }
    }
  }
}

#include "snippet_widget.moc"