summaryrefslogtreecommitdiff
path: root/plugins/ui-designer/src/com/intellij/uiDesigner/designSurface/GuiEditor.java
blob: dbbc27655f4e6c9a469c31227633e09e85478b93 (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
/*
 * Copyright 2000-2009 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.uiDesigner.designSurface;

import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.ide.DeleteProvider;
import com.intellij.ide.palette.PaletteDragEventListener;
import com.intellij.ide.palette.impl.PaletteManager;
import com.intellij.lang.properties.psi.PropertiesFile;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.event.DocumentAdapter;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.ui.JBColor;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.ui.components.JBLayeredPane;
import com.intellij.uiDesigner.*;
import com.intellij.uiDesigner.compiler.Utils;
import com.intellij.uiDesigner.componentTree.ComponentPtr;
import com.intellij.uiDesigner.componentTree.ComponentSelectionListener;
import com.intellij.uiDesigner.componentTree.ComponentTree;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.intellij.uiDesigner.core.Util;
import com.intellij.uiDesigner.lw.CompiledClassPropertiesProvider;
import com.intellij.uiDesigner.lw.IComponent;
import com.intellij.uiDesigner.lw.IProperty;
import com.intellij.uiDesigner.lw.LwRootContainer;
import com.intellij.uiDesigner.palette.ComponentItem;
import com.intellij.uiDesigner.propertyInspector.PropertyInspector;
import com.intellij.uiDesigner.propertyInspector.UIDesignerToolWindowManager;
import com.intellij.uiDesigner.propertyInspector.properties.IntroStringProperty;
import com.intellij.uiDesigner.radComponents.RadComponent;
import com.intellij.uiDesigner.radComponents.RadContainer;
import com.intellij.uiDesigner.radComponents.RadRootContainer;
import com.intellij.uiDesigner.radComponents.RadTabbedPane;
import com.intellij.util.Alarm;
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.EventListenerList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.event.*;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

/**
 * <code>GuiEditor</code> is a panel with border layout. It has palette at the north,
 * tree of component with property editor at the west and editor area at the center.
 * This editor area contains internal component where user edit the UI.
 *
 * @author Anton Katilin
 * @author Vladimir Kondratyev
 */
public final class GuiEditor extends JPanel implements DataProvider, ModuleProvider {
  private static final Logger LOG = Logger.getInstance("#com.intellij.uiDesigner.GuiEditor");

  private final Project myProject;
  private Module myModule;
  @NotNull private final VirtualFile myFile;

  /**
   * for debug purposes
   */
  private Exception myWhere;

  /**
   * All component are on this layer
   */
  private static final Integer LAYER_COMPONENT = JLayeredPane.DEFAULT_LAYER;
  /**
   * This layer contains all "passive" decorators such as component boundaries
   * and selection rectangle.
   */
  private static final Integer LAYER_PASSIVE_DECORATION = JLayeredPane.POPUP_LAYER;
  /**
   * We show (and move) dragged component at this layer
   */
  private static final Integer LAYER_DND = JLayeredPane.DRAG_LAYER;
  /**
   * This is the topmost layer. It gets and redispatch all incoming events
   */
  private static final Integer LAYER_GLASS = new Integer(JLayeredPane.DRAG_LAYER.intValue() + 100);
  /**
   * This layer contains all "active" decorators. This layer should be over
   * LAYER_GLASS because active decorators must get AWT events to work correctly.
   */
  private static final Integer LAYER_ACTIVE_DECORATION = new Integer(LAYER_GLASS.intValue() + 100);
  /**
   * This layer contains all inplace editors.
   */
  private static final Integer LAYER_INPLACE_EDITING = new Integer(LAYER_ACTIVE_DECORATION.intValue() + 100);

  private final EventListenerList myListenerList;
  /**
   * we have to store document here but not file because there can be a situation when
   * document we added listener to has been disposed, and remove listener will be applied to
   * a new document (got by file) -> assertion (see SCR 14143)
   */
  private final Document myDocument;

  final MainProcessor myProcessor;
  @NotNull private final JScrollPane myScrollPane;
  /**
   * This layered pane contains all layers to lay components out and to
   * show all necessary decoration items
   */
  @NotNull private final MyLayeredPane myLayeredPane;
  /**
   * The component which represents decoration layer. All passive
   * decorators are on this layer.
   */
  private final PassiveDecorationLayer myDecorationLayer;
  /**
   * The component which represents layer where located all dragged
   * components
   */
  private final DragLayer myDragLayer;
  /**
   * This layer contains all inplace editors
   */
  private final InplaceEditingLayer myInplaceEditingLayer;
  /**
   * Brings functionality to "DEL" button
   */
  private final MyDeleteProvider myDeleteProvider;
  /**
   * Rerun error analizer
   */
  private final MyPsiTreeChangeListener myPsiTreeChangeListener;

  private RadRootContainer myRootContainer;
  /**
   * Panel with components palette.
   */
  //@NotNull private final PalettePanel myPalettePanel;
  /**
   * GuiEditor should not react on own events. If <code>myInsideChange</code>
   * is <code>true</code> then we do not react on incoming DocumentEvent.
   */
  private boolean myInsideChange;
  private final DocumentAdapter myDocumentListener;
  private final CardLayout myCardLayout;

  @NonNls private final static String CARD_VALID = "valid";
  @NonNls private final static String CARD_INVALID = "invalid";
  private final JPanel myValidCard;
  private final JPanel myInvalidCard;
  private boolean myInvalid = false;

  private final CutCopyPasteSupport myCutCopyPasteSupport;
  /**
   * Implementation of Crtl+W and Ctrl+Shift+W behavior
   */
  private final SelectionState mySelectionState;
  @NotNull private final GlassLayer myGlassLayer;
  private final ActiveDecorationLayer myActiveDecorationLayer;

  private boolean myShowGrid = true;
  private boolean myShowComponentTags = true;
  private final DesignDropTargetListener myDropTargetListener;
  private JLabel myFormInvalidLabel;
  private final QuickFixManagerImpl myQuickFixManager;
  private final GridCaptionPanel myHorzCaptionPanel;
  private final GridCaptionPanel myVertCaptionPanel;
  private final MyPaletteKeyListener myPaletteKeyListener;
  private final MyPaletteDragListener myPaletteDragListener;
  private final MyPaletteSelectionListener myPaletteSelectionListener;
  private ComponentPtr mySelectionAnchor;
  private ComponentPtr mySelectionLead;
  /**
   * Undo group ID for undoing actions that need to be undone together with the form modification.
   */
  private Object myNextSaveGroupId = new Object();

  @NonNls private static final String ourHelpID = "guiDesigner.uiTour.workspace";

  public static final DataKey<GuiEditor> DATA_KEY = DataKey.create(GuiEditor.class.getName());

  /**
   * @param file file to be edited
   * @throws java.lang.IllegalArgumentException
   *          if the <code>file</code>
   *          is <code>null</code> or <code>file</code> is not valid PsiFile
   */
  public GuiEditor(Project project, @NotNull final Module module, @NotNull final VirtualFile file) {
    LOG.assertTrue(file.isValid());

    myProject = project;
    myModule = module;
    myFile = file;

    myCutCopyPasteSupport = new CutCopyPasteSupport(this);

    myCardLayout = new CardLayout();
    setLayout(myCardLayout);

    myValidCard = new JPanel(new BorderLayout());
    myInvalidCard = createInvalidCard();
    add(myValidCard, CARD_VALID);
    add(myInvalidCard, CARD_INVALID);

    myListenerList = new EventListenerList();

    myDecorationLayer = new PassiveDecorationLayer(this);
    myDragLayer = new DragLayer(this);

    myLayeredPane = new MyLayeredPane();
    myInplaceEditingLayer = new InplaceEditingLayer(this);
    myLayeredPane.add(myInplaceEditingLayer, LAYER_INPLACE_EDITING);
    myActiveDecorationLayer = new ActiveDecorationLayer(this);
    myLayeredPane.add(myActiveDecorationLayer, LAYER_ACTIVE_DECORATION);
    myGlassLayer = new GlassLayer(this);
    myLayeredPane.add(myGlassLayer, LAYER_GLASS);
    myLayeredPane.add(myDecorationLayer, LAYER_PASSIVE_DECORATION);
    myLayeredPane.add(myDragLayer, LAYER_DND);

    myGlassLayer.addFocusListener(new FocusListener() {
      public void focusGained(FocusEvent e) {
        myDecorationLayer.repaint();
        //fireSelectedComponentChanged(); // EA-36478
      }

      public void focusLost(FocusEvent e) {
        myDecorationLayer.repaint();
      }
    });

    // Ctrl+W / Ctrl+Shift+W support
    mySelectionState = new SelectionState(this);

    // DeleteProvider
    myDeleteProvider = new MyDeleteProvider();

    // We need to synchronize GUI editor with the document
    final Alarm alarm = new Alarm();
    myDocumentListener = new DocumentAdapter() {
      public void documentChanged(final DocumentEvent e) {
        if (!myInsideChange) {
          UndoManager undoManager = UndoManager.getInstance(getProject());
          alarm.cancelAllRequests();
          alarm.addRequest(new MySynchronizeRequest(undoManager.isUndoInProgress() || undoManager.isRedoInProgress()),
                           100/*any arbitrary delay*/, ModalityState.stateForComponent(GuiEditor.this));
        }
      }
    };

    // Prepare document
    myDocument = FileDocumentManager.getInstance().getDocument(file);
    myDocument.addDocumentListener(myDocumentListener);

    // Read form from file
    readFromFile(false);

    JPanel panel = new JPanel(new GridBagLayout());
    panel.setBackground(Color.LIGHT_GRAY);

    myHorzCaptionPanel = new GridCaptionPanel(this, false);
    myVertCaptionPanel = new GridCaptionPanel(this, true);

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.weightx = 0.0;
    gbc.weighty = 0.0;
    gbc.fill = GridBagConstraints.BOTH;
    panel.add(myVertCaptionPanel, gbc);

    gbc.gridx = 1;
    gbc.gridy = 0;
    panel.add(myHorzCaptionPanel, gbc);

    gbc.gridx = 1;
    gbc.gridy = 1;
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;

    myScrollPane = ScrollPaneFactory.createScrollPane(myLayeredPane);
    myScrollPane.setBackground(new JBColor(Color.WHITE, UIUtil.getListBackground()));
    panel.add(myScrollPane, gbc);
    myHorzCaptionPanel.attachToScrollPane(myScrollPane);
    myVertCaptionPanel.attachToScrollPane(myScrollPane);

    myValidCard.add(panel, BorderLayout.CENTER);

    final CancelCurrentOperationAction cancelCurrentOperationAction = new CancelCurrentOperationAction();
    cancelCurrentOperationAction.registerCustomShortcutSet(CommonShortcuts.ESCAPE, this);

    myProcessor = new MainProcessor(this);

    // PSI listener to restart error highlighter
    myPsiTreeChangeListener = new MyPsiTreeChangeListener();
    PsiManager.getInstance(getProject()).addPsiTreeChangeListener(myPsiTreeChangeListener);

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

    myDropTargetListener = new DesignDropTargetListener(this);
    if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
      new DropTarget(getGlassLayer(), DnDConstants.ACTION_COPY_OR_MOVE, myDropTargetListener);
    }

    myActiveDecorationLayer.installSelectionWatcher();

    final PaletteManager paletteManager = PaletteManager.getInstance(getProject());
    myPaletteKeyListener = new MyPaletteKeyListener();
    paletteManager.addKeyListener(myPaletteKeyListener);
    myPaletteDragListener = new MyPaletteDragListener();
    paletteManager.addDragEventListener(myPaletteDragListener);
    myPaletteSelectionListener = new MyPaletteSelectionListener();
    paletteManager.addSelectionListener(myPaletteSelectionListener);

    ActionManager.getInstance().getAction("GuiDesigner.IncreaseIndent").registerCustomShortcutSet(
      new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0)), myGlassLayer);
    ActionManager.getInstance().getAction("GuiDesigner.DecreaseIndent").registerCustomShortcutSet(
      new CustomShortcutSet(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_MASK)), myGlassLayer);
  }

  @NotNull
  public SelectionState getSelectionState() {
    return mySelectionState;
  }

  public void dispose() {
    ApplicationManager.getApplication().assertIsDispatchThread();

    if (myWhere != null) {
      LOG.error("Already disposed: old trace: ", myWhere);
      LOG.error("Already disposed: new trace: ");
    }
    else {
      myWhere = new Exception();
    }

    final PaletteManager paletteManager = PaletteManager.getInstance(getProject());
    paletteManager.removeKeyListener(myPaletteKeyListener);
    paletteManager.removeDragEventListener(myPaletteDragListener);
    paletteManager.removeSelectionListener(myPaletteSelectionListener);
    myDocument.removeDocumentListener(myDocumentListener);
    PsiManager.getInstance(getProject()).removePsiTreeChangeListener(myPsiTreeChangeListener);
    myPsiTreeChangeListener.dispose();
  }

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

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

  @NotNull
  public VirtualFile getFile() {
    return myFile;
  }

  public PsiFile getPsiFile() {
    return PsiManager.getInstance(getProject()).findFile(myFile);
  }

  public boolean isEditable() {
    final Document document = FileDocumentManager.getInstance().getDocument(myFile);
    return document != null && document.isWritable();
  }

  public boolean ensureEditable() {
    if (isEditable()) {
      return true;
    }
    VirtualFile sourceFileToCheckOut = null;
    if (!GuiDesignerConfiguration.getInstance(getProject()).INSTRUMENT_CLASSES) {
      final String classToBind = myRootContainer.getClassToBind();
      if (classToBind != null && classToBind.length() > 0) {
        PsiClass psiClass = FormEditingUtil.findClassToBind(getModule(), classToBind);
        if (psiClass != null) {
          sourceFileToCheckOut = psiClass.getContainingFile().getVirtualFile();
        }
      }
    }

    final ReadonlyStatusHandler.OperationStatus status;
    if (sourceFileToCheckOut != null) {
      status = ReadonlyStatusHandler.getInstance(getProject()).ensureFilesWritable(myFile, sourceFileToCheckOut);
    }
    else {
      status = ReadonlyStatusHandler.getInstance(getProject()).ensureFilesWritable(myFile);
    }
    return !status.hasReadonlyFiles();
  }

  public void refresh() {
    refreshImpl(myRootContainer);
    myRootContainer.getDelegee().revalidate();
    repaintLayeredPane();
  }

  public void refreshAndSave(final boolean forceSync) {
    // Update property inspector
    final UIDesignerToolWindowManager manager = UIDesignerToolWindowManager.getInstance(getProject());
    final PropertyInspector propertyInspector = manager.getPropertyInspector();
    if (propertyInspector != null) {
      propertyInspector.synchWithTree(forceSync);
    }

    refresh();
    saveToFile();
    // TODO[yole]: install appropriate listeners so that the captions repaint themselves at correct time
    myHorzCaptionPanel.repaint();
    myVertCaptionPanel.repaint();
  }

  public Object getNextSaveGroupId() {
    return myNextSaveGroupId;
  }

  private static void refreshImpl(final RadComponent component) {
    if (component.getParent() != null) {
      final Dimension size = component.getSize();
      final int oldWidth = size.width;
      final int oldHeight = size.height;
      Util.adjustSize(component.getDelegee(), component.getConstraints(), size);

      if (oldWidth != size.width || oldHeight != size.height) {
        if (component.getParent().isXY()) {
          component.setSize(size);
        }
        component.getDelegee().invalidate();
      }
    }

    if (component instanceof RadContainer) {
      component.refresh();

      final RadContainer container = (RadContainer)component;
      for (int i = container.getComponentCount() - 1; i >= 0; i--) {
        refreshImpl(container.getComponent(i));
      }
    }
  }

  public Object getData(final String dataId) {
    if (PlatformDataKeys.HELP_ID.is(dataId)) {
      return ourHelpID;
    }

    // Standard Swing cut/copy/paste actions should work if user is editing something inside property inspector
    Project project = getProject();
    if (project.isDisposed()) return null;
    final UIDesignerToolWindowManager manager = UIDesignerToolWindowManager.getInstance(project);
    final PropertyInspector inspector = manager.getPropertyInspector();
    if (inspector != null && inspector.isEditing()) {
      return null;
    }

    if (PlatformDataKeys.DELETE_ELEMENT_PROVIDER.is(dataId)) {
      return myDeleteProvider;
    }

    if (PlatformDataKeys.COPY_PROVIDER.is(dataId) ||
        PlatformDataKeys.CUT_PROVIDER.is(dataId) ||
        PlatformDataKeys.PASTE_PROVIDER.is(dataId)) {
      return myCutCopyPasteSupport;
    }

    return null;
  }

  private JPanel createInvalidCard() {
    final JPanel panel = new JPanel(new GridBagLayout());
    myFormInvalidLabel = new JLabel(UIDesignerBundle.message("error.form.file.is.invalid"));
    panel.add(myFormInvalidLabel,
              new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
    return panel;
  }

  /**
   * @return the component which represents DnD layer. All currently
   *         dragged (moved) component are on this layer.
   */
  public DragLayer getDragLayer() {
    return myDragLayer;
  }

  /**
   * @return the topmost <code>UiConainer</code> which in the root of
   *         component hierarchy. This method never returns <code>null</code>.
   */
  @NotNull
  public RadRootContainer getRootContainer() {
    return myRootContainer;
  }

  /**
   * Fires event that selection changes
   */
  public void fireSelectedComponentChanged() {
    final ComponentSelectionListener[] listeners = myListenerList.getListeners(ComponentSelectionListener.class);
    for (ComponentSelectionListener listener : listeners) {
      listener.selectedComponentChanged(this);
    }
  }

  private void fireHierarchyChanged() {
    final HierarchyChangeListener[] listeners = myListenerList.getListeners(HierarchyChangeListener.class);
    for (final HierarchyChangeListener listener : listeners) {
      listener.hierarchyChanged();
    }
  }

  @NotNull
  public GlassLayer getGlassLayer() {
    return myGlassLayer;
  }

  /**
   * @return the component which represents layer with active decorators
   *         such as grid edit controls, inplace editors, etc.
   */
  public InplaceEditingLayer getInplaceEditingLayer() {
    return myInplaceEditingLayer;
  }

  @NotNull
  public JLayeredPane getLayeredPane() {
    return myLayeredPane;
  }

  public void repaintLayeredPane() {
    myLayeredPane.repaint();
  }

  /**
   * Adds specified selection listener. This listener gets notification each time
   * the selection in the component the changes.
   */
  public void addComponentSelectionListener(final ComponentSelectionListener l) {
    myListenerList.add(ComponentSelectionListener.class, l);
  }

  /**
   * Removes specified selection listener
   */
  public void removeComponentSelectionListener(final ComponentSelectionListener l) {
    myListenerList.remove(ComponentSelectionListener.class, l);
  }

  /**
   * Adds specified hierarchy change listener
   */
  public void addHierarchyChangeListener(@NotNull final HierarchyChangeListener l) {
    myListenerList.add(HierarchyChangeListener.class, l);
  }

  /**
   * Removes specified hierarchy change listener
   */
  public void removeHierarchyChangeListener(@NotNull final HierarchyChangeListener l) {
    myListenerList.remove(HierarchyChangeListener.class, l);
  }

  private void saveToFile() {
    LOG.debug("GuiEditor.saveToFile(): group ID=" + myNextSaveGroupId);
    CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
      public void run() {
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
          public void run() {
            myInsideChange = true;
            try {
              final XmlWriter writer = new XmlWriter();
              getRootContainer().write(writer);
              final String newText = writer.getText();
              final String oldText = myDocument.getText();

              try {
                final ReplaceInfo replaceInfo = findFragmentToChange(oldText, newText);
                if (replaceInfo.getStartOffset() == -1) {
                  // do nothing - texts are equal
                }
                else {
                  myDocument.replaceString(replaceInfo.getStartOffset(), replaceInfo.getEndOffset(), replaceInfo.getReplacement());
                }
              }
              catch (Exception e) {
                LOG.error(e);
                myDocument.replaceString(0, oldText.length(), newText);
              }
            }
            finally {
              myInsideChange = false;
            }
          }
        });
      }
    }, "UI Designer Save", myNextSaveGroupId);
    myNextSaveGroupId = new Object();

    fireHierarchyChanged();
  }

  public ActiveDecorationLayer getActiveDecorationLayer() {
    return myActiveDecorationLayer;
  }

  public void setStringDescriptorLocale(final Locale locale) {
    myRootContainer.setStringDescriptorLocale(locale);
    refreshProperties();
    UIDesignerToolWindowManager.getInstance(getProject()).updateComponentTree();
    DaemonCodeAnalyzer.getInstance(getProject()).restart();
  }

  @Nullable
  public Locale getStringDescriptorLocale() {
    return myRootContainer.getStringDescriptorLocale();
  }

  private void refreshProperties() {
    final Ref<Boolean> anythingModified = new Ref<Boolean>();
    FormEditingUtil.iterate(myRootContainer, new FormEditingUtil.ComponentVisitor() {
      public boolean visit(final IComponent component) {
        final RadComponent radComponent = (RadComponent)component;
        boolean componentModified = false;
        for (IProperty prop : component.getModifiedProperties()) {
          if (prop instanceof IntroStringProperty) {
            IntroStringProperty strProp = (IntroStringProperty)prop;
            componentModified = strProp.refreshValue(radComponent) || componentModified;
          }
        }

        if (component instanceof RadContainer) {
          componentModified = ((RadContainer)component).updateBorder() || componentModified;
        }

        if (component.getParentContainer() instanceof RadTabbedPane) {
          componentModified = ((RadTabbedPane)component.getParentContainer()).refreshChildTitle(radComponent) || componentModified;
        }
        if (componentModified) {
          anythingModified.set(Boolean.TRUE);
        }

        return true;
      }
    });
    if (!anythingModified.isNull()) {
      refresh();
      final UIDesignerToolWindowManager twm = UIDesignerToolWindowManager.getInstance(getProject());
      ComponentTree tree = twm.getComponentTree();
      if (tree != null) tree.repaint();
      PropertyInspector inspector = twm.getPropertyInspector();
      if (inspector != null) inspector.synchWithTree(true);
    }
  }

  public MainProcessor getMainProcessor() {
    return myProcessor;
  }

  public void refreshIntentionHint() {
    myQuickFixManager.refreshIntentionHint();
  }

  public void setSelectionAnchor(final RadComponent component) {
    mySelectionAnchor = new ComponentPtr(this, component);
  }

  @Nullable
  public RadComponent getSelectionAnchor() {
    if (mySelectionAnchor == null) return null;
    mySelectionAnchor.validate();
    return mySelectionAnchor.getComponent();
  }

  public void setSelectionLead(final RadComponent component) {
    mySelectionLead = new ComponentPtr(this, component);
  }

  @Nullable
  public RadComponent getSelectionLead() {
    if (mySelectionLead == null) return null;
    mySelectionLead.validate();
    return mySelectionLead.getComponent();
  }

  public void scrollComponentInView(final RadComponent component) {
    Rectangle rect = SwingUtilities.convertRectangle(component.getDelegee().getParent(), component.getBounds(), myLayeredPane);
    myLayeredPane.scrollRectToVisible(rect);
  }

  public static final class ReplaceInfo {
    private final int myStartOffset;
    private final int myEndOffset;
    private final String myReplacement;

    public ReplaceInfo(final int startOffset, final int endOffset, final String replacement) {
      myStartOffset = startOffset;
      myEndOffset = endOffset;
      myReplacement = replacement;
    }

    public int getStartOffset() {
      return myStartOffset;
    }

    public int getEndOffset() {
      return myEndOffset;
    }

    public String getReplacement() {
      return myReplacement;
    }
  }

  public static ReplaceInfo findFragmentToChange(final String oldText, final String newText) {
    if (oldText.equals(newText)) {
      return new ReplaceInfo(-1, -1, null);
    }

    final int oldLength = oldText.length();
    final int newLength = newText.length();

    int startOffset = 0;
    while (
      startOffset < oldLength && startOffset < newLength &&
      oldText.charAt(startOffset) == newText.charAt(startOffset)
      ) {
      startOffset++;
    }

    int endOffset = oldLength;
    while (true) {
      if (endOffset <= startOffset) {
        break;
      }
      final int idxInNew = newLength - (oldLength - endOffset) - 1;
      if (idxInNew < startOffset) {
        break;
      }

      final char c1 = oldText.charAt(endOffset - 1);
      final char c2 = newText.charAt(idxInNew);
      if (c1 != c2) {
        break;
      }
      endOffset--;
    }

    return new ReplaceInfo(startOffset, endOffset, newText.substring(startOffset, newLength - (oldLength - endOffset)));
  }

  /**
   * @param rootContainer new container to be set as a root.
   */
  private void setRootContainer(@NotNull final RadRootContainer rootContainer) {
    if (myRootContainer != null) {
      myLayeredPane.remove(myRootContainer.getDelegee());
    }
    myRootContainer = rootContainer;
    setDesignTimeInsets(2);
    myLayeredPane.add(myRootContainer.getDelegee(), LAYER_COMPONENT);

    fireHierarchyChanged();
  }

  public void setDesignTimeInsets(final int insets) {
    Integer oldInsets = (Integer)myRootContainer.getDelegee().getClientProperty(GridLayoutManager.DESIGN_TIME_INSETS);
    if (oldInsets == null || oldInsets.intValue() != insets) {
      myRootContainer.getDelegee().putClientProperty(GridLayoutManager.DESIGN_TIME_INSETS, insets);
      revalidateRecursive(myRootContainer.getDelegee());
    }
  }

  private static void revalidateRecursive(final JComponent component) {
    for (Component child : component.getComponents()) {
      if (child instanceof JComponent) {
        revalidateRecursive((JComponent)child);
      }
    }
    component.revalidate();
    component.repaint();
  }

  /**
   * Creates and sets new <code>RadRootContainer</code>
   *
   * @param keepSelection if true, the GUI designer tries to preserve the selection state after reload.
   */
  public void readFromFile(final boolean keepSelection) {
    try {
      ComponentPtr[] selection = null;
      Map<String, String> tabbedPaneSelectedTabs = null;
      if (keepSelection) {
        selection = SelectionState.getSelection(this);
        tabbedPaneSelectedTabs = saveTabbedPaneSelectedTabs();
      }
      Locale oldLocale = null;
      if (myRootContainer != null) {
        oldLocale = myRootContainer.getStringDescriptorLocale();
      }

      final String text = myDocument.getText();

      final ClassLoader classLoader = LoaderFactory.getInstance(getProject()).getLoader(myFile);

      final LwRootContainer rootContainer = Utils.getRootContainer(text, new CompiledClassPropertiesProvider(classLoader));
      final RadRootContainer container = XmlReader.createRoot(this, rootContainer, classLoader, oldLocale);
      setRootContainer(container);
      if (keepSelection) {
        SelectionState.restoreSelection(this, selection);
        restoreTabbedPaneSelectedTabs(tabbedPaneSelectedTabs);
      }
      myInvalid = false;
      myCardLayout.show(this, CARD_VALID);
      refresh();
    }
    catch (Exception exc) {
      Throwable original = exc;
      while (original instanceof InvocationTargetException) {
        original = original.getCause();
      }
      showInvalidCard(original);
    }
    catch (final LinkageError exc) {
      showInvalidCard(exc);
    }
  }

  private void showInvalidCard(final Throwable exc) {
    LOG.info(exc);
    // setting fictive container
    setRootContainer(new RadRootContainer(this, "0"));
    myFormInvalidLabel.setText(UIDesignerBundle.message("error.form.file.is.invalid.message", FormEditingUtil.getExceptionMessage(exc)));
    myInvalid = true;
    myCardLayout.show(this, CARD_INVALID);
    repaint();
  }

  public boolean isFormInvalid() {
    return myInvalid;
  }

  private Map<String, String> saveTabbedPaneSelectedTabs() {
    final Map<String, String> result = new HashMap<String, String>();
    FormEditingUtil.iterate(getRootContainer(), new FormEditingUtil.ComponentVisitor() {
      public boolean visit(final IComponent component) {
        if (component instanceof RadTabbedPane) {
          RadTabbedPane tabbedPane = (RadTabbedPane)component;
          RadComponent c = tabbedPane.getSelectedTab();
          if (c != null) {
            result.put(tabbedPane.getId(), c.getId());
          }
        }
        return true;
      }
    });
    return result;
  }

  private void restoreTabbedPaneSelectedTabs(final Map<String, String> tabbedPaneSelectedTabs) {
    FormEditingUtil.iterate(getRootContainer(), new FormEditingUtil.ComponentVisitor() {
      public boolean visit(final IComponent component) {
        if (component instanceof RadTabbedPane) {
          RadTabbedPane tabbedPane = (RadTabbedPane)component;
          String selectedTabId = tabbedPaneSelectedTabs.get(tabbedPane.getId());
          if (selectedTabId != null) {
            for (RadComponent c : tabbedPane.getComponents()) {
              if (c.getId().equals(selectedTabId)) {
                tabbedPane.selectTab(c);
                break;
              }
            }
          }
        }
        return true;
      }
    });
  }

  public JComponent getPreferredFocusedComponent() {
    if (myValidCard.isVisible()) {
      return myGlassLayer;
    }
    else {
      return myInvalidCard;
    }
  }

  public static void repaintLayeredPane(final RadComponent component) {
    final GuiEditor uiEditor = (GuiEditor)SwingUtilities.getAncestorOfClass(GuiEditor.class, component.getDelegee());
    if (uiEditor != null) {
      uiEditor.repaintLayeredPane();
    }
  }

  public boolean isShowGrid() {
    return myShowGrid;
  }

  public void setShowGrid(final boolean showGrid) {
    if (myShowGrid != showGrid) {
      myShowGrid = showGrid;
      repaint();
    }
  }

  public boolean isShowComponentTags() {
    return myShowComponentTags;
  }

  public void setShowComponentTags(final boolean showComponentTags) {
    if (myShowComponentTags != showComponentTags) {
      myShowComponentTags = showComponentTags;
      repaint();
    }
  }

  public DesignDropTargetListener getDropTargetListener() {
    return myDropTargetListener;
  }

  @Nullable
  public GridCaptionPanel getFocusedCaptionPanel() {
    if (myHorzCaptionPanel.isFocusOwner()) {
      return myHorzCaptionPanel;
    }
    else if (myVertCaptionPanel.isFocusOwner()) {
      return myVertCaptionPanel;
    }
    return null;
  }

  public boolean isUndoRedoInProgress() {
    UndoManager undoManager = UndoManager.getInstance(getProject());
    return undoManager.isUndoInProgress() || undoManager.isRedoInProgress();
  }

  private boolean isActiveEditor() {
    return UIDesignerToolWindowManager.getInstance(getProject()).getActiveFormEditor() == this;
  }

  void hideIntentionHint() {
    myQuickFixManager.hideIntentionHint();
  }

  private final class MyLayeredPane extends JBLayeredPane implements Scrollable {
    /**
     * All components allocate whole pane's area.
     */
    public void doLayout() {
      for (int i = getComponentCount() - 1; i >= 0; i--) {
        final Component component = getComponent(i);
        component.setBounds(0, 0, getWidth(), getHeight());
      }
    }

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

    public Dimension getPreferredSize() {
      // make sure all components fit
      int width = 0;
      int height = 0;
      for (int i = 0; i < myRootContainer.getComponentCount(); i++) {
        final RadComponent component = myRootContainer.getComponent(i);
        width = Math.max(width, component.getX() + component.getWidth());
        height = Math.max(height, component.getY() + component.getHeight());
      }

      width += 50;
      height += 40;

      Rectangle bounds = myScrollPane.getViewport().getBounds();

      return new Dimension(Math.max(width, bounds.width), Math.max(height, bounds.height));
    }

    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;
    }
  }

  /**
   * Action works only if we are not editing something in the property inspector
   */
  private final class CancelCurrentOperationAction extends AnAction {
    public void actionPerformed(final AnActionEvent e) {
      myProcessor.cancelOperation();
      myQuickFixManager.hideIntentionHint();
    }

    public void update(final AnActionEvent e) {
      final UIDesignerToolWindowManager manager = UIDesignerToolWindowManager.getInstance(getProject());
      PropertyInspector inspector = manager.getPropertyInspector();
      e.getPresentation().setEnabled(inspector != null && !inspector.isEditing());
    }
  }

  /**
   * Allows "DEL" button to work through the standard mechanism
   */
  private final class MyDeleteProvider implements DeleteProvider {
    public void deleteElement(@NotNull final DataContext dataContext) {
      if (!GuiEditor.this.ensureEditable()) {
        return;
      }
      CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
        public void run() {
          FormEditingUtil.deleteSelection(GuiEditor.this);
        }
      }, UIDesignerBundle.message("command.delete.selection"), null);
    }

    public boolean canDeleteElement(@NotNull final DataContext dataContext) {
      final UIDesignerToolWindowManager manager = UIDesignerToolWindowManager.getInstance(getProject());
      return
        !manager.getPropertyInspector().isEditing() &&
        !myInplaceEditingLayer.isEditing() &&
        FormEditingUtil.canDeleteSelection(GuiEditor.this);
    }
  }

  /**
   * Listens PSI event and update error highlighting in the UI editor
   */
  private final class MyPsiTreeChangeListener extends PsiTreeChangeAdapter {
    private final Alarm myAlarm;
    private final MyRefreshPropertiesRequest myRefreshPropertiesRequest = new MyRefreshPropertiesRequest();
    private final MySynchronizeRequest mySynchronizeRequest = new MySynchronizeRequest(true);

    public MyPsiTreeChangeListener() {
      myAlarm = new Alarm();
    }

    /**
     * Cancels all pending update requests. You have to cancel all pending requests
     * to not access to closed project.
     */
    public void dispose() {
      myAlarm.cancelAllRequests();
    }

    public void childAdded(@NotNull final PsiTreeChangeEvent event) {
      handleEvent(event);
    }

    public void childMoved(@NotNull final PsiTreeChangeEvent event) {
      handleEvent(event);
    }

    public void childrenChanged(@NotNull final PsiTreeChangeEvent event) {
      handleEvent(event);
    }

    public void childRemoved(@NotNull PsiTreeChangeEvent event) {
      handleEvent(event);
    }

    public void childReplaced(@NotNull PsiTreeChangeEvent event) {
      handleEvent(event);
    }

    public void propertyChanged(@NotNull final PsiTreeChangeEvent event) {
      if (PsiTreeChangeEvent.PROP_ROOTS.equals(event.getPropertyName())) {
        myAlarm.cancelRequest(myRefreshPropertiesRequest);
        myAlarm.addRequest(myRefreshPropertiesRequest, 500, ModalityState.stateForComponent(GuiEditor.this));
      }
    }

    private void handleEvent(final PsiTreeChangeEvent event) {
      if (event.getParent() != null) {
        PsiFile containingFile = event.getParent().getContainingFile();
        if (containingFile instanceof PropertiesFile) {
          LOG.debug("Received PSI change event for properties file");
          myAlarm.cancelRequest(myRefreshPropertiesRequest);
          myAlarm.addRequest(myRefreshPropertiesRequest, 500, ModalityState.stateForComponent(GuiEditor.this));
        }
        else if (containingFile instanceof PsiPlainTextFile && containingFile.getFileType().equals(StdFileTypes.GUI_DESIGNER_FORM)) {
          // quick check if relevant
          String resourceName = FormEditingUtil.buildResourceName(containingFile);
          if (myDocument.getText().indexOf(resourceName) >= 0) {
            LOG.debug("Received PSI change event for nested form");
            // TODO[yole]: handle multiple nesting
            myAlarm.cancelRequest(mySynchronizeRequest);
            myAlarm.addRequest(mySynchronizeRequest, 500, ModalityState.stateForComponent(GuiEditor.this));
          }
        }
      }
    }
  }

  private class MySynchronizeRequest implements Runnable {
    private final boolean myKeepSelection;

    public MySynchronizeRequest(final boolean keepSelection) {
      myKeepSelection = keepSelection;
    }

    public void run() {
      if (getModule().isDisposed()) {
        return;
      }
      Project project = getProject();
      if (project.isDisposed()) {
        return;
      }
      LOG.debug("Synchronizing GUI editor " + myFile.getName() + " to document");
      PsiDocumentManager.getInstance(project).commitDocument(myDocument);
      readFromFile(myKeepSelection);
    }
  }

  private class MyRefreshPropertiesRequest implements Runnable {
    public void run() {
      if (!getModule().isDisposed() && !getProject().isDisposed()) {
        refreshProperties();
      }
    }
  }

  private class MyPaletteKeyListener extends KeyAdapter {
    @Override
    public void keyPressed(KeyEvent e) {
      PaletteManager paletteManager = PaletteManager.getInstance(getProject());
      if (e.getKeyCode() == KeyEvent.VK_SHIFT && paletteManager.getActiveItem(ComponentItem.class) != null && isActiveEditor()) {
        setDesignTimeInsets(12);
      }
    }

    @Override
    public void keyReleased(KeyEvent e) {
      if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
        setDesignTimeInsets(2);
      }
    }
  }

  private class MyPaletteDragListener implements PaletteDragEventListener {
    public void dropActionChanged(int gestureModifiers) {
      if ((gestureModifiers & InputEvent.SHIFT_MASK) != 0 && isActiveEditor()) {
        setDesignTimeInsets(12);
      }
      else {
        setDesignTimeInsets(2);
      }
    }
  }

  private class MyPaletteSelectionListener implements ListSelectionListener {
    public void valueChanged(ListSelectionEvent e) {
      if (PaletteManager.getInstance(getProject()).getActiveItem() == null) {
        myProcessor.cancelPaletteInsert();
      }
    }
  }
}