summaryrefslogtreecommitdiff
path: root/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java
blob: 87f9e2cb3332f3616811730591510cce83ec75e6 (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
/*
 * Copyright 2000-2012 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.designer.designSurface;

import com.intellij.designer.*;
import com.intellij.designer.actions.AbstractComboBoxAction;
import com.intellij.designer.actions.CommonEditActionsProvider;
import com.intellij.designer.actions.DesignerActionPanel;
import com.intellij.designer.componentTree.TreeComponentDecorator;
import com.intellij.designer.componentTree.TreeEditableArea;
import com.intellij.designer.designSurface.tools.*;
import com.intellij.designer.model.*;
import com.intellij.designer.palette.PaletteGroup;
import com.intellij.designer.palette.PaletteItem;
import com.intellij.designer.palette.PaletteToolWindowManager;
import com.intellij.designer.propertyTable.InplaceContext;
import com.intellij.designer.propertyTable.PropertyTableTab;
import com.intellij.designer.propertyTable.TablePanelActionPolicy;
import com.intellij.diagnostic.AttachmentFactory;
import com.intellij.diagnostic.LogMessageEx;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.diagnostic.Attachment;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.ThreeComponentsSplitter;
import com.intellij.openapi.ui.VerticalFlowLayout;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.HyperlinkLabel;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.JBColor;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.components.JBLabel;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.ThrowableRunnable;
import com.intellij.util.containers.IntArrayList;
import com.intellij.util.ui.AsyncProcessIcon;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.List;

/**
 * @author Alexander Lobas
 */
public abstract class DesignerEditorPanel extends JPanel
  implements DesignerEditorPanelFacade, DataProvider, ModuleProvider, RadPropertyContext {
  private static final Logger LOG = Logger.getInstance("#com.intellij.designer.designSurface.DesignerEditorPanel");

  protected static final Integer LAYER_COMPONENT = JLayeredPane.DEFAULT_LAYER;
  protected static final Integer LAYER_DECORATION = JLayeredPane.POPUP_LAYER;
  protected static final Integer LAYER_FEEDBACK = JLayeredPane.DRAG_LAYER;
  protected static final Integer LAYER_GLASS = LAYER_FEEDBACK + 100;
  protected static final Integer LAYER_INPLACE_EDITING = LAYER_GLASS + 100;
  private static final Integer LAYER_PROGRESS = LAYER_INPLACE_EDITING + 100;

  private final static String DESIGNER_CARD = "designer";
  private final static String ERROR_CARD = "error";
  private final static String ERROR_STACK_CARD = "stack";
  private final static String ERROR_NO_STACK_CARD = "no_stack";

  private final DesignerEditor myEditor;
  private final Project myProject;
  private Module myModule;
  protected final VirtualFile myFile;

  private final CardLayout myLayout = new CardLayout();
  private final ThreeComponentsSplitter myContentSplitter = new ThreeComponentsSplitter();
  private final JPanel myPanel = new JPanel(myLayout);
  private JComponent myDesignerCard;

  protected DesignerActionPanel myActionPanel;

  protected CaptionPanel myHorizontalCaption;
  protected CaptionPanel myVerticalCaption;

  protected JScrollPane myScrollPane;
  protected JLayeredPane myLayeredPane;
  protected GlassLayer myGlassLayer;
  private DecorationLayer myDecorationLayer;
  private FeedbackLayer myFeedbackLayer;
  private InplaceEditingLayer myInplaceEditingLayer;

  protected ToolProvider myToolProvider;
  protected EditableArea mySurfaceArea;

  protected RadComponent myRootComponent;

  protected QuickFixManager myQuickFixManager;

  private PaletteItem myActivePaletteItem;
  private List<?> myExpandedComponents;
  private final Map<String, Property> mySelectionPropertyMap = new HashMap<String, Property>();
  private int[][] myExpandedState;
  private int[][] mySelectionState;
  private final Map<String, int[][]> mySourceSelectionState = new FixedHashMap<String, int[][]>(16);

  private FixableMessageAction myWarnAction;

  private JPanel myErrorPanel;
  protected JPanel myErrorMessages;
  private JPanel myErrorStackPanel;
  private CardLayout myErrorStackLayout;
  private JTextArea myErrorStack;

  private JPanel myProgressPanel;
  private AsyncProcessIcon myProgressIcon;
  private JLabel myProgressMessage;

  protected String myLastExecuteCommand;

  public DesignerEditorPanel(@NotNull DesignerEditor editor, @NotNull Project project, Module module, @NotNull VirtualFile file) {
    myEditor = editor;
    myProject = project;
    myModule = module;
    myFile = file;

    initUI();

    myToolProvider.loadDefaultTool();
  }

  private void initUI() {
    setLayout(new BorderLayout());

    myContentSplitter.setDividerWidth(0);
    myContentSplitter.setDividerMouseZoneSize(Registry.intValue("ide.splitter.mouseZone"));
    add(myContentSplitter, BorderLayout.CENTER);

    createDesignerCard();
    createErrorCard();
    createProgressPanel();

    UIUtil.invokeLaterIfNeeded(new Runnable() {
      @Override
      public void run() {
        DesignerEditorPanel designer = DesignerEditorPanel.this;
        getDesignerWindowManager().bind(designer);
        getPaletteWindowManager().bind(designer);
      }
    });
  }

  private void createDesignerCard() {
    JPanel panel = new JPanel(new LightFillLayout());
    myContentSplitter.setInnerComponent(panel);

    myLayeredPane = new MyLayeredPane();

    mySurfaceArea = createEditableArea();

    myToolProvider = createToolProvider();

    myGlassLayer = createGlassLayer(myToolProvider, mySurfaceArea);
    myLayeredPane.add(myGlassLayer, LAYER_GLASS);

    myDecorationLayer = createDecorationLayer();
    myLayeredPane.add(myDecorationLayer, LAYER_DECORATION);

    myFeedbackLayer = createFeedbackLayer();
    myLayeredPane.add(myFeedbackLayer, LAYER_FEEDBACK);

    myInplaceEditingLayer = createInplaceEditingLayer();
    myLayeredPane.add(myInplaceEditingLayer, LAYER_INPLACE_EDITING);

    myScrollPane = createScrollPane(myLayeredPane);

    myQuickFixManager = new QuickFixManager(this, myGlassLayer, myScrollPane.getViewport());

    myActionPanel = createActionPanel();
    myWarnAction = new FixableMessageAction();

    panel.add(myActionPanel.getToolbarComponent());
    panel.add(myPanel);

    myDesignerCard = createDesignerCardPanel();
    myPanel.add(myDesignerCard, DESIGNER_CARD);

    mySurfaceArea.addSelectionListener(new ComponentSelectionListener() {
      @Override
      public void selectionChanged(EditableArea area) {
        storeSourceSelectionState();
      }
    });
  }

  protected JComponent createDesignerCardPanel() {
    JPanel content = new JPanel(new GridBagLayout());

    GridBagConstraints gbc = new GridBagConstraints();

    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.fill = GridBagConstraints.VERTICAL;

    myVerticalCaption = createCaptionPanel(false);
    content.add(myVerticalCaption, gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    gbc.fill = GridBagConstraints.HORIZONTAL;

    myHorizontalCaption = createCaptionPanel(true);
    content.add(myHorizontalCaption, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.weightx = 1;
    gbc.weighty = 1;
    gbc.fill = GridBagConstraints.BOTH;

    content.add(myScrollPane, gbc);

    myHorizontalCaption.attachToScrollPane(myScrollPane);
    myVerticalCaption.attachToScrollPane(myScrollPane);

    return content;
  }

  public final ThreeComponentsSplitter getContentSplitter() {
    return myContentSplitter;
  }

  protected EditableArea createEditableArea() {
    return new DesignerEditableArea();
  }

  protected ToolProvider createToolProvider() {
    return new DesignerToolProvider();
  }

  protected GlassLayer createGlassLayer(ToolProvider provider, EditableArea area) {
    return new GlassLayer(provider, area);
  }

  protected DecorationLayer createDecorationLayer() {
    return new DecorationLayer(this, mySurfaceArea);
  }

  protected FeedbackLayer createFeedbackLayer() {
    return new FeedbackLayer(this);
  }

  protected InplaceEditingLayer createInplaceEditingLayer() {
    return new InplaceEditingLayer(this);
  }

  protected CaptionPanel createCaptionPanel(boolean horizontal) {
    return new CaptionPanel(this, horizontal, true);
  }

  protected JScrollPane createScrollPane(@NotNull JLayeredPane content) {
    JScrollPane scrollPane = ScrollPaneFactory.createScrollPane(content);
    scrollPane.setBackground(new JBColor(Color.WHITE, UIUtil.getListBackground()));
    return scrollPane;
  }

  protected DesignerActionPanel createActionPanel() {
    return new DesignerActionPanel(this, myGlassLayer);
  }

  @Nullable
  public final PaletteItem getActivePaletteItem() {
    return myActivePaletteItem;
  }

  public final void activatePaletteItem(@Nullable PaletteItem paletteItem) {
    myActivePaletteItem = paletteItem;
    if (paletteItem != null) {
      myToolProvider.setActiveTool(new CreationTool(true, createCreationFactory(paletteItem)));
    }
    else if (myToolProvider.getActiveTool() instanceof CreationTool) {
      myToolProvider.loadDefaultTool();
    }
  }

  protected final void showDesignerCard() {
    myErrorMessages.removeAll();
    myErrorStack.setText(null);
    myLayeredPane.revalidate();

    if (myHorizontalCaption != null) {
      myHorizontalCaption.update();
    }
    if (myVerticalCaption != null) {
      myVerticalCaption.update();
    }

    myLayout.show(myPanel, DESIGNER_CARD);
  }

  private void createErrorCard() {
    myErrorPanel = new JPanel(new BorderLayout());
    myErrorMessages = new JPanel(new VerticalFlowLayout(VerticalFlowLayout.TOP, 10, 5, true, false));
    myErrorPanel.add(myErrorMessages, BorderLayout.PAGE_START);

    myErrorStack = new JTextArea(50, 20);
    myErrorStack.setEditable(false);

    myErrorStackLayout = new CardLayout();
    myErrorStackPanel = new JPanel(myErrorStackLayout);
    myErrorStackPanel.add(new JLabel(), ERROR_NO_STACK_CARD);
    myErrorStackPanel.add(ScrollPaneFactory.createScrollPane(myErrorStack), ERROR_STACK_CARD);

    myErrorPanel.add(myErrorStackPanel, BorderLayout.CENTER);

    myPanel.add(myErrorPanel, ERROR_CARD);
  }

  public final void showError(@NotNull String message, @NotNull Throwable e) {
    if (isProjectClosed()) {
      return;
    }

    while (e instanceof InvocationTargetException) {
      if (e.getCause() == null) {
        break;
      }
      e = e.getCause();
    }

    ErrorInfo info = new ErrorInfo();
    info.myMessage = info.myDisplayMessage = message;
    info.myThrowable = e;
    configureError(info);

    if (info.myShowMessage) {
      showErrorPage(info);
    }
    if (info.myShowLog) {
      LOG.error(LogMessageEx.createEvent(info.myDisplayMessage,
                                         info.myMessage + "\n" + ExceptionUtil.getThrowableText(info.myThrowable),
                                         getErrorAttachments(info)));
    }
  }

  protected Attachment[] getErrorAttachments(ErrorInfo info) {
    return new Attachment[]{AttachmentFactory.createAttachment(myFile)};
  }

  protected abstract void configureError(@NotNull ErrorInfo info);

  protected void showErrorPage(ErrorInfo info) {
    storeState();
    hideProgress();
    myRootComponent = null;

    myErrorMessages.removeAll();

    if (info.myShowStack) {
      ByteArrayOutputStream stream = new ByteArrayOutputStream();
      info.myThrowable.printStackTrace(new PrintStream(stream));
      myErrorStack.setText(stream.toString());
      myErrorStackLayout.show(myErrorStackPanel, ERROR_STACK_CARD);
    }
    else {
      myErrorStack.setText(null);
      myErrorStackLayout.show(myErrorStackPanel, ERROR_NO_STACK_CARD);
    }

    addErrorMessage(new FixableMessageInfo(true, info.myDisplayMessage, "", "", null, null), Messages.getErrorIcon());
    for (FixableMessageInfo message : info.myMessages) {
      addErrorMessage(message, message.myErrorIcon ? Messages.getErrorIcon() : Messages.getWarningIcon());
    }

    myErrorPanel.revalidate();
    myLayout.show(myPanel, ERROR_CARD);

    getDesignerToolWindow().refresh(true);
    repaint();
  }

  protected void addErrorMessage(final FixableMessageInfo message, Icon icon) {
    if (message.myLinkText.length() > 0 || message.myAfterLinkText.length() > 0) {
      HyperlinkLabel warnLabel = new HyperlinkLabel();
      warnLabel.setOpaque(false);
      warnLabel.setHyperlinkText(message.myBeforeLinkText, message.myLinkText, message.myAfterLinkText);
      warnLabel.setIcon(icon);

      if (message.myQuickFix != null) {
        warnLabel.addHyperlinkListener(new HyperlinkListener() {
          public void hyperlinkUpdate(final HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
              message.myQuickFix.run();
            }
          }
        });
      }
      myErrorMessages.add(warnLabel);
    }
    else {
      JBLabel warnLabel = new JBLabel();
      warnLabel.setOpaque(false);
      warnLabel.setText("<html><body>" + message.myBeforeLinkText.replace("\n", "<br>") + "</body></html>");
      warnLabel.setIcon(icon);
      myErrorMessages.add(warnLabel);
    }
    if (message.myAdditionalFixes != null && message.myAdditionalFixes.size() > 0) {
      JPanel fixesPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));
      fixesPanel.setBorder(IdeBorderFactory.createEmptyBorder(3, 0, 10, 0));
      fixesPanel.setOpaque(false);
      fixesPanel.add(Box.createHorizontalStrut(icon.getIconWidth()));

      for (Pair<String, Runnable> pair : message.myAdditionalFixes) {
        HyperlinkLabel fixLabel = new HyperlinkLabel();
        fixLabel.setOpaque(false);
        fixLabel.setHyperlinkText(pair.getFirst());
        final Runnable fix = pair.getSecond();

        fixLabel.addHyperlinkListener(new HyperlinkListener() {
          @Override
          public void hyperlinkUpdate(HyperlinkEvent e) {
            if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
              fix.run();
            }
          }
        });
        fixesPanel.add(fixLabel);
      }
      myErrorMessages.add(fixesPanel);
    }
  }

  protected final void showWarnMessages(@Nullable List<FixableMessageInfo> messages) {
    if (messages == null) {
      myWarnAction.hide();
    }
    else {
      myWarnAction.show(messages);
    }
  }

  private void createProgressPanel() {
    myProgressIcon = new AsyncProcessIcon("Designer progress");
    myProgressMessage = new JLabel();

    JPanel progressBlock = new JPanel();
    progressBlock.add(myProgressIcon);
    progressBlock.add(myProgressMessage);
    progressBlock.setBorder(IdeBorderFactory.createRoundedBorder());

    myProgressPanel = new JPanel(new GridBagLayout());
    myProgressPanel.add(progressBlock,
                        new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0),
                                               0, 0)
    );
    myProgressPanel.setOpaque(false);
  }

  protected final void showProgress(String message) {
    myProgressMessage.setText(message);
    if (myProgressPanel.getParent() == null) {
      myGlassLayer.setEnabled(false);
      myProgressIcon.resume();
      myLayeredPane.add(myProgressPanel, LAYER_PROGRESS);
      myLayeredPane.repaint();
    }
  }

  protected final void hideProgress() {
    myGlassLayer.setEnabled(true);
    myProgressIcon.suspend();
    myLayeredPane.remove(myProgressPanel);
  }

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

  @NotNull
  @Override
  public final Module getModule() {
    if (myModule.isDisposed()) {
      myModule = findModule(myProject, myFile);
      if (myModule == null) {
        throw new IllegalArgumentException("No module for file " + myFile + " in project " + myProject);
      }
    }
    return myModule;
  }

  @Nullable
  protected Module findModule(Project project, VirtualFile file) {
    return ModuleUtilCore.findModuleForFile(file, project);
  }

  public final DesignerEditor getEditor() {
    return myEditor;
  }

  public VirtualFile getFile() {
    return myFile;
  }

  @Override
  public final Project getProject() {
    return myProject;
  }

  public final boolean isProjectClosed() {
    return myProject.isDisposed() || !myProject.isOpen();
  }

  public EditableArea getSurfaceArea() {
    return mySurfaceArea;
  }

  public ToolProvider getToolProvider() {
    return myToolProvider;
  }

  public DesignerActionPanel getActionPanel() {
    return myActionPanel;
  }

  public InplaceEditingLayer getInplaceEditingLayer() {
    return myInplaceEditingLayer;
  }

  public JComponent getPreferredFocusedComponent() {
    return myDesignerCard.isVisible() ? myGlassLayer : myErrorPanel;
  }

  //////////////////////////////////////////////////////////////////////////////////////////
  //
  // State
  //
  //////////////////////////////////////////////////////////////////////////////////////////

  @Nullable
  public List<?> getExpandedComponents() {
    return myExpandedComponents;
  }

  public void setExpandedComponents(@Nullable List<?> expandedComponents) {
    myExpandedComponents = expandedComponents;
  }

  public Property getSelectionProperty(@Nullable String key) {
    return mySelectionPropertyMap.get(key);
  }

  public void setSelectionProperty(@Nullable String key, Property selectionProperty) {
    mySelectionPropertyMap.put(key, selectionProperty);
  }

  protected void storeState() {
    if (myRootComponent != null && myExpandedState == null && mySelectionState == null) {
      myExpandedState = new int[myExpandedComponents == null ? 0 : myExpandedComponents.size()][];
      for (int i = 0; i < myExpandedState.length; i++) {
        IntArrayList path = new IntArrayList();
        componentToPath((RadComponent)myExpandedComponents.get(i), path);
        myExpandedState[i] = path.toArray();
      }

      mySelectionState = getSelectionState();

      myExpandedComponents = null;

      InputTool tool = myToolProvider.getActiveTool();
      if (!(tool instanceof MarqueeTracker) &&
          !(tool instanceof CreationTool) &&
          !(tool instanceof PasteTool)) {
        myToolProvider.loadDefaultTool();
      }
    }
  }

  private void storeSourceSelectionState() {
    if (!CommonEditActionsProvider.isDeleting) {
      mySourceSelectionState.put(getEditorText(), getSelectionState());
    }
  }

  private int[][] getSelectionState() {
    return getSelectionState(mySurfaceArea.getSelection());
  }

  protected static int[][] getSelectionState(List<RadComponent> selection) {
    int[][] selectionState = new int[selection.size()][];

    for (int i = 0; i < selectionState.length; i++) {
      IntArrayList path = new IntArrayList();
      componentToPath(selection.get(i), path);
      selectionState[i] = path.toArray();
    }

    return selectionState;
  }

  private static void componentToPath(RadComponent component, IntArrayList path) {
    RadComponent parent = component.getParent();

    if (parent != null) {
      path.add(0, parent.getChildren().indexOf(component));
      componentToPath(parent, path);
    }
  }

  protected void restoreState() {
    DesignerToolWindowContent toolManager = getDesignerToolWindow();

    if (myExpandedState != null) {
      List<RadComponent> expanded = new ArrayList<RadComponent>();
      for (int[] path : myExpandedState) {
        pathToComponent(expanded, myRootComponent, path, 0);
      }
      myExpandedComponents = expanded;
      toolManager.expandFromState();
      myExpandedState = null;
    }

    List<RadComponent> selection = new ArrayList<RadComponent>();

    int[][] selectionState = mySourceSelectionState.get(getEditorText());
    if (selectionState != null) {
      for (int[] path : selectionState) {
        pathToComponent(selection, myRootComponent, path, 0);
      }
    }

    if (selection.isEmpty()) {
      if (mySelectionState != null) {
        for (int[] path : mySelectionState) {
          pathToComponent(selection, myRootComponent, path, 0);
        }
      }
    }

    if (selection.isEmpty()) {
      toolManager.refresh(true);
    }
    else {
      mySurfaceArea.setSelection(selection);
    }

    mySelectionState = null;
  }

  protected static void pathToComponent(List<RadComponent> components, RadComponent component, int[] path, int index) {
    if (index == path.length) {
      components.add(component);
    }
    else {
      List<RadComponent> children = component.getChildren();
      int componentIndex = path[index];
      if (0 <= componentIndex && componentIndex < children.size()) {
        pathToComponent(components, children.get(componentIndex), path, index + 1);
      }
    }
  }

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

  public abstract String getPlatformTarget();

  protected RadComponent findTarget(int x, int y, @Nullable ComponentTargetFilter filter) {
    if (myRootComponent != null) {
      FindComponentVisitor visitor = new FindComponentVisitor(myLayeredPane, filter, x, y);
      myRootComponent.accept(visitor, false);
      return visitor.getResult();
    }
    return null;
  }

  protected abstract ComponentDecorator getRootSelectionDecorator();

  @Nullable
  protected EditOperation processRootOperation(OperationContext context) {
    return null;
  }

  protected abstract boolean execute(ThrowableRunnable<Exception> operation, boolean updateProperties);

  protected abstract void executeWithReparse(ThrowableRunnable<Exception> operation);

  protected abstract void execute(List<EditOperation> operations);

  public abstract List<PaletteGroup> getPaletteGroups();

  /**
   * Returns a suitable version label from the version attribute from a {@link PaletteItem} version
   */
  @NotNull
  public String getVersionLabel(@Nullable String version) {
    return StringUtil.notNullize(version);
  }

  public boolean isDeprecated(@Nullable String deprecatedIn) {
    return !StringUtil.isEmpty(deprecatedIn);
  }

  protected InputTool createDefaultTool() {
    return new SelectionTool();
  }

  @NotNull
  protected abstract ComponentCreationFactory createCreationFactory(PaletteItem paletteItem);

  @Nullable
  public abstract ComponentPasteFactory createPasteFactory(String xmlComponents);

  public abstract String getEditorText();

  public void activate() {
  }

  public void deactivate() {
  }

  @NotNull
  public DesignerEditorState createState() {
    return new DesignerEditorState(myFile, getZoom());
  }

  public boolean isEditorValid() {
    return myFile.isValid();
  }

  @Override
  public Object getData(@NonNls String dataId) {
    return myActionPanel.getData(dataId);
  }

  public void dispose() {
    Disposer.dispose(myProgressIcon);
    getDesignerWindowManager().dispose(this);
    getPaletteWindowManager().dispose(this);
    Disposer.dispose(myContentSplitter);
  }

  protected AbstractToolWindowManager getDesignerWindowManager() {
    return DesignerToolWindowManager.getInstance(myProject);
  }

  protected AbstractToolWindowManager getPaletteWindowManager() {
    return PaletteToolWindowManager.getInstance(myProject);
  }

  public DesignerToolWindowContent getDesignerToolWindow() {
    return DesignerToolWindowManager.getInstance(this);
  }

  protected PaletteToolWindowContent getPaletteToolWindow() {
    return PaletteToolWindowManager.getInstance(this);
  }

  @Nullable
  public WrapInProvider getWrapInProvider() {
    return null;
  }

  @Nullable
  public RadComponent getRootComponent() {
    return myRootComponent;
  }

  public Object[] getTreeRoots() {
    return myRootComponent == null ? ArrayUtil.EMPTY_OBJECT_ARRAY : new Object[]{myRootComponent};
  }

  public abstract TreeComponentDecorator getTreeDecorator();

  public void handleTreeArea(TreeEditableArea treeArea) {
  }

  @NotNull
  public TablePanelActionPolicy getTablePanelActionPolicy() {
    return TablePanelActionPolicy.ALL;
  }

  @Nullable
  public PropertyTableTab[] getPropertyTableTabs() {
    return null;
  }

  //////////////////////////////////////////////////////////////////////////////////////////
  //
  // Zooming
  //
  //////////////////////////////////////////////////////////////////////////////////////////

  public boolean isZoomSupported() {
    return false;
  }

  public void zoom(@NotNull ZoomType type) {
  }

  public void setZoom(double zoom) {
  }

  public double getZoom() {
    return 1;
  }

  protected void viewZoomed() {
    // Hide quickfix light bulbs; position can be obsolete after the zoom level has changed
    myQuickFixManager.hideHint();
  }

  //////////////////////////////////////////////////////////////////////////////////////////
  //
  // Inspection
  //
  //////////////////////////////////////////////////////////////////////////////////////////

  public void loadInspections(ProgressIndicator progress) {
  }

  public void updateInspections() {
    myQuickFixManager.update();
  }

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

  /**
   * Size of the scene, in scroll pane view port pixels.
   */
  @NotNull
  protected Dimension getSceneSize(Component target) {
    int width = 0;
    int height = 0;

    if (myRootComponent != null) {
      Rectangle bounds = myRootComponent.getBounds(target);
      width = Math.max(width, (int)bounds.getMaxX());
      height = Math.max(height, (int)bounds.getMaxY());

      for (RadComponent component : myRootComponent.getChildren()) {
        Rectangle childBounds = component.getBounds(target);
        width = Math.max(width, (int)childBounds.getMaxX());
        height = Math.max(height, (int)childBounds.getMaxY());
      }
    }

    width += 50;
    height += 40;

    return new Dimension(width, height);
  }

  protected class DesignerEditableArea extends ComponentEditableArea {
    public DesignerEditableArea() {
      super(myLayeredPane);
    }

    @Override
    protected void fireSelectionChanged() {
      super.fireSelectionChanged();
      myLayeredPane.revalidate();
      myLayeredPane.repaint();
    }

    @Override
    public void scrollToSelection() {
      List<RadComponent> selection = getSelection();
      if (selection.size() == 1) {
        Rectangle bounds = selection.get(0).getBounds(myLayeredPane);
        if (bounds != null) {
          myLayeredPane.scrollRectToVisible(bounds);
        }
      }
    }

    @Override
    public RadComponent findTarget(int x, int y, @Nullable ComponentTargetFilter filter) {
      return DesignerEditorPanel.this.findTarget(x, y, filter);
    }

    @Override
    public InputTool findTargetTool(int x, int y) {
      return myDecorationLayer.findTargetTool(x, y);
    }

    @Override
    public void showSelection(boolean value) {
      myDecorationLayer.showSelection(value);
    }

    @Override
    public ComponentDecorator getRootSelectionDecorator() {
      return DesignerEditorPanel.this.getRootSelectionDecorator();
    }

    @Nullable
    public EditOperation processRootOperation(OperationContext context) {
      return DesignerEditorPanel.this.processRootOperation(context);
    }

    @Override
    public FeedbackLayer getFeedbackLayer() {
      return myFeedbackLayer;
    }

    @Override
    public RadComponent getRootComponent() {
      return myRootComponent;
    }

    @Override
    public ActionGroup getPopupActions() {
      return myActionPanel.getPopupActions(this);
    }

    @Override
    public String getPopupPlace() {
      return ActionPlaces.GUI_DESIGNER_EDITOR_POPUP;
    }
  }

  protected class DesignerToolProvider extends ToolProvider {
    @Override
    public void loadDefaultTool() {
      setActiveTool(createDefaultTool());
    }

    @Override
    public void setActiveTool(InputTool tool) {
      if (getActiveTool() instanceof CreationTool && !(tool instanceof CreationTool)) {
        getPaletteToolWindow().clearActiveItem();
      }
      if (!(tool instanceof SelectionTool)) {
        hideInspections();
      }
      super.setActiveTool(tool);
    }

    @Override
    public boolean execute(final ThrowableRunnable<Exception> operation, String command, final boolean updateProperties) {
      myLastExecuteCommand = command;
      final Ref<Boolean> result = Ref.create(Boolean.TRUE);
      CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        public void run() {
          result.set(DesignerEditorPanel.this.execute(operation, updateProperties));
        }
      }, command, null);
      return result.get();
    }

    @Override
    public void executeWithReparse(final ThrowableRunnable<Exception> operation, String command) {
      myLastExecuteCommand = command;
      CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        public void run() {
          DesignerEditorPanel.this.executeWithReparse(operation);
        }
      }, command, null);
    }

    @Override
    public void execute(final List<EditOperation> operations, String command) {
      myLastExecuteCommand = command;
      CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        public void run() {
          DesignerEditorPanel.this.execute(operations);
        }
      }, command, null);
    }

    @Override
    public void startInplaceEditing(@Nullable InplaceContext inplaceContext) {
      myInplaceEditingLayer.startEditing(inplaceContext);
    }

    @Override
    public void hideInspections() {
      myQuickFixManager.hideHint();
    }

    @Override
    public void showError(@NonNls String message, Throwable e) {
      DesignerEditorPanel.this.showError(message, e);
    }

    @Override
    public boolean isZoomSupported() {
      return DesignerEditorPanel.this.isZoomSupported();
    }

    @Override
    public void zoom(@NotNull ZoomType type) {
      DesignerEditorPanel.this.zoom(type);
    }

    @Override
    public void setZoom(double zoom) {
      DesignerEditorPanel.this.setZoom(zoom);
    }

    @Override
    public double getZoom() {
      return DesignerEditorPanel.this.getZoom();
    }
  }

  private final class MyLayeredPane extends JBLayeredPane implements Scrollable {
    public void doLayout() {
      for (int i = getComponentCount() - 1; i >= 0; i--) {
        Component component = getComponent(i);
        component.setBounds(0, 0, getWidth(), getHeight());
      }
    }

    public Dimension getMinimumSize() {
      return getPreferredSize();
    }

    public Dimension getPreferredSize() {
      Rectangle bounds = myScrollPane.getViewport().getBounds();
      Dimension size = getSceneSize(this);

      size.width = Math.max(size.width, bounds.width);
      size.height = Math.max(size.height, bounds.height);

      return size;
    }

    public Dimension getPreferredScrollableViewportSize() {
      return getPreferredSize();
    }

    public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {
      return 10;
    }

    public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
      if (orientation == SwingConstants.HORIZONTAL) {
        return visibleRect.width - 10;
      }
      return visibleRect.height - 10;
    }

    public boolean getScrollableTracksViewportWidth() {
      return false;
    }

    public boolean getScrollableTracksViewportHeight() {
      return false;
    }
  }

  private class FixableMessageAction extends AbstractComboBoxAction<FixableMessageInfo> {
    private final DefaultActionGroup myActionGroup = new DefaultActionGroup();
    private String myTitle;
    private boolean myIsAdded;

    public FixableMessageAction() {
      myActionPanel.getActionGroup().add(myActionGroup);

      Presentation presentation = getTemplatePresentation();
      presentation.setDescription("Warnings");
      presentation.setIcon(AllIcons.Ide.Warning_notifications);
    }

    public void show(List<FixableMessageInfo> messages) {
      if (!myIsAdded) {
        myTitle = Integer.toString(messages.size());
        setItems(messages, null);
        myActionGroup.add(this);
        myActionPanel.update();
        myIsAdded = true;
      }
    }

    public void hide() {
      if (myIsAdded) {
        myActionGroup.remove(this);
        myActionPanel.update();
        myIsAdded = false;
      }
    }

    @NotNull
    @Override
    protected DefaultActionGroup createPopupActionGroup(JComponent button) {
      DefaultActionGroup actionGroup = new DefaultActionGroup();
      for (final FixableMessageInfo message : myItems) {
        AnAction action;
        if ((message.myQuickFix != null && (message.myLinkText.length() > 0 || message.myAfterLinkText.length() > 0)) ||
            (message.myAdditionalFixes != null && message.myAdditionalFixes.size() > 0)) {
          final AnAction[] defaultAction = new AnAction[1];
          DefaultActionGroup popupGroup = new DefaultActionGroup() {
            @Override
            public boolean canBePerformed(DataContext context) {
              return true;
            }

            @Override
            public void actionPerformed(AnActionEvent e) {
              defaultAction[0].actionPerformed(e);
            }
          };
          popupGroup.setPopup(true);
          action = popupGroup;

          if (message.myQuickFix != null && (message.myLinkText.length() > 0 || message.myAfterLinkText.length() > 0)) {
            AnAction popupAction = new AnAction() {
              @Override
              public void actionPerformed(AnActionEvent e) {
                message.myQuickFix.run();
              }
            };
            popupAction.getTemplatePresentation().setText(cleanText(message.myLinkText + message.myAfterLinkText));
            popupGroup.add(popupAction);
            defaultAction[0] = popupAction;
          }
          if (message.myAdditionalFixes != null && message.myAdditionalFixes.size() > 0) {
            for (final Pair<String, Runnable> pair : message.myAdditionalFixes) {
              AnAction popupAction = new AnAction() {
                @Override
                public void actionPerformed(AnActionEvent e) {
                  pair.second.run();
                }
              };
              popupAction.getTemplatePresentation().setText(cleanText(pair.first));
              popupGroup.add(popupAction);
              if (defaultAction[0] == null) {
                defaultAction[0] = popupAction;
              }
            }
          }
        }
        else {
          action = new EmptyAction(true);
        }
        actionGroup.add(action);
        update(message, action.getTemplatePresentation(), true);
      }
      return actionGroup;
    }

    @Override
    protected void update(FixableMessageInfo item, Presentation presentation, boolean popup) {
      if (popup) {
        presentation.setText(cleanText(item.myBeforeLinkText));
      }
      else {
        presentation.setText(myTitle);
      }
    }

    private String cleanText(String text) {
      if (text != null) {
        text = text.trim();
        text = StringUtil.replace(text, "&nbsp;", " ");
        text = StringUtil.replace(text, "\n", " ");

        StringBuilder builder = new StringBuilder();
        int length = text.length();
        boolean whitespace = false;

        for (int i = 0; i < length; i++) {
          char ch = text.charAt(i);
          if (ch == ' ') {
            if (!whitespace) {
              whitespace = true;
              builder.append(ch);
            }
          }
          else {
            whitespace = false;
            builder.append(ch);
          }
        }

        text = builder.toString();
      }
      return text;
    }

    @Override
    protected boolean selectionChanged(FixableMessageInfo item) {
      return false;
    }
  }

  public static final class ErrorInfo {
    public String myMessage;
    public String myDisplayMessage;

    public final List<FixableMessageInfo> myMessages = new ArrayList<FixableMessageInfo>();

    public Throwable myThrowable;

    public boolean myShowMessage = true;
    public boolean myShowStack = true;
    public boolean myShowLog;
  }

  public static final class FixableMessageInfo {
    public final boolean myErrorIcon;
    public final String myBeforeLinkText;
    public final String myLinkText;
    public final String myAfterLinkText;
    public final Runnable myQuickFix;
    public final List<Pair<String, Runnable>> myAdditionalFixes;

    public FixableMessageInfo(boolean errorIcon,
                              String beforeLinkText,
                              String linkText,
                              String afterLinkText,
                              Runnable quickFix,
                              List<Pair<String, Runnable>> additionalFixes) {
      myErrorIcon = errorIcon;
      myBeforeLinkText = beforeLinkText;
      myLinkText = linkText;
      myAfterLinkText = afterLinkText;
      myQuickFix = quickFix;
      myAdditionalFixes = additionalFixes;
    }
  }

  private static class FixedHashMap<K, V> extends HashMap<K, V> {
    private final int mySize;
    private final List<K> myKeys = new LinkedList<K>();

    public FixedHashMap(int size) {
      mySize = size;
    }

    @Override
    public V put(K key, V value) {
      if (!myKeys.contains(key)) {
        if (myKeys.size() >= mySize) {
          remove(myKeys.remove(0));
        }
        myKeys.add(key);
      }
      return super.put(key, value);
    }

    @Override
    public V get(Object key) {
      if (myKeys.contains(key)) {
        int index = myKeys.indexOf(key);
        int last = myKeys.size() - 1;
        myKeys.set(index, myKeys.get(last));
        myKeys.set(last, (K)key);
      }
      return super.get(key);
    }
  }
}