summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/execution/impl/RunConfigurable.java
blob: 1a006c2942751331277510bc9157eefb87830e5e (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
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
/*
 * Copyright 2000-2010 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.execution.impl;

import com.intellij.execution.*;
import com.intellij.execution.configuration.ConfigurationFactoryEx;
import com.intellij.execution.configurations.*;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.options.*;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.Splitter;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.ui.popup.ListPopupStep;
import com.intellij.openapi.ui.popup.PopupStep;
import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Trinity;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.*;
import com.intellij.ui.components.JBScrollPane;
import com.intellij.ui.components.labels.ActionLink;
import com.intellij.ui.treeStructure.Tree;
import com.intellij.util.ArrayUtilRt;
import com.intellij.util.IconUtil;
import com.intellij.util.PlatformIcons;
import com.intellij.util.config.StorageAccessors;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.Convertor;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.EditableModel;
import com.intellij.util.ui.EmptyIcon;
import com.intellij.util.ui.GridBag;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.tree.TreeUtil;
import gnu.trove.THashSet;
import net.miginfocom.swing.MigLayout;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.*;
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;

import static com.intellij.execution.impl.RunConfigurable.NodeKind.*;
import static com.intellij.ui.RowsDnDSupport.RefinedDropSupport.Position.*;

class RunConfigurable extends BaseConfigurable {

  private static final Icon ADD_ICON = IconUtil.getAddIcon();
  private static final Icon REMOVE_ICON = IconUtil.getRemoveIcon();
  private static final Icon SHARED_ICON = AllIcons.Nodes.Shared;
  private static final Icon NON_SHARED_ICON = EmptyIcon.ICON_16;
  @NonNls private static final String DIVIDER_PROPORTION = "dividerProportion";
  @NonNls private static final Object DEFAULTS = new Object() {
    @Override
    public String toString() {
      return "Defaults";
    }
  };

  private volatile boolean isDisposed = false;

  private final Project myProject;
  private RunDialogBase myRunDialog;
  @NonNls final DefaultMutableTreeNode myRoot = new DefaultMutableTreeNode("Root");
  final MyTreeModel myTreeModel = new MyTreeModel(myRoot);
  final Tree myTree = new Tree(myTreeModel);
  private final JPanel myRightPanel = new JPanel(new BorderLayout());
  private final Splitter mySplitter = new Splitter(false);
  private JPanel myWholePanel;
  private final StorageAccessors myProperties = StorageAccessors.createGlobal("RunConfigurable");
  private Configurable mySelectedConfigurable = null;
  private static final Logger LOG = Logger.getInstance("#com.intellij.execution.impl.RunConfigurable");
  private final JTextField myRecentsLimit = new JTextField("5", 2);
  private final JCheckBox myConfirmation = new JCheckBox(ExecutionBundle.message("rerun.confirmation.checkbox"), true);
  private final List<Pair<UnnamedConfigurable, JComponent>> myAdditionalSettings = new ArrayList<Pair<UnnamedConfigurable, JComponent>>();
  private Map<ConfigurationFactory, Configurable> myStoredComponents = new HashMap<ConfigurationFactory, Configurable>();
  private ToolbarDecorator myToolbarDecorator;
  private boolean isFolderCreating;
  private RunConfigurable.MyToolbarAddAction myAddAction = new MyToolbarAddAction();

  public RunConfigurable(final Project project) {
    this(project, null);
  }

  public RunConfigurable(final Project project, @Nullable final RunDialogBase runDialog) {
    myProject = project;
    myRunDialog = runDialog;
  }

  @Override
  public String getDisplayName() {
    return ExecutionBundle.message("run.configurable.display.name");
  }

  private void initTree() {
    myTree.setRootVisible(false);
    myTree.setShowsRootHandles(true);
    UIUtil.setLineStyleAngled(myTree);
    TreeUtil.installActions(myTree);
    new TreeSpeedSearch(myTree, new Convertor<TreePath, String>() {
      @Override
      public String convert(TreePath o) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)o.getLastPathComponent();
        final Object userObject = node.getUserObject();
        if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
          return ((RunnerAndConfigurationSettingsImpl)userObject).getName();
        }
        else if (userObject instanceof SingleConfigurationConfigurable) {
          return ((SingleConfigurationConfigurable)userObject).getNameText();
        }
        else {
          if (userObject instanceof ConfigurationType) {
            return ((ConfigurationType)userObject).getDisplayName();
          }
          else if (userObject instanceof String) {
            return (String)userObject;
          }
        }
        return o.toString();
      }
    });
    myTree.setCellRenderer(new ColoredTreeCellRenderer() {
      @Override
      public void customizeCellRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row,
                                        boolean hasFocus) {
        if (value instanceof DefaultMutableTreeNode) {
          final DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
          final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
          final Object userObject = node.getUserObject();
          Boolean shared = null;
          final String name = RunConfigurable.getName(userObject);
          if (userObject instanceof ConfigurationType) {
            final ConfigurationType configurationType = (ConfigurationType)userObject;
            append(name, parent.isRoot() ? SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES);
            setIcon(configurationType.getIcon());
          }
          else if (userObject == DEFAULTS) {
            append(name, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
            setIcon(AllIcons.General.Settings);
          }
          else if (userObject instanceof String) {//Folders
            append(name, SimpleTextAttributes.REGULAR_ATTRIBUTES);
            setIcon(AllIcons.Nodes.Folder);
          }
          else if (userObject instanceof ConfigurationFactory) {
            append(name);
            setIcon(((ConfigurationFactory)userObject).getIcon());
          }
          else {
            final RunManagerImpl runManager = getRunManager();
            RunnerAndConfigurationSettings configuration = null;
            if (userObject instanceof SingleConfigurationConfigurable) {
              final SingleConfigurationConfigurable<?> settings = (SingleConfigurationConfigurable)userObject;
              RunnerAndConfigurationSettings configurationSettings;
              configurationSettings = settings.getSettings();
              configuration = configurationSettings;
              shared = settings.isStoreProjectConfiguration();
              setIcon(ProgramRunnerUtil.getConfigurationIcon(configurationSettings, !settings.isValid()));
            }
            else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
              RunnerAndConfigurationSettings settings = (RunnerAndConfigurationSettings)userObject;
              shared = runManager.isConfigurationShared(settings);
              setIcon(RunManagerEx.getInstanceEx(myProject).getConfigurationIcon(settings));
              configuration = settings;
            }
            if (configuration != null) {
              append(name, configuration.isTemporary()
                           ? SimpleTextAttributes.GRAY_ATTRIBUTES
                           : SimpleTextAttributes.REGULAR_ATTRIBUTES);
            }
          }
          if (shared != null) {
            Icon icon = getIcon();
            LayeredIcon layeredIcon = new LayeredIcon(icon, shared ? SHARED_ICON : NON_SHARED_ICON);
            setIcon(layeredIcon);
            setIconTextGap(0);
          } else {
            setIconTextGap(2);
          }
        }
      }
    });
    final RunManagerEx manager = getRunManager();
    final ConfigurationType[] factories = manager.getConfigurationFactories();
    for (ConfigurationType type : factories) {
      final List<RunnerAndConfigurationSettings> configurations = manager.getConfigurationSettingsList(type);
      if (!configurations.isEmpty()) {
        final DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(type);
        myRoot.add(typeNode);
        Map<String, DefaultMutableTreeNode> folderMapping = new HashMap<String, DefaultMutableTreeNode>();
        int folderCounter = 0;
        for (RunnerAndConfigurationSettings configuration : configurations) {
          String folder = configuration.getFolderName();
          if (folder != null) {
            DefaultMutableTreeNode node = folderMapping.get(folder);
            if (node == null) {
              node = new DefaultMutableTreeNode(folder);
              typeNode.insert(node, folderCounter);
              folderCounter++;
              folderMapping.put(folder, node);
            }
            node.add(new DefaultMutableTreeNode(configuration));
          } else {
            typeNode.add(new DefaultMutableTreeNode(configuration));
          }
        }
      }
    }

    // add defaults
    final DefaultMutableTreeNode defaults = new DefaultMutableTreeNode(DEFAULTS);
    final ConfigurationType[] configurationTypes = RunManagerImpl.getInstanceImpl(myProject).getConfigurationFactories();
    for (final ConfigurationType type : configurationTypes) {
      if (!(type instanceof UnknownConfigurationType)) {
        ConfigurationFactory[] configurationFactories = type.getConfigurationFactories();
        DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(type);
        defaults.add(typeNode);
        if (configurationFactories.length != 1) {
          for (ConfigurationFactory factory : configurationFactories) {
            typeNode.add(new DefaultMutableTreeNode(factory));
          }
        }
      }
    }
    if (defaults.getChildCount() > 0) myRoot.add(defaults);

    myTree.addTreeSelectionListener(new TreeSelectionListener() {
      @Override
      public void valueChanged(TreeSelectionEvent e) {
        final TreePath selectionPath = myTree.getSelectionPath();
        if (selectionPath != null) {
          DefaultMutableTreeNode node = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
          final Object userObject = getSafeUserObject(node);
          if (userObject instanceof SingleConfigurationConfigurable) {
            updateRightPanel((SingleConfigurationConfigurable<RunConfiguration>)userObject);
          }
          else if (userObject instanceof String) {
            showFolderField(getSelectedConfigurationType(), node, (String)userObject);
          }
          else {
            if (userObject instanceof ConfigurationType || userObject == DEFAULTS) {
              final DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
              if (parent.isRoot()) {
                drawPressAddButtonMessage(userObject == DEFAULTS ? null : (ConfigurationType)userObject);
              }
              else {
                final ConfigurationType type = (ConfigurationType)userObject;
                ConfigurationFactory[] factories = type.getConfigurationFactories();
                if (factories.length == 1) {
                  final ConfigurationFactory factory = factories[0];
                  showTemplateConfigurable(factory);
                }
                else {
                  drawPressAddButtonMessage((ConfigurationType)userObject);
                }
              }
            }
            else if (userObject instanceof ConfigurationFactory) {
              showTemplateConfigurable((ConfigurationFactory)userObject);
            }
          }
        }
        updateDialog();
      }
    });
    myTree.registerKeyboardAction(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        clickDefaultButton();
      }
    }, KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), JComponent.WHEN_FOCUSED);
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        if (isDisposed) return;

        myTree.requestFocusInWindow();
        final RunnerAndConfigurationSettings settings = manager.getSelectedConfiguration();
        if (settings != null) {
          final Enumeration enumeration = myRoot.breadthFirstEnumeration();
          while (enumeration.hasMoreElements()) {
            final DefaultMutableTreeNode node = (DefaultMutableTreeNode)enumeration.nextElement();
            final Object userObject = node.getUserObject();
            if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
              final RunnerAndConfigurationSettings runnerAndConfigurationSettings = (RunnerAndConfigurationSettings)userObject;
              final ConfigurationType configurationType = settings.getType();
              if (configurationType != null &&
                  Comparing.strEqual(runnerAndConfigurationSettings.getConfiguration().getType().getId(), configurationType.getId()) &&
                  Comparing.strEqual(runnerAndConfigurationSettings.getConfiguration().getName(), settings.getName())) {
                TreeUtil.selectInTree(node, true, myTree);
                return;
              }
            }
          }
        }
        else {
          mySelectedConfigurable = null;
        }
        //TreeUtil.selectInTree(defaults, true, myTree);
        drawPressAddButtonMessage(null);
      }
    });
    sortTopLevelBranches();
    ((DefaultTreeModel)myTree.getModel()).reload();
  }

  private void showTemplateConfigurable(ConfigurationFactory factory) {
    Configurable configurable = myStoredComponents.get(factory);
    if (configurable == null){
      configurable = new TemplateConfigurable(RunManagerImpl.getInstanceImpl(myProject).getConfigurationTemplate(factory));
      myStoredComponents.put(factory, configurable);
      configurable.reset();
    }
    updateRightPanel(configurable);
  }

  private void showFolderField(final ConfigurationType type, final DefaultMutableTreeNode node, final String folderName) {
    myRightPanel.removeAll();
    JPanel p = new JPanel(new MigLayout("ins " + myToolbarDecorator.getActionsPanel().getHeight() + " 5 0 0, flowx"));
    final JTextField textField = new JTextField(folderName);
    textField.getDocument().addDocumentListener(new DocumentAdapter() {
      @Override
      protected void textChanged(DocumentEvent e) {
        node.setUserObject(textField.getText());
        myTreeModel.reload(node);
      }
    });
    p.add(new JLabel("Folder name:"), "gapright 5");
    p.add(textField, "pushx, growx, wrap");
    p.add(new JLabel(ExecutionBundle.message("run.configuration.rename.folder.disclaimer")), "gaptop 5, spanx 2");

    myRightPanel.add(p);
    myRightPanel.revalidate();
    myRightPanel.repaint();
    if (isFolderCreating) {
      textField.selectAll();
      textField.requestFocus();
    }
  }

  private Object getSafeUserObject(DefaultMutableTreeNode node) {
    Object userObject = node.getUserObject();
    if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
      final SingleConfigurationConfigurable<RunConfiguration> configurationConfigurable =
        SingleConfigurationConfigurable.editSettings((RunnerAndConfigurationSettings)userObject, null);
      installUpdateListeners(configurationConfigurable);
      node.setUserObject(configurationConfigurable);
      return configurationConfigurable;
    }
    return userObject;
  }

  public void setRunDialog(final RunDialogBase runDialog) {
    myRunDialog = runDialog;
  }

  private void updateRightPanel(final Configurable configurable) {
    myRightPanel.removeAll();
    mySelectedConfigurable = configurable;

    final JBScrollPane scrollPane = new JBScrollPane(configurable.createComponent());
    scrollPane.setBorder(null);
    myRightPanel.add(scrollPane, BorderLayout.CENTER);
    if (configurable instanceof SingleConfigurationConfigurable) {
      myRightPanel.add(((SingleConfigurationConfigurable)configurable).getValidationComponent(), BorderLayout.SOUTH);
    }

    setupDialogBounds();
  }

  private void sortTopLevelBranches() {
    List<TreePath> expandedPaths = TreeUtil.collectExpandedPaths(myTree);
    TreeUtil.sort(myRoot, new Comparator() {
      @Override
      public int compare(final Object o1, final Object o2) {
        final Object userObject1 = ((DefaultMutableTreeNode)o1).getUserObject();
        final Object userObject2 = ((DefaultMutableTreeNode)o2).getUserObject();
        if (userObject1 instanceof ConfigurationType && userObject2 instanceof ConfigurationType) {
          return ((ConfigurationType)userObject1).getDisplayName().compareTo(((ConfigurationType)userObject2).getDisplayName());
        }
        else if (userObject1 == DEFAULTS && userObject2 instanceof ConfigurationType) {
          return 1;
        }
        else if (userObject2 == DEFAULTS && userObject1 instanceof ConfigurationType) {
          return -1;
        }

        return 0;
      }
    });
    TreeUtil.restoreExpandedPaths(myTree, expandedPaths);
  }

  private void update() {
    updateDialog();
    final TreePath selectionPath = myTree.getSelectionPath();
    if (selectionPath != null) {
      final DefaultMutableTreeNode node = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
      myTreeModel.reload(node);
    }
  }

  private void installUpdateListeners(final SingleConfigurationConfigurable<RunConfiguration> info) {
    final boolean[] changed = new boolean[]{false};
    info.getEditor().addSettingsEditorListener(new SettingsEditorListener<RunnerAndConfigurationSettings>() {
      @Override
      public void stateChanged(final SettingsEditor<RunnerAndConfigurationSettings> editor) {
        update();
        final RunConfiguration configuration = info.getConfiguration();
        if (configuration instanceof LocatableConfiguration) {
          final LocatableConfiguration runtimeConfiguration = (LocatableConfiguration)configuration;
          if (runtimeConfiguration.isGeneratedName() && !changed[0]) {
            try {
              final LocatableConfiguration snapshot = (LocatableConfiguration)editor.getSnapshot().getConfiguration();
              final String generatedName = snapshot.suggestedName();
              if (generatedName != null && generatedName.length() > 0) {
                info.setNameText(generatedName);
                changed[0] = false;
              }
            }
            catch (ConfigurationException ignore) {
            }
          }
        }
        setupDialogBounds();
      }
    });

    info.addNameListener(new DocumentAdapter() {
      @Override
      protected void textChanged(DocumentEvent e) {
        changed[0] = true;
        update();
      }
    });

    info.addSharedListener(new ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent e) {
        changed[0] = true;
        update();
      }
    });
  }

  private void drawPressAddButtonMessage(final ConfigurationType configurationType) {
    JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
    panel.setBorder(new EmptyBorder(30, 0, 0, 0));
    panel.add(new JLabel("Press the"));

    ActionLink addIcon = new ActionLink("", ADD_ICON, myAddAction);
    addIcon.setBorder(new EmptyBorder(0, 0, 0, 5));
    panel.add(addIcon);

    final String configurationTypeDescription = configurationType != null
                                                ? configurationType.getConfigurationTypeDescription()
                                                : ExecutionBundle.message("run.configuration.default.type.description");
    panel.add(new JLabel(ExecutionBundle.message("empty.run.configuration.panel.text.label3", configurationTypeDescription)));
    JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(panel, true);

    myRightPanel.removeAll();
    myRightPanel.add(scrollPane, BorderLayout.CENTER);
    if (configurationType == null) {
      JPanel settingsPanel = new JPanel(new GridBagLayout());
      GridBag grid = new GridBag().setDefaultAnchor(GridBagConstraints.NORTHWEST);

      for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
        settingsPanel.add(each.second, grid.nextLine().next());
      }
      settingsPanel.add(createSettingsPanel(), grid.nextLine().next());

      JPanel wrapper = new JPanel(new BorderLayout());
      wrapper.add(settingsPanel, BorderLayout.WEST);
      wrapper.add(Box.createGlue(), BorderLayout.CENTER);

      myRightPanel.add(wrapper, BorderLayout.SOUTH);
    }
    myRightPanel.revalidate();
    myRightPanel.repaint();
  }

  private static String getName(Object userObject) {
    if (userObject instanceof ConfigurationType) {
      return ((ConfigurationType)userObject).getDisplayName();
    }
    if (userObject == DEFAULTS) {
      return "Defaults";
    }
    if (userObject instanceof ConfigurationFactory) {
      return ((ConfigurationFactory)userObject).getName();
    }
    if (userObject instanceof SingleConfigurationConfigurable) {
      return ((SingleConfigurationConfigurable)userObject).getNameText();
    }
    if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
      return ((RunnerAndConfigurationSettingsImpl)userObject).getName();
    }
    return String.valueOf(userObject);//Folder objects are strings
  }

  private JPanel createLeftPanel() {
    initTree();
    MyRemoveAction removeAction = new MyRemoveAction();
    MyMoveAction moveUpAction = new MyMoveAction(ExecutionBundle.message("move.up.action.name"), null, IconUtil.getMoveUpIcon(), -1);
    MyMoveAction moveDownAction = new MyMoveAction(ExecutionBundle.message("move.down.action.name"), null, IconUtil.getMoveDownIcon(), 1);
    myToolbarDecorator = ToolbarDecorator.createDecorator(myTree).setAsUsualTopToolbar()
      .setAddAction(myAddAction).setAddActionName(ExecutionBundle.message("add.new.run.configuration.acrtion.name"))
      .setRemoveAction(removeAction).setRemoveActionUpdater(removeAction)
      .setRemoveActionName(ExecutionBundle.message("remove.run.configuration.action.name"))
      .setMoveUpAction(moveUpAction).setMoveUpActionName(ExecutionBundle.message("move.up.action.name")).setMoveUpActionUpdater(
        moveUpAction)
      .setMoveDownAction(moveDownAction).setMoveDownActionName(ExecutionBundle.message("move.down.action.name")).setMoveDownActionUpdater(
        moveDownAction)
      .addExtraAction(AnActionButton.fromAction(new MyCopyAction()))
      .addExtraAction(AnActionButton.fromAction(new MySaveAction()))
      .addExtraAction(AnActionButton.fromAction(new MyEditDefaultsAction()))
      .addExtraAction(AnActionButton.fromAction(new MyCreateFolderAction()))
      .addExtraAction(AnActionButton.fromAction(new MySortFolderAction()))
      .setButtonComparator(ExecutionBundle.message("add.new.run.configuration.acrtion.name"),
                           ExecutionBundle.message("remove.run.configuration.action.name"),
                           ExecutionBundle.message("copy.configuration.action.name"),
                           ExecutionBundle.message("action.name.save.configuration"),
                           ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"),
                           ExecutionBundle.message("move.up.action.name"),
                           ExecutionBundle.message("move.down.action.name"),
                           ExecutionBundle.message("run.configuration.create.folder.text")
      ).setForcedDnD();
    return myToolbarDecorator.createPanel();
  }

  private JPanel createSettingsPanel() {
    JPanel bottomPanel = new JPanel(new GridBagLayout());
    GridBag g = new GridBag();

    bottomPanel.add(myConfirmation, g.nextLine().coverLine());
    bottomPanel.add(new JLabel("Temporary configurations limit:"), g.nextLine().next());
    bottomPanel.add(myRecentsLimit, g.next().anchor(GridBagConstraints.WEST));

    myRecentsLimit.getDocument().addDocumentListener(new DocumentAdapter() {
      @Override
      protected void textChanged(DocumentEvent e) {
        setModified(true);
      }
    });
    myConfirmation.addChangeListener(new ChangeListener() {
      @Override
      public void stateChanged(ChangeEvent e) {
        setModified(true);
      }
    });
    return bottomPanel;
  }

  @Nullable
  private ConfigurationType getSelectedConfigurationType() {
    final DefaultMutableTreeNode configurationTypeNode = getSelectedConfigurationTypeNode();
    return configurationTypeNode != null ? (ConfigurationType)configurationTypeNode.getUserObject() : null;
  }

  @Override
  public JComponent createComponent() {
    for (RunConfigurationsSettings each : Extensions.getExtensions(RunConfigurationsSettings.EXTENSION_POINT, myProject)) {
      UnnamedConfigurable configurable = each.createConfigurable();
      myAdditionalSettings.add(Pair.create(configurable, configurable.createComponent()));
    }

    myWholePanel = new JPanel(new BorderLayout());
    mySplitter.setFirstComponent(createLeftPanel());
    mySplitter.setSecondComponent(myRightPanel);
    myWholePanel.add(mySplitter, BorderLayout.CENTER);

    updateDialog();

    Dimension d = myWholePanel.getPreferredSize();
    d.width = Math.max(d.width, 800);
    d.height = Math.max(d.height, 600);
    myWholePanel.setPreferredSize(d);

    mySplitter.setProportion(myProperties.getFloat(DIVIDER_PROPORTION, 0.3f));

    return myWholePanel;
  }

  @Override
  public void reset() {
    final RunManagerEx manager = getRunManager();
    final RunManagerConfig config = manager.getConfig();
    myRecentsLimit.setText(Integer.toString(config.getRecentsLimit()));
    myConfirmation.setSelected(config.isRestartRequiresConfirmation());

    for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
      each.first.reset();
    }

    setModified(false);
  }

  public Configurable getSelectedConfigurable() {
    return mySelectedConfigurable;
  }

  @Override
  public void apply() throws ConfigurationException {
    updateActiveConfigurationFromSelected();

    final RunManagerImpl manager = getRunManager();
    final ConfigurationType[] types = manager.getConfigurationFactories();
    List<ConfigurationType> configurationTypes = new ArrayList<ConfigurationType>();
    for (int i = 0; i < myRoot.getChildCount(); i++) {
      final DefaultMutableTreeNode node = (DefaultMutableTreeNode)myRoot.getChildAt(i);
      Object userObject = node.getUserObject();
      if (userObject instanceof ConfigurationType) {
        configurationTypes.add((ConfigurationType)userObject);
      }
    }
    for (ConfigurationType type : types) {
      if (!configurationTypes.contains(type))
        configurationTypes.add(type);
    }

    for (ConfigurationType configurationType : configurationTypes) {
      applyByType(configurationType);
    }

    try {
      int i = Math.max(RunManagerConfig.MIN_RECENT_LIMIT, Integer.parseInt(myRecentsLimit.getText()));
      int oldLimit = manager.getConfig().getRecentsLimit();
      if (oldLimit != i) {
        manager.getConfig().setRecentsLimit(i);
        manager.checkRecentsLimit();
      }
    }
    catch (NumberFormatException e) {
      // ignore
    }
    manager.getConfig().setRestartRequiresConfirmation(myConfirmation.isSelected());

    for (Configurable configurable : myStoredComponents.values()) {
      if (configurable.isModified()){
        configurable.apply();
      }
    }

    for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
      each.first.apply();
    }

    manager.saveOrder();
    setModified(false);
    myTree.repaint();
  }

  protected void updateActiveConfigurationFromSelected() {
    if (mySelectedConfigurable != null && mySelectedConfigurable instanceof SingleConfigurationConfigurable) {
      RunnerAndConfigurationSettings settings =
        (RunnerAndConfigurationSettings)((SingleConfigurationConfigurable)mySelectedConfigurable).getSettings();

      getRunManager().setSelectedConfiguration(settings);
    }
  }

  private void applyByType(@NotNull ConfigurationType type) throws ConfigurationException {
    RunnerAndConfigurationSettings selectedSettings = getSelectedSettings();
    int indexToMove = -1;

    DefaultMutableTreeNode typeNode = getConfigurationTypeNode(type);
    final RunManagerImpl manager = getRunManager();
    final ArrayList<RunConfigurationBean> stableConfigurations = new ArrayList<RunConfigurationBean>();
    if (typeNode != null) {
      final Set<String> names = new HashSet<String>();
      List<DefaultMutableTreeNode> configurationNodes = new ArrayList<DefaultMutableTreeNode>();
      collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION);
      for (DefaultMutableTreeNode node : configurationNodes) {
        final Object userObject = node.getUserObject();
        RunConfigurationBean configurationBean = null;
        RunnerAndConfigurationSettings settings = null;
        if (userObject instanceof SingleConfigurationConfigurable) {
          final SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
          settings = (RunnerAndConfigurationSettings)configurable.getSettings();
          if (settings.isTemporary()) {
            applyConfiguration(typeNode, configurable);
          }
          configurationBean = new RunConfigurationBean(configurable);
        }
        else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
          settings = (RunnerAndConfigurationSettings)userObject;
          configurationBean = new RunConfigurationBean(settings,
                                                       manager.isConfigurationShared(settings),
                                                       manager.getBeforeRunTasks(settings.getConfiguration()));

        }
        if (configurationBean != null) {
          final SingleConfigurationConfigurable configurable = configurationBean.getConfigurable();
          final String nameText = configurable != null ? configurable.getNameText() : configurationBean.getSettings().getName();
          if (!names.add(nameText)) {
            TreeUtil.selectNode(myTree, node);
            throw new ConfigurationException(type.getDisplayName() + " with name \'" + nameText + "\' already exists");
          }
          stableConfigurations.add(configurationBean);
          if (settings == selectedSettings) {
            indexToMove = stableConfigurations.size()-1;
          }
        }
      }
      List<DefaultMutableTreeNode> folderNodes = new ArrayList<DefaultMutableTreeNode>();
      collectNodesRecursively(typeNode, folderNodes, FOLDER);
      names.clear();
      for (DefaultMutableTreeNode node : folderNodes) {
        String folderName = (String)node.getUserObject();
        if (folderName.isEmpty()) {
          TreeUtil.selectNode(myTree, node);
          throw new ConfigurationException("Folder name shouldn't be empty");
        }
        if (!names.add(folderName)) {
          TreeUtil.selectNode(myTree, node);
          throw new ConfigurationException("Folders name \'" + folderName + "\' is duplicated");
        }
      }
    }
    // try to apply all
    for (RunConfigurationBean bean : stableConfigurations) {
      final SingleConfigurationConfigurable configurable = bean.getConfigurable();
      if (configurable != null) {
        applyConfiguration(typeNode, configurable);
      }
    }

    // if apply succeeded, update the list of configurations in RunManager
    Set<RunnerAndConfigurationSettings> toDeleteSettings = new THashSet<RunnerAndConfigurationSettings>();
    for (RunConfiguration each : manager.getConfigurationsList(type)) {
      ContainerUtil.addIfNotNull(toDeleteSettings, manager.getSettings(each));
    }

    //Just saved as 'stable' configuration shouldn't stay between temporary ones (here we order model to save)
    int shift = 0;
    if (selectedSettings != null && selectedSettings.getType() == type) {
      shift = adjustOrder();
    }
    if (shift != 0 && indexToMove != -1) {
      stableConfigurations.add(indexToMove-shift, stableConfigurations.remove(indexToMove));
    }
    for (RunConfigurationBean each : stableConfigurations) {
      toDeleteSettings.remove(each.getSettings());
      manager.addConfiguration(each.getSettings(), each.isShared(), each.getStepsBeforeLaunch(), false);
    }

    for (RunnerAndConfigurationSettings each : toDeleteSettings) {
      manager.removeConfiguration(each);
    }
  }

  static void collectNodesRecursively(DefaultMutableTreeNode parentNode, List<DefaultMutableTreeNode> nodes, NodeKind... allowed) {
    for (int i = 0; i < parentNode.getChildCount(); i++) {
      DefaultMutableTreeNode child = (DefaultMutableTreeNode)parentNode.getChildAt(i);
      if (ArrayUtilRt.find(allowed, getKind(child)) != -1) {
        nodes.add(child);
      }
      collectNodesRecursively(child, nodes, allowed);
    }
  }

  @Nullable
  private DefaultMutableTreeNode getConfigurationTypeNode(@NotNull final ConfigurationType type) {
    for (int i = 0; i < myRoot.getChildCount(); i++) {
      final DefaultMutableTreeNode node = (DefaultMutableTreeNode)myRoot.getChildAt(i);
      if (node.getUserObject() == type) return node;
    }
    return null;
  }

  private void applyConfiguration(DefaultMutableTreeNode typeNode, SingleConfigurationConfigurable<?> configurable) throws ConfigurationException {
    try {
      if (configurable != null) {
        configurable.apply();
        RunManagerImpl.getInstanceImpl(myProject).fireRunConfigurationChanged(configurable.getSettings());
      }
    }
    catch (ConfigurationException e) {
      for (int i = 0; i < typeNode.getChildCount(); i++) {
        final DefaultMutableTreeNode node = (DefaultMutableTreeNode)typeNode.getChildAt(i);
        if (Comparing.equal(configurable, node.getUserObject())) {
          TreeUtil.selectNode(myTree, node);
          break;
        }
      }
      throw e;
    }
  }

  @Override
  public boolean isModified() {
    if (super.isModified()) return true;
    final RunManagerImpl runManager = getRunManager();
    final List<RunConfiguration> allConfigurations = runManager.getAllConfigurationsList();
    final List<RunConfiguration> currentConfigurations = new ArrayList<RunConfiguration>();
    for (int i = 0; i < myRoot.getChildCount(); i++) {
      DefaultMutableTreeNode typeNode = (DefaultMutableTreeNode)myRoot.getChildAt(i);
      final Object object = typeNode.getUserObject();
      if (object instanceof ConfigurationType) {
        final List<RunnerAndConfigurationSettings> configurationSettings = runManager.getConfigurationSettingsList(
          (ConfigurationType)object);
        List<DefaultMutableTreeNode> configurationNodes = new ArrayList<DefaultMutableTreeNode>();
        collectNodesRecursively(typeNode, configurationNodes, CONFIGURATION, TEMPORARY_CONFIGURATION);
        if (configurationSettings.size() != configurationNodes.size()) return true;
        for (int j = 0; j < configurationNodes.size(); j++) {
          DefaultMutableTreeNode configurationNode = configurationNodes.get(j);
          final Object userObject = configurationNode.getUserObject();
          if (userObject instanceof SingleConfigurationConfigurable) {
            SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
            if (!Comparing.strEqual(configurationSettings.get(j).getConfiguration().getName(), configurable.getConfiguration().getName())) {
              return true;
            }
            if (configurable.isModified()) return true;
            currentConfigurations.add(configurable.getConfiguration());
          }
          else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
            currentConfigurations.add(((RunnerAndConfigurationSettings)userObject).getConfiguration());
          }
        }
      }
    }
    if (allConfigurations.size() != currentConfigurations.size() || !allConfigurations.containsAll(currentConfigurations)) return true;

    for (Configurable configurable : myStoredComponents.values()) {
      if (configurable.isModified()) return true;
    }

    for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
      if (each.first.isModified()) return true;
    }

    return false;
  }

  @Override
  public void disposeUIResources() {
    isDisposed = true;
    for (Configurable configurable : myStoredComponents.values()) {
      configurable.disposeUIResources();
    }
    myStoredComponents.clear();

    for (Pair<UnnamedConfigurable, JComponent> each : myAdditionalSettings) {
      each.first.disposeUIResources();
    }

    TreeUtil.traverseDepth(myRoot, new TreeUtil.Traverse() {
      @Override
      public boolean accept(Object node) {
        if (node instanceof DefaultMutableTreeNode) {
          final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
          final Object userObject = treeNode.getUserObject();
          if (userObject instanceof SingleConfigurationConfigurable) {
            ((SingleConfigurationConfigurable)userObject).disposeUIResources();
          }
        }
        return true;
      }
    });
    myRightPanel.removeAll();
    myProperties.setFloat(DIVIDER_PROPORTION, mySplitter.getProportion());
    mySplitter.dispose();
  }

  private void updateDialog() {
    final Executor executor = myRunDialog != null ? myRunDialog.getExecutor() : null;
    if (executor == null) return;
    final StringBuilder buffer = new StringBuilder();
    buffer.append(executor.getId());
    final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
    if (configuration != null) {
      buffer.append(" - ");
      buffer.append(configuration.getNameText());
    }
    myRunDialog.setOKActionEnabled(canRunConfiguration(configuration, executor));
    myRunDialog.setTitle(buffer.toString());
  }

  private void setupDialogBounds() {
    SwingUtilities.invokeLater(new Runnable() {
      @Override
      public void run() {
        UIUtil.setupEnclosingDialogBounds(myWholePanel);
      }
    });
  }

  @Nullable
  private SingleConfigurationConfigurable<RunConfiguration> getSelectedConfiguration() {
    final TreePath selectionPath = myTree.getSelectionPath();
    if (selectionPath != null) {
      final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
      final Object userObject = treeNode.getUserObject();
      if (userObject instanceof SingleConfigurationConfigurable) {
        return (SingleConfigurationConfigurable<RunConfiguration>)userObject;
      }
    }
    return null;
  }

  private static boolean canRunConfiguration(@Nullable SingleConfigurationConfigurable<RunConfiguration> configuration, final @NotNull Executor executor) {
    try {
      return configuration != null && RunManagerImpl.canRunConfiguration(configuration.getSnapshot(), executor);
    }
    catch (ConfigurationException e) {
      return false;
    }
  }

  RunManagerImpl getRunManager() {
    return RunManagerImpl.getInstanceImpl(myProject);
  }

  @Override
  public String getHelpTopic() {
    final ConfigurationType type = getSelectedConfigurationType();
    if (type != null) {
      return "reference.dialogs.rundebug." + type.getId();
    }
    return "reference.dialogs.rundebug";
  }

  private void clickDefaultButton() {
    if (myRunDialog != null) myRunDialog.clickDefaultButton();
  }

  @Nullable
  private DefaultMutableTreeNode getSelectedConfigurationTypeNode() {
    TreePath selectionPath = myTree.getSelectionPath();
    DefaultMutableTreeNode node = selectionPath != null ? (DefaultMutableTreeNode)selectionPath.getLastPathComponent() : null;
    while(node != null) {
      Object userObject = node.getUserObject();
      if (userObject instanceof ConfigurationType) {
        return node;
      }
      node = (DefaultMutableTreeNode)node.getParent();
    }
    return null;
  }

  @NotNull
  private DefaultMutableTreeNode getNode(int row) {
    return (DefaultMutableTreeNode)myTree.getPathForRow(row).getLastPathComponent();
  }

  @Nullable
  Trinity<Integer, Integer, RowsDnDSupport.RefinedDropSupport.Position> getAvailableDropPosition(int direction) {
    int[] rows = myTree.getSelectionRows();
    if (rows == null || rows.length != 1) {
      return null;
    }
    int oldIndex = rows[0];
    int newIndex = oldIndex + direction;

    if (!getKind((DefaultMutableTreeNode)myTree.getPathForRow(oldIndex).getLastPathComponent()).supportsDnD())
      return null;

    while (newIndex > 0 && newIndex < myTree.getRowCount()) {
      TreePath targetPath = myTree.getPathForRow(newIndex);
      boolean allowInto = getKind((DefaultMutableTreeNode)targetPath.getLastPathComponent()) == FOLDER && !myTree.isExpanded(targetPath);
      RowsDnDSupport.RefinedDropSupport.Position position = allowInto && myTreeModel.isDropInto(myTree, oldIndex, newIndex) ?
                                                            INTO :
                                                            direction > 0 ? BELOW : ABOVE;
      DefaultMutableTreeNode oldNode = getNode(oldIndex);
      DefaultMutableTreeNode newNode = getNode(newIndex);
      if (oldNode.getParent() != newNode.getParent() && getKind(newNode) != FOLDER) {
        RowsDnDSupport.RefinedDropSupport.Position copy = position;
        if (position == BELOW) {
          copy = ABOVE;
        }
        else if (position == ABOVE) {
          copy = BELOW;
        }
        if (myTreeModel.canDrop(oldIndex, newIndex, copy)) {
          return Trinity.create(oldIndex, newIndex, copy);
        }
      }
      if (myTreeModel.canDrop(oldIndex, newIndex, position)) {
        return Trinity.create(oldIndex, newIndex, position);
      }

      if (position == BELOW && newIndex < myTree.getRowCount() - 1 && myTreeModel.canDrop(oldIndex, newIndex + 1, ABOVE)) {
        return Trinity.create(oldIndex, newIndex + 1, ABOVE);
      }
      if (position == ABOVE && newIndex > 1 && myTreeModel.canDrop(oldIndex, newIndex - 1, BELOW)) {
        return Trinity.create(oldIndex, newIndex - 1, BELOW);
      }
      if (position == BELOW && myTreeModel.canDrop(oldIndex, newIndex, ABOVE)) {
        return Trinity.create(oldIndex, newIndex, ABOVE);
      }
      if (position == ABOVE && myTreeModel.canDrop(oldIndex, newIndex, BELOW)) {
        return Trinity.create(oldIndex, newIndex, BELOW);
      }
      newIndex += direction;
    }
    return null;
  }


  @NotNull
  private static String createUniqueName(DefaultMutableTreeNode typeNode, @Nullable String baseName, NodeKind...kinds) {
    String str = (baseName == null) ? ExecutionBundle.message("run.configuration.unnamed.name.prefix") : baseName;
    List<DefaultMutableTreeNode> configurationNodes = new ArrayList<DefaultMutableTreeNode>();
    collectNodesRecursively(typeNode, configurationNodes, kinds);
    final ArrayList<String> currentNames = new ArrayList<String>();
    for (DefaultMutableTreeNode node : configurationNodes) {
      final Object userObject = node.getUserObject();
      if (userObject instanceof SingleConfigurationConfigurable) {
        currentNames.add(((SingleConfigurationConfigurable)userObject).getNameText());
      }
      else if (userObject instanceof RunnerAndConfigurationSettingsImpl) {
        currentNames.add(((RunnerAndConfigurationSettings)userObject).getName());
      }
      else if (userObject instanceof String) {
        currentNames.add((String)userObject);
      }
    }
    return RunManager.suggestUniqueName(str, currentNames);
  }

  private SingleConfigurationConfigurable<RunConfiguration> createNewConfiguration(final RunnerAndConfigurationSettings settings,
                                                                                   final DefaultMutableTreeNode node,
                                                                                   DefaultMutableTreeNode selectedNode) {
    final SingleConfigurationConfigurable<RunConfiguration> configurationConfigurable =
      SingleConfigurationConfigurable.editSettings(settings, null);
    installUpdateListeners(configurationConfigurable);
    DefaultMutableTreeNode nodeToAdd = new DefaultMutableTreeNode(configurationConfigurable);
    myTreeModel.insertNodeInto(nodeToAdd, node, selectedNode != null ? node.getIndex(selectedNode) + 1 :node.getChildCount());
    TreeUtil.selectNode(myTree, nodeToAdd);
    return configurationConfigurable;
  }

  private void createNewConfiguration(final ConfigurationFactory factory) {
    DefaultMutableTreeNode node = null;
    DefaultMutableTreeNode selectedNode = null;
    TreePath selectionPath = myTree.getSelectionPath();
    if (selectionPath != null) {
      selectedNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
    }
    DefaultMutableTreeNode typeNode = getConfigurationTypeNode(factory.getType());
    if (typeNode == null) {
      typeNode = new DefaultMutableTreeNode(factory.getType());
      myRoot.add(typeNode);
      sortTopLevelBranches();
      ((DefaultTreeModel)myTree.getModel()).reload();
    }
    node = typeNode;
    if (selectedNode != null && typeNode.isNodeDescendant(selectedNode)) {
      node = selectedNode;
      if (getKind(node).isConfiguration()) {
        node = (DefaultMutableTreeNode)node.getParent();
      }
    }
    final RunnerAndConfigurationSettings settings = getRunManager().createConfiguration(createUniqueName(typeNode, null, CONFIGURATION, TEMPORARY_CONFIGURATION), factory);
    if (factory instanceof ConfigurationFactoryEx) {
      ((ConfigurationFactoryEx)factory).onNewConfigurationCreated(settings.getConfiguration());
    }
    createNewConfiguration(settings, node, selectedNode);
  }

  private class MyToolbarAddAction extends AnAction implements AnActionButtonRunnable {
    public MyToolbarAddAction() {
      super(ExecutionBundle.message("add.new.run.configuration.acrtion.name"),
            ExecutionBundle.message("add.new.run.configuration.acrtion.name"), ADD_ICON);
      registerCustomShortcutSet(CommonShortcuts.INSERT, myTree);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      showAddPopup(true);
    }

    @Override
    public void run(AnActionButton button) {
      showAddPopup(true);
    }

    private void showAddPopup(final boolean showApplicableTypesOnly) {
      ConfigurationType[] allTypes = getRunManager().getConfigurationFactories(false);
      final List<ConfigurationType> configurationTypes = getTypesToShow(showApplicableTypesOnly, allTypes);
      Collections.sort(configurationTypes, new Comparator<ConfigurationType>() {
        @Override
        public int compare(final ConfigurationType type1, final ConfigurationType type2) {
          return type1.getDisplayName().compareToIgnoreCase(type2.getDisplayName());
        }
      });
      final int hiddenCount = allTypes.length - configurationTypes.size();
      if (hiddenCount > 0) {
        configurationTypes.add(null);
      }

      final ListPopup popup = JBPopupFactory.getInstance().createListPopup(new BaseListPopupStep<ConfigurationType>(
          ExecutionBundle.message("add.new.run.configuration.acrtion.name"), configurationTypes) {

          @Override
          @NotNull
          public String getTextFor(final ConfigurationType type) {
            return type != null ? type.getDisplayName() :  hiddenCount + " items more (irrelevant)...";
          }

          @Override
          public boolean isSpeedSearchEnabled() {
            return true;
          }

          @Override
          public boolean canBeHidden(ConfigurationType value) {
            return true;
          }

          @Override
          public Icon getIconFor(final ConfigurationType type) {
            return type != null ? type.getIcon() : EmptyIcon.ICON_16;
          }

          @Override
          public PopupStep onChosen(final ConfigurationType type, final boolean finalChoice) {
            if (hasSubstep(type)) {
              return getSupStep(type);
            }
            if (type == null) {
              return doFinalStep(new Runnable() {
                @Override
                public void run() {
                  showAddPopup(false);
                }
              });
            }

            final ConfigurationFactory[] factories = type.getConfigurationFactories();
            if (factories.length > 0) {
              createNewConfiguration(factories[0]);
            }
            return FINAL_CHOICE;
          }

          @Override
          public int getDefaultOptionIndex() {
            ConfigurationType type = getSelectedConfigurationType();
            return type != null ? configurationTypes.indexOf(type) : super.getDefaultOptionIndex();
          }

          private ListPopupStep getSupStep(final ConfigurationType type) {
            final ConfigurationFactory[] factories = type.getConfigurationFactories();
            Arrays.sort(factories, new Comparator<ConfigurationFactory>() {
              @Override
              public int compare(final ConfigurationFactory factory1, final ConfigurationFactory factory2) {
                return factory1.getName().compareToIgnoreCase(factory2.getName());
              }
            });
            return new BaseListPopupStep<ConfigurationFactory>(
              ExecutionBundle.message("add.new.run.configuration.action.name", type.getDisplayName()), factories) {

              @Override
              @NotNull
              public String getTextFor(final ConfigurationFactory value) {
                return value.getName();
              }

              @Override
              public Icon getIconFor(final ConfigurationFactory factory) {
                return factory.getIcon();
              }

              @Override
              public PopupStep onChosen(final ConfigurationFactory factory, final boolean finalChoice) {
                createNewConfiguration(factory);
                return FINAL_CHOICE;
              }
            };
          }

          @Override
          public boolean hasSubstep(final ConfigurationType type) {
            return type != null && type.getConfigurationFactories().length > 1;
          }
        });
      //new TreeSpeedSearch(myTree);
      popup.showUnderneathOf(myToolbarDecorator.getActionsPanel());
    }

    private List<ConfigurationType> getTypesToShow(boolean showApplicableTypesOnly, ConfigurationType[] allTypes) {
      if (showApplicableTypesOnly) {
        List<ConfigurationType> applicableTypes = new ArrayList<ConfigurationType>();
        for (ConfigurationType type : allTypes) {
          if (isApplicable(type)) {
            applicableTypes.add(type);
          }
        }
        if (applicableTypes.size() < allTypes.length - 3) {
          return applicableTypes;
        }
      }
      return new ArrayList<ConfigurationType>(Arrays.asList(allTypes));
    }

    private boolean isApplicable(ConfigurationType type) {
      for (ConfigurationFactory factory : type.getConfigurationFactories()) {
        if (factory.isApplicable(myProject)) {
          return true;
        }
      }
      return false;
    }
  }


  private class MyRemoveAction extends AnAction implements AnActionButtonRunnable, AnActionButtonUpdater{

    public MyRemoveAction() {
      super(ExecutionBundle.message("remove.run.configuration.action.name"),
            ExecutionBundle.message("remove.run.configuration.action.name"), REMOVE_ICON);
      registerCustomShortcutSet(CommonShortcuts.getDelete(), myTree);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      doRemove();
    }

    @Override
    public void run(AnActionButton button) {
      doRemove();
    }

    private void doRemove() {
      TreePath[] selections = myTree.getSelectionPaths();
      myTree.clearSelection();

      int nodeIndexToSelect = -1;
      DefaultMutableTreeNode parentToSelect = null;

      Set<DefaultMutableTreeNode> changedParents = new HashSet<DefaultMutableTreeNode>();
      boolean wasRootChanged = false;

      for (TreePath each : selections) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode)each.getLastPathComponent();
        DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
        NodeKind kind = getKind(node);
        if (!kind.isConfiguration() && kind != FOLDER)
          continue;

        if (node.getUserObject() instanceof SingleConfigurationConfigurable) {
          ((SingleConfigurationConfigurable)node.getUserObject()).disposeUIResources();
        }

        nodeIndexToSelect = parent.getIndex(node);
        parentToSelect = parent;
        myTreeModel.removeNodeFromParent(node);
        changedParents.add(parent);

        if (kind == FOLDER) {
          List<DefaultMutableTreeNode> children = new ArrayList<DefaultMutableTreeNode>();
          for (int i = 0; i < node.getChildCount(); i++) {
            DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i);
            Object userObject = getSafeUserObject(child);
            if (userObject instanceof SingleConfigurationConfigurable) {
              ((SingleConfigurationConfigurable)userObject).setFolderName(null);
            }
            children.add(0, child);
          }
          int confIndex = 0;
          for (int i = 0; i < parent.getChildCount(); i++) {
            if (getKind((DefaultMutableTreeNode)parent.getChildAt(i)).isConfiguration()) {
              confIndex = i;
              break;
            }
          }
          for (DefaultMutableTreeNode child : children) {
            if (getKind(child) == CONFIGURATION)
              myTreeModel.insertNodeInto(child, parent, confIndex);
          }
          confIndex = parent.getChildCount();
          for (int i = 0; i < parent.getChildCount(); i++) {
            if (getKind((DefaultMutableTreeNode)parent.getChildAt(i)) == TEMPORARY_CONFIGURATION) {
              confIndex = i;
              break;
            }
          }
          for (DefaultMutableTreeNode child : children) {
            if (getKind(child) == TEMPORARY_CONFIGURATION)
              myTreeModel.insertNodeInto(child, parent, confIndex);
          }
        }

        if (parent.getChildCount() == 0 && parent.getUserObject() instanceof ConfigurationType) {
          changedParents.remove(parent);
          wasRootChanged = true;

          nodeIndexToSelect = myRoot.getIndex(parent);
          nodeIndexToSelect = Math.max(0, nodeIndexToSelect - 1);
          parentToSelect = myRoot;
          parent.removeFromParent();
        }
      }

      if (wasRootChanged) {
        ((DefaultTreeModel)myTree.getModel()).reload();
      } else {
        for (DefaultMutableTreeNode each : changedParents) {
          myTreeModel.reload(each);
          myTree.expandPath(new TreePath(each));
        }
      }

      mySelectedConfigurable = null;
      if (myRoot.getChildCount() == 0) {
        drawPressAddButtonMessage(null);
      }
      else {
        if (parentToSelect.getChildCount() > 0) {
          TreeNode nodeToSelect = nodeIndexToSelect < parentToSelect.getChildCount()
                                  ? parentToSelect.getChildAt(nodeIndexToSelect)
                                  : parentToSelect.getChildAt(nodeIndexToSelect - 1);
          TreeUtil.selectInTree((DefaultMutableTreeNode)nodeToSelect, true, myTree);
        }
      }
    }


    @Override
    public void update(AnActionEvent e) {
      boolean enabled = isEnabled(e);
      e.getPresentation().setEnabled(enabled);
    }

    @Override
    public boolean isEnabled(AnActionEvent e) {
      boolean enabled = false;
      TreePath[] selections = myTree.getSelectionPaths();
      if (selections != null) {
        for (TreePath each : selections) {
          NodeKind kind = getKind((DefaultMutableTreeNode)each.getLastPathComponent());
          if (kind.isConfiguration() || kind == FOLDER) {
            enabled = true;
            break;
          }
        }
      }
      return enabled;
    }
  }

  private class MyCopyAction extends AnAction {
    public MyCopyAction() {
      super(ExecutionBundle.message("copy.configuration.action.name"),
            ExecutionBundle.message("copy.configuration.action.name"),
            PlatformIcons.COPY_ICON);

      final AnAction action = ActionManager.getInstance().getAction(IdeActions.ACTION_EDITOR_DUPLICATE);
      registerCustomShortcutSet(action.getShortcutSet(), myTree);
    }


    @Override
    public void actionPerformed(AnActionEvent e) {
      final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
      LOG.assertTrue(configuration != null);
      try {
        final DefaultMutableTreeNode typeNode = getSelectedConfigurationTypeNode();
        final RunnerAndConfigurationSettings settings = configuration.getSnapshot();
        final String copyName = createUniqueName(typeNode, configuration.getNameText(), CONFIGURATION, TEMPORARY_CONFIGURATION);
        settings.setName(copyName);
        final ConfigurationFactory factory = settings.getFactory();
        if (factory instanceof ConfigurationFactoryEx) {
          ((ConfigurationFactoryEx)factory).onConfigurationCopied(settings.getConfiguration());
        }
        final SingleConfigurationConfigurable<RunConfiguration> configurable = createNewConfiguration(settings, typeNode, getSelectedNode());
        IdeFocusManager.getInstance(myProject).requestFocus(configurable.getNameTextField(), true);
        configurable.getNameTextField().setSelectionStart(0);
        configurable.getNameTextField().setSelectionEnd(copyName.length());
      }
      catch (ConfigurationException e1) {
        Messages.showErrorDialog(myToolbarDecorator.getActionsPanel(), e1.getMessage(), e1.getTitle());
      }
    }

    @Override
    public void update(AnActionEvent e) {
      final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
      e.getPresentation().setEnabled(configuration != null && !(configuration.getConfiguration() instanceof UnknownRunConfiguration));
    }
  }

  private class MySaveAction extends AnAction {

    public MySaveAction() {
      super(ExecutionBundle.message("action.name.save.configuration"), null, AllIcons.Actions.Menu_saveall);
    }

    @Override
    public void actionPerformed(final AnActionEvent e) {
      final SingleConfigurationConfigurable<RunConfiguration> configurationConfigurable = getSelectedConfiguration();
      LOG.assertTrue(configurationConfigurable != null);
      try {
        configurationConfigurable.apply();
      }
      catch (ConfigurationException e1) {
        //do nothing
      }
      final RunnerAndConfigurationSettings originalConfiguration = configurationConfigurable.getSettings();
      if (originalConfiguration.isTemporary()) {
        getRunManager().makeStable(originalConfiguration);
        adjustOrder();
      }
      myTree.repaint();
    }

    @Override
    public void update(final AnActionEvent e) {
      final SingleConfigurationConfigurable<RunConfiguration> configuration = getSelectedConfiguration();
      final Presentation presentation = e.getPresentation();
      final boolean enabled;
      if (configuration == null) {
        enabled = false;
      } else {
        RunnerAndConfigurationSettings settings = configuration.getSettings();
        enabled = settings != null && settings.isTemporary();
      }
      presentation.setEnabled(enabled);
      presentation.setVisible(enabled);
    }
  }

  /**
   * Just saved as 'stable' configuration shouldn't stay between temporary ones (here we order nodes in JTree only)
   * @return shift (positive) for move configuration "up" to other stable configurations. Zero means "there is nothing to change"
   */


  private int adjustOrder() {
    TreePath selectionPath = myTree.getSelectionPath();
    if (selectionPath == null)
      return 0;
    final DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)selectionPath.getLastPathComponent();
    RunnerAndConfigurationSettings selectedSettings = getSettings(treeNode);
    if (selectedSettings == null || selectedSettings.isTemporary())
      return 0;
    MutableTreeNode parent = (MutableTreeNode)treeNode.getParent();
    int initialPosition = parent.getIndex(treeNode);
    int position = initialPosition;
    DefaultMutableTreeNode node = treeNode.getPreviousSibling();
    while (node != null) {
      RunnerAndConfigurationSettings settings = getSettings(node);
      if (settings != null && settings.isTemporary()) {
        position--;
      } else {
        break;
      }
      node = node.getPreviousSibling();
    }
    for (int i = 0; i < initialPosition - position; i++) {
      TreeUtil.moveSelectedRow(myTree, -1);
    }
    return initialPosition - position;
  }

  private class MyMoveAction extends AnAction implements AnActionButtonRunnable, AnActionButtonUpdater {
    private final int myDirection;

    protected MyMoveAction(String text, String description, Icon icon, int direction) {
      super(text, description, icon);
      myDirection = direction;
    }

    @Override
    public void actionPerformed(final AnActionEvent e) {
      doMove();
    }

    private void doMove() {
      Trinity<Integer, Integer, RowsDnDSupport.RefinedDropSupport.Position> dropPosition = getAvailableDropPosition(myDirection);
      if (dropPosition != null) {
        myTreeModel.drop(dropPosition.first, dropPosition.second, dropPosition.third);
      }
    }

    @Override
    public void run(AnActionButton button) {
      doMove();
    }

    @Override
    public void update(final AnActionEvent e) {
      e.getPresentation().setEnabled(isEnabled(e));
    }

    @Override
    public boolean isEnabled(AnActionEvent e) {
      return getAvailableDropPosition(myDirection) != null;
    }
  }

  private class MyEditDefaultsAction extends AnAction {
    public MyEditDefaultsAction() {
      super(ExecutionBundle.message("run.configuration.edit.default.configuration.settings.text"),
            ExecutionBundle.message("run.configuration.edit.default.configuration.settings.description"), AllIcons.General.Settings);
    }

    @Override
    public void actionPerformed(final AnActionEvent e) {
      TreeNode defaults = TreeUtil.findNodeWithObject(DEFAULTS, myTree.getModel(), myRoot);
      if (defaults != null) {
        final ConfigurationType configurationType = getSelectedConfigurationType();
        if (configurationType != null) {
          defaults = TreeUtil.findNodeWithObject(configurationType, myTree.getModel(), defaults);
        }
        final DefaultMutableTreeNode defaultsNode = (DefaultMutableTreeNode)defaults;
        if (defaultsNode == null) {
          return;
        }
        final TreePath path = TreeUtil.getPath(myRoot, defaultsNode);
        myTree.expandPath(path);
        TreeUtil.selectInTree(defaultsNode, true, myTree);
        myTree.scrollPathToVisible(path);
      }
    }

    @Override
    public void update(AnActionEvent e) {
      boolean isEnabled = TreeUtil.findNodeWithObject(DEFAULTS, myTree.getModel(), myRoot) != null;
      TreePath path = myTree.getSelectionPath();
      if (path != null) {
        Object o = path.getLastPathComponent();
        if (o instanceof DefaultMutableTreeNode && ((DefaultMutableTreeNode)o).getUserObject().equals(DEFAULTS)) {
          isEnabled = false;
        }
        o = path.getParentPath().getLastPathComponent();
        if (o instanceof DefaultMutableTreeNode && ((DefaultMutableTreeNode)o).getUserObject().equals(DEFAULTS)) {
          isEnabled = false;
        }
      }
      e.getPresentation().setEnabled(isEnabled);
    }
  }

  private class MyCreateFolderAction extends AnAction {
    private MyCreateFolderAction() {
      super(ExecutionBundle.message("run.configuration.create.folder.text"),
            ExecutionBundle.message("run.configuration.create.folder.description"), AllIcons.Nodes.Folder);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      final ConfigurationType type = getSelectedConfigurationType();
      if (type == null) {
        return;
      }
      final DefaultMutableTreeNode[] selectedNodes = getSelectedNodes();
      DefaultMutableTreeNode typeNode = getConfigurationTypeNode(type);
      if (typeNode == null) {
        return;
      }
      String folderName = createUniqueName(typeNode, "New Folder", FOLDER);
      List<DefaultMutableTreeNode> folders = new ArrayList<DefaultMutableTreeNode>();
      collectNodesRecursively(getConfigurationTypeNode(type), folders, FOLDER);
      final DefaultMutableTreeNode folderNode = new DefaultMutableTreeNode(folderName);
      myTreeModel.insertNodeInto(folderNode, typeNode, folders.size());
      isFolderCreating = true;
      try {
        for (DefaultMutableTreeNode node : selectedNodes) {
          int folderRow = myTree.getRowForPath(new TreePath(folderNode.getPath()));
          int rowForPath = myTree.getRowForPath(new TreePath(node.getPath()));
          if (getKind(node).isConfiguration() && myTreeModel.canDrop(rowForPath, folderRow, INTO)) {
            myTreeModel.drop(rowForPath, folderRow, INTO);
          }
        }
        myTree.setSelectionPath(new TreePath(folderNode.getPath()));
      }
      finally {
        isFolderCreating = false;
      }
    }

    @Override
    public void update(AnActionEvent e) {
      boolean isEnabled = false;
      boolean toMove = false;
      DefaultMutableTreeNode[] selectedNodes = getSelectedNodes();
      ConfigurationType selectedType = null;
      for (DefaultMutableTreeNode node : selectedNodes) {
        ConfigurationType type = getType(node);
        if (selectedType == null) {
          selectedType = type;
        } else {
          if (!Comparing.equal(type, selectedType)) {
            isEnabled = false;
            break;
          }
        }
        NodeKind kind = getKind(node);
        if (kind.isConfiguration() || (kind == CONFIGURATION_TYPE && node.getParent() == myRoot) || kind == FOLDER) {
          isEnabled = true;
        }
        if (kind.isConfiguration()) {
          toMove = true;
        }
      }
      e.getPresentation().setText(ExecutionBundle.message("run.configuration.create.folder.description" + (toMove ? ".move" : "")));
      e.getPresentation().setEnabled(isEnabled);
    }
  }

  private class MySortFolderAction extends AnAction implements Comparator<DefaultMutableTreeNode>{
    private MySortFolderAction() {
      super(ExecutionBundle.message("run.configuration.sort.folder.text"),
            ExecutionBundle.message("run.configuration.sort.folder.description"), AllIcons.Icons.Inspector.SortByName);
    }

    @Override
    public int compare(DefaultMutableTreeNode node1, DefaultMutableTreeNode node2) {
      NodeKind kind1 = getKind(node1);
      NodeKind kind2 = getKind(node2);
      if (kind1 == FOLDER) {
        return  (kind2 == FOLDER) ? node1.getParent().getIndex(node1) - node2.getParent().getIndex(node2) : -1;
      }
      if (kind2 == FOLDER) {
        return 1;
      }
      String name1 = getName(node1.getUserObject());
      String name2 = getName(node2.getUserObject());
      if (kind1 == TEMPORARY_CONFIGURATION) {
        return (kind2 == TEMPORARY_CONFIGURATION) ? name1.compareTo(name2) : 1;
      }
      if (kind2 == TEMPORARY_CONFIGURATION) {
        return -1;
      }
      return name1.compareTo(name2);
    }

    @Override
    public void actionPerformed(AnActionEvent e) {
      final DefaultMutableTreeNode[] selectedNodes = getSelectedNodes();
      List<DefaultMutableTreeNode> foldersToSort = new ArrayList<DefaultMutableTreeNode>();
      for (DefaultMutableTreeNode node : selectedNodes) {
        NodeKind kind = getKind(node);
        if (kind == CONFIGURATION_TYPE || kind == FOLDER) {
          foldersToSort.add(node);
        }
      }
      for (DefaultMutableTreeNode folderNode : foldersToSort) {
        List<DefaultMutableTreeNode> children = new ArrayList<DefaultMutableTreeNode>();
        for (int i = 0; i < folderNode.getChildCount(); i++) {
          DefaultMutableTreeNode child = (DefaultMutableTreeNode)folderNode.getChildAt(i);
          children.add(child);
        }
        Collections.sort(children, this);
        for (DefaultMutableTreeNode child : children) {
          folderNode.add(child);
        }
        myTreeModel.nodeStructureChanged(folderNode);
      }
    }

    @Override
    public void update(AnActionEvent e) {
      final DefaultMutableTreeNode[] selectedNodes = getSelectedNodes();
      for (DefaultMutableTreeNode node : selectedNodes) {
        NodeKind kind = getKind(node);
        if (kind == CONFIGURATION_TYPE || kind == FOLDER) {
          e.getPresentation().setEnabled(true);
          return;
        }
      }
      e.getPresentation().setEnabled(false);
    }
  }

  @Nullable
  private static ConfigurationType getType(DefaultMutableTreeNode node) {
    while (node != null) {
      if (node.getUserObject() instanceof ConfigurationType) {
        return (ConfigurationType)node.getUserObject();
      }
      node = (DefaultMutableTreeNode)node.getParent();
    }
    return null;
  }

  @NotNull
  private DefaultMutableTreeNode[] getSelectedNodes() {
    return myTree.getSelectedNodes(DefaultMutableTreeNode.class, null);
  }

  @Nullable
  private DefaultMutableTreeNode getSelectedNode() {
    DefaultMutableTreeNode[] nodes = myTree.getSelectedNodes(DefaultMutableTreeNode.class, null);
    return nodes.length >= 1 ? nodes[0] : null;
  }

  @Nullable
  private RunnerAndConfigurationSettings getSelectedSettings() {
    TreePath selectionPath = myTree.getSelectionPath();
    if (selectionPath == null)
      return null;
    return getSettings((DefaultMutableTreeNode)selectionPath.getLastPathComponent());
  }

  @Nullable
  private static RunnerAndConfigurationSettings getSettings(DefaultMutableTreeNode treeNode) {
    if (treeNode == null)
      return null;
    RunnerAndConfigurationSettings settings = null;
    if (treeNode.getUserObject() instanceof SingleConfigurationConfigurable) {
      settings = (RunnerAndConfigurationSettings)((SingleConfigurationConfigurable)treeNode.getUserObject()).getSettings();
    }
    if (treeNode.getUserObject() instanceof RunnerAndConfigurationSettings) {
      settings = (RunnerAndConfigurationSettings)treeNode.getUserObject();
    }
    return settings;
  }

  private static class RunConfigurationBean {
    private final RunnerAndConfigurationSettings mySettings;
    private final boolean myShared;
    private final List<BeforeRunTask> myStepsBeforeLaunch;
    private final SingleConfigurationConfigurable myConfigurable;

    public RunConfigurationBean(final RunnerAndConfigurationSettings settings,
                                final boolean shared,
                                final List<BeforeRunTask> stepsBeforeLaunch) {
      mySettings = settings;
      myShared = shared;
      myStepsBeforeLaunch = Collections.unmodifiableList(stepsBeforeLaunch);
      myConfigurable = null;
    }

    public RunConfigurationBean(final SingleConfigurationConfigurable configurable) {
      myConfigurable = configurable;
      mySettings = (RunnerAndConfigurationSettings)myConfigurable.getSettings();
      final ConfigurationSettingsEditorWrapper editorWrapper = (ConfigurationSettingsEditorWrapper)myConfigurable.getEditor();
      myShared = configurable.isStoreProjectConfiguration();
      myStepsBeforeLaunch = editorWrapper.getStepsBeforeLaunch();
    }

    public RunnerAndConfigurationSettings getSettings() {
      return mySettings;
    }

    public boolean isShared() {
      return myShared;
    }

    public List<BeforeRunTask> getStepsBeforeLaunch() {
      return myStepsBeforeLaunch;
    }

    public SingleConfigurationConfigurable getConfigurable() {
      return myConfigurable;
    }

    @Override
    public String toString() {
      return String.valueOf(mySettings);
    }
  }

  public interface RunDialogBase {
    void setOKActionEnabled(boolean isEnabled);

    @Nullable
    Executor getExecutor();

    void setTitle(String title);

    void clickDefaultButton();
  }

  enum NodeKind {
    CONFIGURATION_TYPE, FOLDER, CONFIGURATION, TEMPORARY_CONFIGURATION, UNKNOWN;

    boolean supportsDnD() {
      return this == FOLDER || this == CONFIGURATION || this == TEMPORARY_CONFIGURATION;
    }

    boolean isConfiguration() {
      return this == CONFIGURATION | this == TEMPORARY_CONFIGURATION;
    }
  }

  @NotNull
  static NodeKind getKind(@Nullable DefaultMutableTreeNode node) {
    if (node == null)
      return UNKNOWN;
    Object userObject = node.getUserObject();
    if (userObject instanceof SingleConfigurationConfigurable || userObject instanceof RunnerAndConfigurationSettings) {
      RunnerAndConfigurationSettings settings = getSettings(node);
      if (settings == null) {
        return UNKNOWN;
      }
      return settings.isTemporary() ? TEMPORARY_CONFIGURATION : CONFIGURATION;
    }
    if (userObject instanceof String) {
      return FOLDER;
    }
    if (userObject instanceof ConfigurationType) {
      return CONFIGURATION_TYPE;
    }
    return UNKNOWN;
  }

  class MyTreeModel extends DefaultTreeModel implements EditableModel, RowsDnDSupport.RefinedDropSupport {
    private MyTreeModel(TreeNode root) {
      super(root);
    }

    @Override
    public void addRow() {
    }

    @Override
    public void removeRow(int index) {
    }

    @Override
    public void exchangeRows(int oldIndex, int newIndex) {
      //Do nothing, use drop() instead
    }

    @Override
    public boolean canExchangeRows(int oldIndex, int newIndex) {
      return false;//Legacy, use canDrop() instead
    }

    @Override
    public boolean canDrop(int oldIndex, int newIndex, @NotNull Position position) {
      if (myTree.getRowCount() <= oldIndex || myTree.getRowCount() <= newIndex || oldIndex < 0 || newIndex < 0) {
        return false;
      }
      DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode)myTree.getPathForRow(oldIndex).getLastPathComponent();
      DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)myTree.getPathForRow(newIndex).getLastPathComponent();
      DefaultMutableTreeNode oldParent = (DefaultMutableTreeNode)oldNode.getParent();
      DefaultMutableTreeNode newParent = (DefaultMutableTreeNode)newNode.getParent();
      NodeKind oldKind = getKind(oldNode);
      NodeKind newKind = getKind(newNode);
      ConfigurationType oldType = getType(oldNode);
      ConfigurationType newType = getType(newNode);
      if (oldParent == newParent) {
        if (oldNode.getPreviousSibling() == newNode && position == BELOW) {
          return false;
        }
        if (oldNode.getNextSibling() == newNode && position == ABOVE) {
          return false;
        }
      }
      if (oldType == null)
        return false;
      if (oldType != newType) {
        DefaultMutableTreeNode typeNode = getConfigurationTypeNode(oldType);
        if (getKind(oldParent) == FOLDER && typeNode != null && typeNode.getNextSibling() == newNode && position == ABOVE) {
          return true;
        }
        if (getKind(oldParent) == CONFIGURATION_TYPE &&
            oldKind == FOLDER &&
            typeNode != null &&
            typeNode.getNextSibling() == newNode &&
            position == ABOVE &&
            oldParent.getLastChild() != oldNode &&
            getKind((DefaultMutableTreeNode)oldParent.getLastChild()) == FOLDER) {
          return true;
        }
        return false;
      }
      if (newParent == oldNode || oldParent == newNode)
        return false;
      if (oldKind == FOLDER && newKind != FOLDER) {
        if (newKind.isConfiguration() &&
            position == ABOVE &&
            getKind(newParent) == CONFIGURATION_TYPE &&
            newIndex > 1 &&
            getKind((DefaultMutableTreeNode)myTree.getPathForRow(newIndex - 1).getParentPath().getLastPathComponent()) == FOLDER) {
          return true;
        }
        return false;
      }
      if (!oldKind.supportsDnD() || !newKind.supportsDnD()) {
        return false;
      }
      if (oldKind.isConfiguration() && newKind == FOLDER && position == ABOVE)
        return false;
      if (oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == ABOVE)
        return false;
      if (oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == BELOW)
        return false;
      if (oldKind == CONFIGURATION && newKind == TEMPORARY_CONFIGURATION && position == ABOVE) {
        return newNode.getPreviousSibling() == null ||
               getKind(newNode.getPreviousSibling()) == CONFIGURATION ||
               getKind(newNode.getPreviousSibling()) == FOLDER;
      }
      if (oldKind == TEMPORARY_CONFIGURATION && newKind == CONFIGURATION && position == BELOW)
        return newNode.getNextSibling() == null || getKind(newNode.getNextSibling()) == TEMPORARY_CONFIGURATION;
      if (oldParent == newParent) { //Same parent
        if (oldKind.isConfiguration() && newKind.isConfiguration()) {
          return oldKind == newKind;//both are temporary or saved
        } else if (oldKind == FOLDER) {
          return !myTree.isExpanded(newIndex) || position == ABOVE;
        }
      }
      return true;
    }

    @Override
    public boolean isDropInto(JComponent component, int oldIndex, int newIndex) {
      TreePath oldPath = myTree.getPathForRow(oldIndex);
      TreePath newPath = myTree.getPathForRow(newIndex);
      if (oldPath == null || newPath == null) {
        return false;
      }
      DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode)oldPath.getLastPathComponent();
      DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)newPath.getLastPathComponent();
      return getKind(oldNode).isConfiguration() && getKind(newNode) == FOLDER;
    }

    @Override
    public void drop(int oldIndex, int newIndex, @NotNull Position position) {
      DefaultMutableTreeNode oldNode = (DefaultMutableTreeNode)myTree.getPathForRow(oldIndex).getLastPathComponent();
      DefaultMutableTreeNode newNode = (DefaultMutableTreeNode)myTree.getPathForRow(newIndex).getLastPathComponent();
      DefaultMutableTreeNode newParent = (DefaultMutableTreeNode)newNode.getParent();
      NodeKind oldKind = getKind(oldNode);
      boolean wasExpanded = myTree.isExpanded(new TreePath(oldNode.getPath()));
      if (isDropInto(myTree, oldIndex, newIndex)) { //Drop in folder
        removeNodeFromParent(oldNode);
        int index = newNode.getChildCount();
        if (oldKind.isConfiguration()) {
          int middleIndex = newNode.getChildCount();
          for (int i = 0; i < newNode.getChildCount(); i++) {
            if (getKind((DefaultMutableTreeNode)newNode.getChildAt(i)) == TEMPORARY_CONFIGURATION) {
              middleIndex = i;//index of first temporary configuration in target folder
              break;
            }
          }
          if (position != INTO) {
            if (oldIndex < newIndex) {
              index = oldKind == CONFIGURATION ? 0 : middleIndex;
            }
            else {
              index = oldKind == CONFIGURATION ? middleIndex : newNode.getChildCount();
            }
          } else {
            index = oldKind == TEMPORARY_CONFIGURATION ? newNode.getChildCount() : middleIndex;
          }
        }
        insertNodeInto(oldNode, newNode, index);
        myTree.expandPath(new TreePath(newNode.getPath()));
      }
      else {
        ConfigurationType type = getType(oldNode);
        assert type != null;
        removeNodeFromParent(oldNode);
        int index;
        if (type != getType(newNode)) {
          DefaultMutableTreeNode typeNode = getConfigurationTypeNode(type);
          assert typeNode != null;
          newParent = typeNode;
          index = newParent.getChildCount();
        } else {
          index = newParent.getIndex(newNode);
          if (position == BELOW)
            index++;
        }
        insertNodeInto(oldNode, newParent, index);
      }
      TreePath treePath = new TreePath(oldNode.getPath());
      myTree.setSelectionPath(treePath);
      if (wasExpanded) {
        myTree.expandPath(treePath);
      }
    }

    @Override
    public void insertNodeInto(MutableTreeNode newChild, MutableTreeNode parent, int index) {
      super.insertNodeInto(newChild, parent, index);
      if (!getKind((DefaultMutableTreeNode)newChild).isConfiguration()) {
        return;
      }
      Object userObject = getSafeUserObject((DefaultMutableTreeNode)newChild);
      String newFolderName = getKind((DefaultMutableTreeNode)parent) == FOLDER
                             ? (String)((DefaultMutableTreeNode)parent).getUserObject()
                             : null;
      if (userObject instanceof SingleConfigurationConfigurable) {
        ((SingleConfigurationConfigurable)userObject).setFolderName(newFolderName);
      }
    }

    @Override
    public void reload(TreeNode node) {
      super.reload(node);
      Object userObject = ((DefaultMutableTreeNode)node).getUserObject();
      if (userObject instanceof String) {
        String folderName = (String)userObject;
        for (int i = 0; i < node.getChildCount(); i++) {
          DefaultMutableTreeNode child = (DefaultMutableTreeNode)node.getChildAt(i);
          Object safeUserObject = getSafeUserObject(child);
          if (safeUserObject instanceof SingleConfigurationConfigurable) {
            ((SingleConfigurationConfigurable)safeUserObject).setFolderName(folderName);
          }
        }
      }
    }

    @Nullable
    private RunnerAndConfigurationSettings getSettings(@NotNull DefaultMutableTreeNode treeNode) {
      Object userObject = treeNode.getUserObject();
      if (userObject instanceof SingleConfigurationConfigurable) {
        SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
        return (RunnerAndConfigurationSettings)configurable.getSettings();
      } else if (userObject instanceof RunnerAndConfigurationSettings) {
        return (RunnerAndConfigurationSettings)userObject;
      }
      return null;
    }

    @Nullable
    private ConfigurationType getType(@Nullable DefaultMutableTreeNode treeNode) {
      if (treeNode == null)
        return null;
      Object userObject = treeNode.getUserObject();
      if (userObject instanceof SingleConfigurationConfigurable) {
        SingleConfigurationConfigurable configurable = (SingleConfigurationConfigurable)userObject;
        return configurable.getConfiguration().getType();
      } else if (userObject instanceof RunnerAndConfigurationSettings) {
        return ((RunnerAndConfigurationSettings)userObject).getType();
      } else if (userObject instanceof ConfigurationType) {
        return (ConfigurationType)userObject;
      }
      if (treeNode.getParent() instanceof DefaultMutableTreeNode) {
        return getType((DefaultMutableTreeNode)treeNode.getParent());
      }
      return null;
    }
  }
}