summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateListPanel.java
blob: 9a7a724e2d5d21a8199d45794d97af7e573cb6f2 (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
/*
 * Copyright 2000-2014 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intellij.codeInsight.template.impl;

import com.intellij.application.options.ExportSchemeAction;
import com.intellij.application.options.SchemesToImportPopup;
import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.ide.DataManager;
import com.intellij.ide.dnd.*;
import com.intellij.ide.dnd.aware.DnDAwareTree;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SchemesManager;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.ui.*;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.*;
import com.intellij.util.Alarm;
import com.intellij.util.NullableFunction;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PlatformIcons;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.Convertor;
import com.intellij.util.ui.tree.TreeUtil;
import com.intellij.util.ui.update.UiNotifyConnector;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.*;
import java.util.List;

public class TemplateListPanel extends JPanel implements Disposable {

  private static final String NO_SELECTION = "NoSelection";
  private static final String TEMPLATE_SETTINGS = "TemplateSettings";
  private static final TemplateImpl MOCK_TEMPLATE = new TemplateImpl("mockTemplate-xxx", "mockTemplateGroup-yyy");
  public static final String ABBREVIATION = "<abbreviation>";
  public static final Comparator<TemplateImpl> TEMPLATE_COMPARATOR = new Comparator<TemplateImpl>() {
    @Override
    public int compare(final TemplateImpl o1, final TemplateImpl o2) {
      return o1.getKey().compareToIgnoreCase(o2.getKey());
    }
  };

  static {
    MOCK_TEMPLATE.setString("");
  }

  private CheckboxTree myTree;
  private final List<TemplateGroup> myTemplateGroups = new ArrayList<TemplateGroup>();
  private JComboBox myExpandByCombo;
  private static final String SPACE = CodeInsightBundle.message("template.shortcut.space");
  private static final String TAB = CodeInsightBundle.message("template.shortcut.tab");
  private static final String ENTER = CodeInsightBundle.message("template.shortcut.enter");

  private CheckedTreeNode myTreeRoot = new CheckedTreeNode(null);

  private final Alarm myAlarm = new Alarm();
  private boolean myUpdateNeeded = false;

  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.template.impl.TemplateListPanel");

  private final Map<Integer, Map<TemplateOptionalProcessor, Boolean>> myTemplateOptions = new LinkedHashMap<Integer, Map<TemplateOptionalProcessor, Boolean>>();
  private final Map<Integer, TemplateContext> myTemplateContext = ContainerUtil.newLinkedHashMap();
  private final JPanel myDetailsPanel = new JPanel(new CardLayout());
  private LiveTemplateSettingsEditor myCurrentTemplateEditor;

  public TemplateListPanel() {
    super(new BorderLayout());

    myDetailsPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
    JLabel label = new JLabel("No live template is selected");
    label.setHorizontalAlignment(SwingConstants.CENTER);
    myDetailsPanel.add(label, NO_SELECTION);
    createTemplateEditor(MOCK_TEMPLATE, "Tab", MOCK_TEMPLATE.createOptions(), MOCK_TEMPLATE.createContext());

    add(createExpandByPanel(), BorderLayout.NORTH);

    Splitter splitter = new Splitter(true, 0.9f);
    splitter.setFirstComponent(createTable());
    splitter.setSecondComponent(myDetailsPanel);
    add(splitter, BorderLayout.CENTER);
  }

  @Override
  public void dispose() {
    myCurrentTemplateEditor.dispose();
    myAlarm.cancelAllRequests();
  }

  public void reset() {
    myTemplateOptions.clear();
    myTemplateContext.clear();

    TemplateSettings templateSettings = TemplateSettings.getInstance();
    List<TemplateGroup> groups = new ArrayList<TemplateGroup>(templateSettings.getTemplateGroups());

    Collections.sort(groups, new Comparator<TemplateGroup>() {
      @Override
      public int compare(final TemplateGroup o1, final TemplateGroup o2) {
        return o1.getName().compareToIgnoreCase(o2.getName());
      }
    });

    initTemplates(groups, templateSettings.getLastSelectedTemplateGroup(), templateSettings.getLastSelectedTemplateKey());



    if (templateSettings.getDefaultShortcutChar() == TemplateSettings.TAB_CHAR) {
      myExpandByCombo.setSelectedItem(TAB);
    }
    else if (templateSettings.getDefaultShortcutChar() == TemplateSettings.ENTER_CHAR) {
      myExpandByCombo.setSelectedItem(ENTER);
    }
    else {
      myExpandByCombo.setSelectedItem(SPACE);
    }

    UiNotifyConnector.doWhenFirstShown(this, new Runnable() {
      @Override
      public void run() {
        updateTemplateDetails(false, false);
      }
    });

    myUpdateNeeded = true;
  }

  public void apply() throws ConfigurationException {
    List<TemplateGroup> templateGroups = getTemplateGroups();
    for (TemplateGroup templateGroup : templateGroups) {
      Set<String> names = ContainerUtil.newHashSet();

      List<TemplateImpl> templates = templateGroup.getElements();
      for (TemplateImpl template : templates) {
        if (StringUtil.isEmptyOrSpaces(template.getKey())) {
          throw new ConfigurationException("A live template with an empty key has been found in " + templateGroup.getName() + " group, such live templates cannot be invoked");
        }

        if (StringUtil.isEmptyOrSpaces(template.getString())) {
          throw new ConfigurationException("A live template with an empty text has been found in " + templateGroup.getName() + " group, such live templates cannot be invoked");
        }

        if (!names.add(template.getKey())) {
          throw new ConfigurationException("Duplicate " + template.getKey() + " live templates in " + templateGroup.getName() + " group");
        }
      }
    }


    for (TemplateGroup templateGroup : templateGroups) {
      for (TemplateImpl template : templateGroup.getElements()) {
        template.applyOptions(getTemplateOptions(template));
        template.applyContext(getTemplateContext(template));
      }
    }
    TemplateSettings templateSettings = TemplateSettings.getInstance();
    templateSettings.setTemplates(templateGroups);
    templateSettings.setDefaultShortcutChar(getDefaultShortcutChar());

    reset();
  }

  private final boolean isTest = ApplicationManager.getApplication().isUnitTestMode();
  public boolean isModified() {
    TemplateSettings templateSettings = TemplateSettings.getInstance();
    if (templateSettings.getDefaultShortcutChar() != getDefaultShortcutChar()) {
      if (isTest) {
        //noinspection UseOfSystemOutOrSystemErr
        System.err.println("LiveTemplatesConfig: templateSettings.getDefaultShortcutChar()="+templateSettings.getDefaultShortcutChar()+"; getDefaultShortcutChar()="+getDefaultShortcutChar());
      }
      return true;
    }

    List<TemplateGroup> originalGroups = templateSettings.getTemplateGroups();
    List<TemplateGroup> newGroups = getTemplateGroups();

    List<TemplateImpl> originalGroup = collectTemplates(originalGroups);
    List<TemplateImpl> newGroup = collectTemplates(newGroups);

    if (checkAreEqual(originalGroup, newGroup)) return false;

    if (isTest) {
      //noinspection UseOfSystemOutOrSystemErr
      System.err.println("LiveTemplatesConfig: originalGroups="+originalGroups+"; collectTemplates(originalGroups)="+
                         originalGroup +";\n newGroups="+newGroups+"; collectTemplates(newGroups)="+ newGroup);
    }
    return true;
  }

  public void editTemplate(TemplateImpl template) {
    selectTemplate(template.getGroupName(), template.getKey());
    updateTemplateDetails(true, false);
  }

  @Nullable
  public JComponent getPreferredFocusedComponent() {
    if (getTemplate(getSingleSelectedIndex()) != null) {
      return myCurrentTemplateEditor.getKeyField();
    }
    return null;
  }

  private static List<TemplateImpl> collectTemplates(final List<TemplateGroup> groups) {
    ArrayList<TemplateImpl> result = new ArrayList<TemplateImpl>();
    for (TemplateGroup group : groups) {
      result.addAll(group.getElements());
    }
    Collections.sort(result, new Comparator<TemplateImpl>(){
      @Override
      public int compare(final TemplateImpl o1, final TemplateImpl o2) {
        final int groupsEqual = o1.getGroupName().compareToIgnoreCase(o2.getGroupName());
        if (groupsEqual != 0) {
          return groupsEqual;
        }
        return o1.getKey().compareToIgnoreCase(o2.getKey());
      }
    });
    return result;
  }

  private boolean checkAreEqual(List<TemplateImpl> originalGroup, List<TemplateImpl> newGroup) {
    if (originalGroup.size() != newGroup.size()) return false;

    for (int i = 0; i < newGroup.size(); i++) {
      if (templatesDiffer(newGroup.get(i), originalGroup.get(i))) {
        return false;
      }
    }
    return true;
  }

  private boolean areOptionsEqual(final TemplateImpl newTemplate, final TemplateImpl originalTemplate) {
    Map<TemplateOptionalProcessor, Boolean> templateOptions = getTemplateOptions(newTemplate);
    for (TemplateOptionalProcessor processor : templateOptions.keySet()) {
      if (processor.isEnabled(originalTemplate) != templateOptions.get(processor).booleanValue()) return false;
    }
    return true;
  }

  private TemplateContext getTemplateContext(final TemplateImpl newTemplate) {
    return myTemplateContext.get(getKey(newTemplate));
  }

  private Map<TemplateOptionalProcessor, Boolean> getTemplateOptions(final TemplateImpl newTemplate) {
    return myTemplateOptions.get(getKey(newTemplate));
  }

  private char getDefaultShortcutChar() {
    Object selectedItem = myExpandByCombo.getSelectedItem();
    if (TAB.equals(selectedItem)) {
      return TemplateSettings.TAB_CHAR;
    }
    else if (ENTER.equals(selectedItem)) {
      return TemplateSettings.ENTER_CHAR;
    }
    else {
      return TemplateSettings.SPACE_CHAR;
    }
  }

  private List<TemplateGroup> getTemplateGroups() {
    return myTemplateGroups;
  }

  private void createTemplateEditor(final TemplateImpl template,
                                    String shortcut,
                                    Map<TemplateOptionalProcessor, Boolean> options,
                                    TemplateContext context) {
    myCurrentTemplateEditor = new LiveTemplateSettingsEditor(template, shortcut, options, context, new Runnable() {
      @Override
      public void run() {
        DefaultMutableTreeNode node = getNode(getSingleSelectedIndex());
        if (node != null) {
          ((DefaultTreeModel)myTree.getModel()).nodeChanged(node);
          TemplateSettings.getInstance().setLastSelectedTemplate(template.getGroupName(), template.getKey());
        }
      }
    }, TemplateSettings.getInstance().getTemplate(template.getKey(), template.getGroupName()) != null);
    for (Component component : myDetailsPanel.getComponents()) {
      if (component instanceof LiveTemplateSettingsEditor) {
        myDetailsPanel.remove(component);
      }
    }

    myDetailsPanel.add(myCurrentTemplateEditor, TEMPLATE_SETTINGS);
  }

  private Iterable<? extends TemplateImpl> collectAllTemplates() {
    ArrayList<TemplateImpl> result = new ArrayList<TemplateImpl>();
    for (TemplateGroup templateGroup : myTemplateGroups) {
      result.addAll(templateGroup.getElements());
    }
    return result;
  }

  private void exportCurrentGroup() {
    int selected = getSingleSelectedIndex();
    if (selected < 0) return;

    ExportSchemeAction.doExport(getGroup(selected), getSchemesManager());

  }

  private static SchemesManager<TemplateGroup, TemplateGroup> getSchemesManager() {
    return (TemplateSettings.getInstance()).getSchemesManager();
  }

  private JPanel createExpandByPanel() {
    JPanel panel = new JPanel(new GridBagLayout());
    GridBagConstraints gbConstraints = new GridBagConstraints();
    gbConstraints.weighty = 0;
    gbConstraints.weightx = 0;
    gbConstraints.gridy = 0;
    panel.add(new JLabel(CodeInsightBundle.message("templates.dialog.shortcut.chooser.label")), gbConstraints);

    gbConstraints.gridx = 1;
    gbConstraints.insets = new Insets(0, 4, 0, 0);
    myExpandByCombo = new JComboBox();
    myExpandByCombo.addItem(SPACE);
    myExpandByCombo.addItem(TAB);
    myExpandByCombo.addItem(ENTER);
    panel.add(myExpandByCombo, gbConstraints);

    gbConstraints.gridx = 2;
    gbConstraints.weightx = 1;
    panel.add(new JPanel(), gbConstraints);
    panel.setBorder(new EmptyBorder(0, 0, 10, 0));
    return panel;
  }

  @Nullable
  private TemplateImpl getTemplate(int row) {
    JTree tree = myTree;
    TreePath path = tree.getPathForRow(row);
    if (path != null) {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
      if (node.getUserObject() instanceof TemplateImpl) {
        return (TemplateImpl)node.getUserObject();
      }
    }

    return null;
  }

  @Nullable
  private TemplateGroup getGroup(int row) {
    TreePath path = myTree.getPathForRow(row);
    if (path != null) {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
      if (node.getUserObject() instanceof TemplateGroup) {
        return (TemplateGroup)node.getUserObject();
      }
    }

    return null;
  }

  private void moveTemplates(Map<TemplateImpl, DefaultMutableTreeNode> map, @NotNull String newGroupName) {
    List<TreePath> toSelect = new ArrayList<TreePath>();
    for (TemplateImpl template : map.keySet()) {
      DefaultMutableTreeNode oldTemplateNode = map.get(template);

      TemplateGroup oldGroup = getTemplateGroup(template.getGroupName());
      if (oldGroup != null) {
        oldGroup.removeElement(template);
      }

      template.setGroupName(newGroupName);

      DefaultMutableTreeNode parent = (DefaultMutableTreeNode)oldTemplateNode.getParent();
      removeNodeFromParent(oldTemplateNode);
      if (parent.getChildCount() == 0) removeNodeFromParent(parent);

      toSelect.add(new TreePath(registerTemplate(template).getPath()));
    }

    myTree.getSelectionModel().clearSelection();
    for (TreePath path : toSelect) {
      myTree.expandPath(path.getParentPath());
      myTree.addSelectionPath(path);
      myTree.scrollRowToVisible(myTree.getRowForPath(path));
    }
  }

  @Nullable
  private DefaultMutableTreeNode getNode(final int row) {
    JTree tree = myTree;
    TreePath path = tree.getPathForRow(row);
    if (path != null) {
      return (DefaultMutableTreeNode)path.getLastPathComponent();
    }

    return null;

  }

  @Nullable
  private TemplateGroup getTemplateGroup(final String groupName) {
    for (TemplateGroup group : myTemplateGroups) {
      if (group.getName().equals(groupName)) return group;
    }

    return null;
  }

  private void addTemplate() {
    String defaultGroup = TemplateSettings.USER_GROUP_NAME;
    final DefaultMutableTreeNode node = getNode(getSingleSelectedIndex());
    if (node != null) {
      if (node.getUserObject() instanceof TemplateImpl) {
        defaultGroup = ((TemplateImpl) node.getUserObject()).getGroupName();
      }
      else if (node.getUserObject() instanceof TemplateGroup) {
        defaultGroup = ((TemplateGroup) node.getUserObject()).getName();
      }
    }

    addTemplate(new TemplateImpl(ABBREVIATION, "", defaultGroup));
  }

  public void addTemplate(TemplateImpl template) {
    myTemplateOptions.put(getKey(template), template.createOptions());
    myTemplateContext.put(getKey(template), template.createContext());

    registerTemplate(template);
    updateTemplateDetails(true, false);
  }

  private static int getKey(final TemplateImpl template) {
    return System.identityHashCode(template);
  }

  private void copyRow() {
    int selected = getSingleSelectedIndex();
    if (selected < 0) return;

    TemplateImpl orTemplate = getTemplate(selected);
    LOG.assertTrue(orTemplate != null);
    TemplateImpl template = orTemplate.copy();
    template.setKey(ABBREVIATION);
    myTemplateOptions.put(getKey(template), new HashMap<TemplateOptionalProcessor, Boolean>(getTemplateOptions(orTemplate)));
    myTemplateContext.put(getKey(template), getTemplateContext(orTemplate).createCopy());
    registerTemplate(template);

    updateTemplateDetails(true, false);
  }

  private int getSingleSelectedIndex() {
    int[] rows = myTree.getSelectionRows();
    return rows != null && rows.length == 1 ? rows[0] : -1;
  }

  private void removeRows() {
    TreeNode toSelect = null;

    TreePath[] paths = myTree.getSelectionPaths();
    if (paths == null) return;

    for (TreePath path : paths) {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
      Object o = node.getUserObject();
      if (o instanceof TemplateGroup) {
        //noinspection SuspiciousMethodCalls
        myTemplateGroups.remove(o);
        removeNodeFromParent(node);
      } else if (o instanceof TemplateImpl) {
        TemplateImpl template = (TemplateImpl)o;
        TemplateGroup templateGroup = getTemplateGroup(template.getGroupName());
        if (templateGroup != null) {
          templateGroup.removeElement(template);
          toSelect = ((DefaultMutableTreeNode)node.getParent()).getChildAfter(node);
          removeNodeFromParent(node);
        }
      }
    }

    if (toSelect instanceof DefaultMutableTreeNode) {
      setSelectedNode((DefaultMutableTreeNode)toSelect);
    }
  }

  private JPanel createTable() {
    myTreeRoot = new CheckedTreeNode(null);

    myTree = new CheckboxTree(new CheckboxTree.CheckboxTreeCellRenderer(){
      @Override
      public void customizeRenderer(final JTree tree,
                                        Object value,
                                        final boolean selected,
                                        final boolean expanded,
                                        final boolean leaf,
                                        final int row,
                                        final boolean hasFocus) {
        if (!(value instanceof DefaultMutableTreeNode)) return;
        value = ((DefaultMutableTreeNode)value).getUserObject();

        if (value instanceof TemplateImpl) {
          TemplateImpl template = (TemplateImpl)value;
          TemplateImpl defaultTemplate = TemplateSettings.getInstance().getDefaultTemplate(template);
          Color fgColor = defaultTemplate != null && templatesDiffer(template, defaultTemplate) ? JBColor.BLUE : null;
          getTextRenderer().append(template.getKey(), new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, fgColor));
          String description = template.getDescription();
          if (StringUtil.isNotEmpty(description)) {
            getTextRenderer().append (" (" + description + ")", SimpleTextAttributes.GRAY_ATTRIBUTES);
          }
        }
        else if (value instanceof TemplateGroup) {
          getTextRenderer().append (((TemplateGroup)value).getName(), SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
        }

      }
    }, myTreeRoot) {
      @Override
      protected void onNodeStateChanged(final CheckedTreeNode node) {
        Object obj = node.getUserObject();
        if (obj instanceof TemplateImpl) {
          ((TemplateImpl)obj).setDeactivated(!node.isChecked());
        }
      }

      @Override
      protected void installSpeedSearch() {
        new TreeSpeedSearch(this, new Convertor<TreePath, String>() {
          @Override
          public String convert(TreePath o) {
            Object object = ((DefaultMutableTreeNode)o.getLastPathComponent()).getUserObject();
            if (object instanceof TemplateGroup) {
              return ((TemplateGroup)object).getName();
            }
            if (object instanceof TemplateImpl) {
              TemplateImpl template = (TemplateImpl)object;
              return StringUtil.notNullize(template.getKey()) + " " + StringUtil.notNullize(template.getDescription()) + " " + template.getTemplateText();
            }
            return "";
          }
        }, true);

      }
    };
    myTree.setRootVisible(false);
    myTree.setShowsRootHandles(true);
    myTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);

    myTree.getSelectionModel().addTreeSelectionListener(new TreeSelectionListener(){
      @Override
      public void valueChanged(final TreeSelectionEvent e) {
        TemplateSettings templateSettings = TemplateSettings.getInstance();
        TemplateImpl template = getTemplate(getSingleSelectedIndex());
        if (template != null) {
          templateSettings.setLastSelectedTemplate(template.getGroupName(), template.getKey());
        } else {
          templateSettings.setLastSelectedTemplate(null, null);
          ((CardLayout) myDetailsPanel.getLayout()).show(myDetailsPanel, NO_SELECTION);
        }
        if (myUpdateNeeded) {
          myAlarm.cancelAllRequests();
          myAlarm.addRequest(new Runnable() {
            @Override
            public void run() {
              updateTemplateDetails(false, false);
            }
          }, 100);
        }
      }
    });

    myTree.registerKeyboardAction(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent event) {
        myCurrentTemplateEditor.focusKey();
      }
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);

    installPopup();


    DnDSupport.createBuilder(myTree)
      .setBeanProvider(new NullableFunction<DnDActionInfo, DnDDragStartBean>() {
        @Override
        public DnDDragStartBean fun(DnDActionInfo dnDActionInfo) {
          Point point = dnDActionInfo.getPoint();
          if (myTree.getPathForLocation(point.x, point.y) == null) return null;

          Map<TemplateImpl, DefaultMutableTreeNode> templates = getSelectedTemplates();

          return !templates.isEmpty() ? new DnDDragStartBean(templates) : null;
        }
      }).
      setDisposableParent(this)
      .setTargetChecker(new DnDTargetChecker() {
        @Override
        public boolean update(DnDEvent event) {
          @SuppressWarnings("unchecked") Set<String> oldGroupNames = getAllGroups((Map<TemplateImpl, DefaultMutableTreeNode>)event.getAttachedObject());
          TemplateGroup group = getDropGroup(event);
          boolean differentGroup = group != null && !oldGroupNames.contains(group.getName());
          boolean possible = differentGroup && !getSchemesManager().isShared(group);
          event.setDropPossible(possible, differentGroup && !possible ? "Cannot modify a shared group" : "");
          return true;
        }
      })
      .setDropHandler(new DnDDropHandler() {
        @Override
        public void drop(DnDEvent event) {
          //noinspection unchecked
          moveTemplates((Map<TemplateImpl, DefaultMutableTreeNode>)event.getAttachedObject(),
                        ObjectUtils.assertNotNull(getDropGroup(event)).getName());
        }
      })
      .setImageProvider(new NullableFunction<DnDActionInfo, DnDImage>() {
        @Override
        public DnDImage fun(DnDActionInfo dnDActionInfo) {
          Point point = dnDActionInfo.getPoint();
          TreePath path = myTree.getPathForLocation(point.x, point.y);
          return path == null ? null : new DnDImage(DnDAwareTree.getDragImage(myTree, path, point).first);
        }
      })
      .install();

    if (myTemplateGroups.size() > 0) {
      myTree.setSelectionInterval(0, 0);
    }

    return initToolbar().createPanel();

  }

  private boolean templatesDiffer(@NotNull TemplateImpl template, @NotNull TemplateImpl defaultTemplate) {
    template.parseSegments();
    defaultTemplate.parseSegments();
    return !template.equals(defaultTemplate) ||
           !template.getVariables().equals(defaultTemplate.getVariables()) ||
           !areOptionsEqual(template, defaultTemplate) ||
           !getTemplateContext(template).getDifference(defaultTemplate.getTemplateContext()).isEmpty();
  }

  private ToolbarDecorator initToolbar() {
    ToolbarDecorator decorator = ToolbarDecorator.createDecorator(myTree)
      .setAddAction(new AnActionButtonRunnable() {
        @Override
        public void run(AnActionButton button) {
          addTemplateOrGroup(button);
        }
      })
      .setRemoveAction(new AnActionButtonRunnable() {
        @Override
        public void run(AnActionButton anActionButton) {
          removeRows();
        }
      })
      .disableDownAction()
      .disableUpAction()
      .addExtraAction(new AnActionButton("Copy", PlatformIcons.COPY_ICON) {
        @Override
        public void actionPerformed(AnActionEvent e) {
          copyRow();
        }

        @Override
        public void updateButton(AnActionEvent e) {
          e.getPresentation().setEnabled(getTemplate(getSingleSelectedIndex()) != null);
        }
      });
    if (getSchemesManager().isExportAvailable()) {
      decorator.addExtraAction(new AnActionButton("Share...", PlatformIcons.EXPORT_ICON) {
        @Override
        public void actionPerformed(AnActionEvent e) {
          exportCurrentGroup();
        }

        @Override
        public void updateButton(AnActionEvent e) {
          TemplateGroup group = getGroup(getSingleSelectedIndex());
          e.getPresentation().setEnabled(group != null && !getSchemesManager().isShared(group));
        }
      });
    }
    if (getSchemesManager().isImportAvailable()) {
      decorator.addExtraAction(new AnActionButton("Import Shared...", PlatformIcons.IMPORT_ICON) {
        @Override
        public void actionPerformed(AnActionEvent e) {
          new SchemesToImportPopup<TemplateGroup, TemplateGroup>(TemplateListPanel.this){
            @Override
            protected void onSchemeSelected(final TemplateGroup scheme) {
              for (TemplateImpl newTemplate : scheme.getElements()) {
                for (TemplateImpl existingTemplate : collectAllTemplates()) {
                  if (existingTemplate.getKey().equals(newTemplate.getKey())) {
                    Messages.showMessageDialog(
                      TemplateListPanel.this,
                      CodeInsightBundle
                        .message("dialog.edit.template.error.already.exists", existingTemplate.getKey(), existingTemplate.getGroupName()),
                      CodeInsightBundle.message("dialog.edit.template.error.title"),
                      Messages.getErrorIcon()
                    );
                    return;
                  }
                }
              }
              insertNewGroup(scheme);
              for (TemplateImpl template : scheme.getElements()) {
                registerTemplate(template);
              }
            }
          }.show(getSchemesManager(), myTemplateGroups);
        }
      });
    }
    return decorator.setToolbarPosition(ActionToolbarPosition.RIGHT);
  }

  private void addTemplateOrGroup(AnActionButton button) {
    DefaultActionGroup group = new DefaultActionGroup();
    group.add(new DumbAwareAction("Live Template") {
      @Override
      public void actionPerformed(AnActionEvent e) {
        addTemplate();
      }
    });
    group.add(new DumbAwareAction("Template Group...") {
      @Override
      public void actionPerformed(AnActionEvent e) {
        String newName = Messages
          .showInputDialog(myTree, "Enter the new group name:", "Create New Group", null, "", new TemplateGroupInputValidator(null));
        if (newName != null) {
          TemplateGroup newGroup = new TemplateGroup(newName);
          setSelectedNode(insertNewGroup(newGroup));
        }
      }
    });
    DataContext context = DataManager.getInstance().getDataContext(button.getContextComponent());
    ListPopup popup = JBPopupFactory.getInstance()
      .createActionGroupPopup(null, group, context, JBPopupFactory.ActionSelectionAid.ALPHA_NUMBERING, true, null);
    popup.show(button.getPreferredPopupPoint());
  }

  @Nullable
  private TemplateGroup getDropGroup(DnDEvent event) {
    Point point = event.getPointOn(myTree);
    return getGroup(myTree.getRowForLocation(point.x, point.y));
  }

  private void installPopup() {
    final DumbAwareAction rename = new DumbAwareAction("Rename") {

      @Override
      public void update(AnActionEvent e) {
        final int selected = getSingleSelectedIndex();
        final TemplateGroup templateGroup = getGroup(selected);
        boolean enabled = templateGroup != null;
        e.getPresentation().setEnabled(enabled);
        e.getPresentation().setVisible(enabled);
        super.update(e);
      }

      @Override
      public void actionPerformed(AnActionEvent e) {
        renameGroup();
      }
    };
    rename.registerCustomShortcutSet(ActionManager.getInstance().getAction(IdeActions.ACTION_RENAME).getShortcutSet(), myTree);

    final DefaultActionGroup move = new DefaultActionGroup("Move", true) {
      @Override
      public void update(AnActionEvent e) {
        final Map<TemplateImpl, DefaultMutableTreeNode> templates = getSelectedTemplates();
        boolean enabled = !templates.isEmpty();
        e.getPresentation().setEnabled(enabled);
        e.getPresentation().setVisible(enabled);

        if (enabled) {
          Set<String> oldGroups = getAllGroups(templates);

          removeAll();
          SchemesManager<TemplateGroup, TemplateGroup> schemesManager = TemplateSettings.getInstance().getSchemesManager();

          for (TemplateGroup group : getTemplateGroups()) {
            final String newGroupName = group.getName();
            if (!oldGroups.contains(newGroupName) && !schemesManager.isShared(group)) {
              add(new DumbAwareAction(newGroupName) {
                @Override
                public void actionPerformed(AnActionEvent e) {
                  moveTemplates(templates, newGroupName);
                }
              });
            }
          }
          addSeparator();
          add(new DumbAwareAction("New group...") {
            @Override
            public void actionPerformed(AnActionEvent e) {
              String newName = Messages.showInputDialog(myTree, "Enter the new group name:", "Move to a New Group", null, "", new TemplateGroupInputValidator(null));
              if (newName != null) {
                moveTemplates(templates, newName);
              }
            }
          });
        }
      }
    };

    final DumbAwareAction changeContext = new DumbAwareAction("Change context...") {

      @Override
      public void update(AnActionEvent e) {
        boolean enabled = !getSelectedTemplates().isEmpty();
        e.getPresentation().setEnabled(enabled);
        super.update(e);
      }

      @Override
      public void actionPerformed(AnActionEvent e) {
        Map<TemplateImpl, DefaultMutableTreeNode> templates = getSelectedTemplates();
        TemplateContext context = new TemplateContext();
        JPanel contextPanel = LiveTemplateSettingsEditor.createPopupContextPanel(EmptyRunnable.INSTANCE, context);
        DialogBuilder builder = new DialogBuilder(TemplateListPanel.this);
        builder.setCenterPanel(contextPanel);
        builder.setTitle("Change Context Type For Selected Templates");
        int result = builder.show();
        if (result == DialogWrapper.OK_EXIT_CODE) {
          for (TemplateImpl template : templates.keySet()) {
            myTemplateContext.put(getKey(template), context);
          }
        }
        updateTemplateDetails(false, true);
        myTree.repaint();
      }
    };
    final DumbAwareAction revert = new DumbAwareAction("Restore defaults", "Restore default setting for the selected templates", null) {

      @Override
      public void update(AnActionEvent e) {
        boolean enabled = false;
        Map<TemplateImpl, DefaultMutableTreeNode> templates = getSelectedTemplates();
        for (TemplateImpl template : templates.keySet()) {
          TemplateImpl defaultTemplate = TemplateSettings.getInstance().getDefaultTemplate(template);
          if (defaultTemplate != null && templatesDiffer(template, defaultTemplate)) {
            enabled = true;
          }
        }
        e.getPresentation().setEnabled(enabled);
        e.getPresentation().setVisible(enabled);
        super.update(e);
      }

      @Override
      public void actionPerformed(AnActionEvent e) {
        Map<TemplateImpl, DefaultMutableTreeNode> templates = getSelectedTemplates();
        for (TemplateImpl template : templates.keySet()) {
          TemplateImpl defaultTemplate = TemplateSettings.getInstance().getDefaultTemplate(template);
          if (defaultTemplate != null) {
            myTemplateOptions.put(getKey(template), defaultTemplate.createOptions());
            myTemplateContext.put(getKey(template), defaultTemplate.createContext());
            template.resetFrom(defaultTemplate);
          }
        }
        updateTemplateDetails(false, true);
        myTree.repaint();
      }
    };


    myTree.addMouseListener(new PopupHandler() {
      @Override
      public void invokePopup(Component comp, int x, int y) {
        final DefaultActionGroup group = new DefaultActionGroup();
        group.add(rename);
        group.add(move);
        group.add(changeContext);
        group.add(revert);
        ActionManager.getInstance().createActionPopupMenu(ActionPlaces.UNKNOWN, group).getComponent().show(comp, x, y);
      }
    });
  }

  private static Set<String> getAllGroups(Map<TemplateImpl, DefaultMutableTreeNode> templates) {
    Set<String> oldGroups = new HashSet<String>();
    for (TemplateImpl template : templates.keySet()) {
      oldGroups.add(template.getGroupName());
    }
    return oldGroups;
  }

  private Map<TemplateImpl, DefaultMutableTreeNode> getSelectedTemplates() {
    TreePath[] paths = myTree.getSelectionPaths();
    if (paths == null) {
      return Collections.emptyMap();
    }
    Map<TemplateImpl, DefaultMutableTreeNode> templates = new LinkedHashMap<TemplateImpl, DefaultMutableTreeNode>();
    for (TreePath path : paths) {
      DefaultMutableTreeNode node = (DefaultMutableTreeNode)path.getLastPathComponent();
      Object o = node.getUserObject();
      if (!(o instanceof TemplateImpl)) {
        return Collections.emptyMap();
      }
      templates.put((TemplateImpl)o, node);
    }
    return templates;
  }

  private void renameGroup() {
    final int selected = getSingleSelectedIndex();
    final TemplateGroup templateGroup = getGroup(selected);
    if (templateGroup == null) return;

    final String oldName = templateGroup.getName();
    String newName = Messages.showInputDialog(myTree, "Enter the new group name:", "Rename", null, oldName,
                                              new TemplateGroupInputValidator(oldName));

    if (newName != null && !newName.equals(oldName)) {
      templateGroup.setName(newName);
      ((DefaultTreeModel)myTree.getModel()).nodeChanged(getNode(selected));
    }
  }

  private void updateTemplateDetails(boolean focusKey, boolean forceReload) {
    int selected = getSingleSelectedIndex();
    CardLayout layout = (CardLayout)myDetailsPanel.getLayout();
    if (selected < 0 || getTemplate(selected) == null) {
      layout.show(myDetailsPanel, NO_SELECTION);
    }
    else {
      TemplateImpl newTemplate = getTemplate(selected);
      if (myCurrentTemplateEditor == null || forceReload || myCurrentTemplateEditor.getTemplate() != newTemplate) {
        if (myCurrentTemplateEditor != null) {
          myCurrentTemplateEditor.dispose();
        }
        createTemplateEditor(newTemplate, (String)myExpandByCombo.getSelectedItem(), getTemplateOptions(newTemplate),
                             getTemplateContext(newTemplate));
        myCurrentTemplateEditor.resetUi();
        if (focusKey) {
          myCurrentTemplateEditor.focusKey();
        }
      }
      layout.show(myDetailsPanel, TEMPLATE_SETTINGS);
    }
  }

  private CheckedTreeNode registerTemplate(TemplateImpl template) {
    TemplateGroup newGroup = getTemplateGroup(template.getGroupName());
    if (newGroup == null) {
      newGroup = new TemplateGroup(template.getGroupName());
      insertNewGroup(newGroup);
    }
    if (!newGroup.contains(template)) {
      newGroup.addElement(template);
    }

    CheckedTreeNode node = new CheckedTreeNode(template);
    node.setChecked(!template.isDeactivated());
    for (DefaultMutableTreeNode child = (DefaultMutableTreeNode)myTreeRoot.getFirstChild();
         child != null;
         child = (DefaultMutableTreeNode)myTreeRoot.getChildAfter(child)) {
      if (((TemplateGroup)child.getUserObject()).getName().equals(template.getGroupName())) {
        int index = getIndexToInsert (child, template.getKey());
        child.insert(node, index);
        ((DefaultTreeModel)myTree.getModel()).nodesWereInserted(child, new int[]{index});
        setSelectedNode(node);
      }
    }
    return node;
  }

  private DefaultMutableTreeNode insertNewGroup(final TemplateGroup newGroup) {
    myTemplateGroups.add(newGroup);

    int index = getIndexToInsert(myTreeRoot, newGroup.getName());
    DefaultMutableTreeNode groupNode = new CheckedTreeNode(newGroup);
    myTreeRoot.insert(groupNode, index);
    ((DefaultTreeModel)myTree.getModel()).nodesWereInserted(myTreeRoot, new int[]{index});
    return groupNode;
  }

  private static int getIndexToInsert(DefaultMutableTreeNode parent, String key) {
    if (parent.getChildCount() == 0) return 0;

    int res = 0;
    for (DefaultMutableTreeNode child = (DefaultMutableTreeNode)parent.getFirstChild();
         child != null;
         child = (DefaultMutableTreeNode)parent.getChildAfter(child)) {
      Object o = child.getUserObject();
      String key1 = o instanceof TemplateImpl ? ((TemplateImpl)o).getKey() : ((TemplateGroup)o).getName();
      if (key1.compareToIgnoreCase(key) > 0) return res;
      res++;
    }
    return res;
  }

  private void setSelectedNode(DefaultMutableTreeNode node) {
    TreePath path = new TreePath(node.getPath());
    myTree.expandPath(path.getParentPath());
    int row = myTree.getRowForPath(path);
    myTree.setSelectionRow(row);
    myTree.scrollRowToVisible(row);
  }

  private void removeNodeFromParent(DefaultMutableTreeNode node) {
    TreeNode parent = node.getParent();
    int idx = parent.getIndex(node);
    node.removeFromParent();

    ((DefaultTreeModel)myTree.getModel()).nodesWereRemoved(parent, new int[]{idx}, new TreeNode[]{node});
  }

  private void initTemplates(List<TemplateGroup> groups, String lastSelectedGroup, String lastSelectedKey) {
    myTreeRoot.removeAllChildren();
    myTemplateGroups.clear();
    for (TemplateGroup group : groups) {
      myTemplateGroups.add((TemplateGroup)group.copy());
    }

    for (TemplateGroup group : myTemplateGroups) {
      CheckedTreeNode groupNode = new CheckedTreeNode(group);
      addTemplateNodes(group, groupNode);
      myTreeRoot.add(groupNode);
    }
    fireStructureChange();

    selectTemplate(lastSelectedGroup, lastSelectedKey);
  }

  private void selectTemplate(final String lastSelectedGroup, final String lastSelectedKey) {
    TreeUtil.traverseDepth(myTreeRoot, new TreeUtil.Traverse() {
      @Override
      public boolean accept(Object node) {
        Object o = ((DefaultMutableTreeNode)node).getUserObject();
        if (lastSelectedKey == null && o instanceof TemplateGroup && Comparing.equal(lastSelectedGroup, ((TemplateGroup)o).getName()) ||
            o instanceof TemplateImpl && Comparing.equal(lastSelectedKey, ((TemplateImpl)o).getKey()) && Comparing.equal(lastSelectedGroup, ((TemplateImpl)o).getGroupName())) {
          setSelectedNode((DefaultMutableTreeNode)node);
          return false;
        }

        return true;
      }
    });
  }

  private void fireStructureChange() {
    ((DefaultTreeModel)myTree.getModel()).nodeStructureChanged(myTreeRoot);
  }

  private void addTemplateNodes(TemplateGroup group, CheckedTreeNode groupNode) {
    List<TemplateImpl> templates = new ArrayList<TemplateImpl>(group.getElements());
    Collections.sort(templates, TEMPLATE_COMPARATOR);
    for (final TemplateImpl template : templates) {
      myTemplateOptions.put(getKey(template), template.createOptions());
      myTemplateContext.put(getKey(template), template.createContext());
      CheckedTreeNode node = new CheckedTreeNode(template);
      node.setChecked(!template.isDeactivated());
      groupNode.add(node);
    }
  }

  private class TemplateGroupInputValidator implements InputValidator {
    private final String myOldName;

    public TemplateGroupInputValidator(String oldName) {
      myOldName = oldName;
    }

    @Override
    public boolean checkInput(String inputString) {
      return StringUtil.isNotEmpty(inputString) &&
             (getTemplateGroup(inputString) == null || inputString.equals(myOldName));
    }

    @Override
    public boolean canClose(String inputString) {
      return checkInput(inputString);
    }
  }
}