Snapshot 36a7a0702ddda30083713c9b8f140495d5f09d32 from master branch of git://git.jetbrains.org/idea/community.git

Change-Id: Ia9068e36d373808400a123a395b037bdb6940a17
diff --git a/.idea/libraries/rhino_js_1_7R4.xml b/.idea/libraries/rhino_js_1_7R4.xml
deleted file mode 100644
index 5944b78..0000000
--- a/.idea/libraries/rhino_js_1_7R4.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<component name="libraryTable">
-  <library name="rhino-js-1_7R4">
-    <CLASSES>
-      <root url="jar://$PROJECT_DIR$/lib/rhino-js-1_7R4.jar!/" />
-    </CLASSES>
-    <JAVADOC />
-    <SOURCES>
-      <root url="jar://$PROJECT_DIR$/lib/src/rhino-js-1_7R4.zip!/src" />
-    </SOURCES>
-  </library>
-</component>
\ No newline at end of file
diff --git a/.idea/libraries/sass_stdlib.xml b/.idea/libraries/sass_stdlib.xml
deleted file mode 100644
index fa4e8b4..0000000
--- a/.idea/libraries/sass_stdlib.xml
+++ /dev/null
@@ -1,9 +0,0 @@
-<component name="libraryTable">
-  <library name="sass-stdlib">
-    <CLASSES />
-    <JAVADOC />
-    <SOURCES>
-      <root url="file://$APPLICATION_HOME_DIR$/plugins/sass/lib/stubs/sass_functions.scss" />
-    </SOURCES>
-  </library>
-</component>
\ No newline at end of file
diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/generic/GenericCompilerPersistentData.java b/java/compiler/impl/src/com/intellij/compiler/impl/generic/GenericCompilerPersistentData.java
index 513be6c..86c6803 100644
--- a/java/compiler/impl/src/com/intellij/compiler/impl/generic/GenericCompilerPersistentData.java
+++ b/java/compiler/impl/src/com/intellij/compiler/impl/generic/GenericCompilerPersistentData.java
@@ -16,6 +16,7 @@
 package com.intellij.compiler.impl.generic;
 
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.util.io.IOUtil;
 import gnu.trove.TIntHashSet;
 import org.jetbrains.annotations.NotNull;
@@ -46,32 +47,38 @@
       return;
     }
 
-    DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(myFile)));
     try {
-      final int dataVersion = input.readInt();
-      if (dataVersion != VERSION) {
-        LOG.info("Version of compiler info file (" + myFile.getAbsolutePath() + ") changed: " + dataVersion + " -> " + VERSION);
-        myVersionChanged = true;
-        return;
-      }
+      DataInputStream input = new DataInputStream(new BufferedInputStream(new FileInputStream(myFile)));
+      try {
+        final int dataVersion = input.readInt();
+        if (dataVersion != VERSION) {
+          LOG.info("Version of compiler info file (" + myFile.getAbsolutePath() + ") changed: " + dataVersion + " -> " + VERSION);
+          myVersionChanged = true;
+          return;
+        }
 
-      final int savedCompilerVersion = input.readInt();
-      if (savedCompilerVersion != compilerVersion) {
-        LOG.info("Compiler caches version changed (" + myFile.getAbsolutePath() + "): " + savedCompilerVersion + " -> " + compilerVersion);
-        myVersionChanged = true;
-        return;
-      }
+        final int savedCompilerVersion = input.readInt();
+        if (savedCompilerVersion != compilerVersion) {
+          LOG.info("Compiler caches version changed (" + myFile.getAbsolutePath() + "): " + savedCompilerVersion + " -> " + compilerVersion);
+          myVersionChanged = true;
+          return;
+        }
 
-      int size = input.readInt();
-      while (size-- > 0) {
-        final String target = IOUtil.readString(input);
-        final int id = input.readInt();
-        myTarget2Id.put(target, id);
-        myUsedIds.add(id);
+        int size = input.readInt();
+        while (size-- > 0) {
+          final String target = IOUtil.readString(input);
+          final int id = input.readInt();
+          myTarget2Id.put(target, id);
+          myUsedIds.add(id);
+        }
+      }
+      finally {
+        input.close();
       }
     }
-    finally {
-      input.close();
+    catch (IOException e) {
+      FileUtil.delete(myFile);
+      throw e;
     }
   }
 
diff --git a/java/idea-ui/src/com/intellij/framework/FrameworkGroup.java b/java/idea-ui/src/com/intellij/framework/FrameworkGroup.java
new file mode 100644
index 0000000..bd626e5
--- /dev/null
+++ b/java/idea-ui/src/com/intellij/framework/FrameworkGroup.java
@@ -0,0 +1,34 @@
+package com.intellij.framework;
+
+import org.jetbrains.annotations.NotNull;
+
+import javax.swing.*;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author nik
+ */
+public abstract class FrameworkGroup {
+  private final String myId;
+
+  public FrameworkGroup(String id) {
+    myId = id;
+  }
+
+  @NotNull
+  public final String getId() {
+    return myId;
+  }
+
+  @NotNull
+  public abstract String getPresentableName();
+
+  @NotNull
+  public abstract Icon getIcon();
+
+  @NotNull
+  public List<String> getGroupVersions() {
+    return Collections.emptyList();
+  }
+}
diff --git a/java/idea-ui/src/com/intellij/framework/FrameworkTypeEx.java b/java/idea-ui/src/com/intellij/framework/FrameworkTypeEx.java
index ce58e53..4c8e59e 100644
--- a/java/idea-ui/src/com/intellij/framework/FrameworkTypeEx.java
+++ b/java/idea-ui/src/com/intellij/framework/FrameworkTypeEx.java
@@ -30,6 +30,11 @@
     super(id);
   }
 
+  @Nullable
+  public FrameworkGroup getParentGroup() {
+    return null;
+  }
+
   @NotNull
   public abstract FrameworkSupportInModuleProvider createProvider();
 
diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java
index 312d9d1..bb54043b 100644
--- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java
+++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AddSupportForFrameworksPanel.java
@@ -19,6 +19,7 @@
 import com.intellij.facet.impl.ui.libraries.LibraryCompositionSettings;
 import com.intellij.facet.impl.ui.libraries.LibraryOptionsPanel;
 import com.intellij.facet.ui.FacetBasedFrameworkSupportProvider;
+import com.intellij.framework.FrameworkGroup;
 import com.intellij.framework.addSupport.FrameworkSupportInModuleConfigurable;
 import com.intellij.framework.addSupport.FrameworkSupportInModuleProvider;
 import com.intellij.ide.util.frameworkSupport.FrameworkSupportConfigurable;
@@ -33,12 +34,14 @@
 import com.intellij.openapi.roots.ModifiableRootModel;
 import com.intellij.openapi.roots.libraries.Library;
 import com.intellij.openapi.roots.ui.configuration.projectRoot.LibrariesContainer;
+import com.intellij.openapi.ui.ComboBox;
 import com.intellij.openapi.ui.Splitter;
+import com.intellij.openapi.ui.VerticalFlowLayout;
 import com.intellij.openapi.util.Comparing;
-import com.intellij.openapi.util.MultiValuesMap;
 import com.intellij.ui.CheckedTreeNode;
 import com.intellij.ui.ScrollPaneFactory;
 import com.intellij.util.containers.ContainerUtil;
+import com.intellij.util.ui.FormBuilder;
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -59,14 +62,15 @@
   @NonNls private static final String EMPTY_CARD = "empty";
   private JPanel myMainPanel;
   private JPanel myFrameworksPanel;
-  private List<List<FrameworkSupportNode>> myGroups;
+  private List<FrameworkSupportNodeBase> myRoots;
   private final LibrariesContainer myLibrariesContainer;
   private final List<FrameworkSupportInModuleProvider> myProviders;
   private final FrameworkSupportModelBase myModel;
   private final JPanel myOptionsPanel;
   private final FrameworksTree myFrameworksTree;
   private final Map<FrameworkSupportNode, FrameworkSupportOptionsComponent> myInitializedOptionsComponents = new HashMap<FrameworkSupportNode, FrameworkSupportOptionsComponent>();
-  private FrameworkSupportNode myLastSelectedNode;
+  private final Map<FrameworkGroup, JPanel> myInitializedGroupPanels = new HashMap<FrameworkGroup, JPanel>();
+  private FrameworkSupportNodeBase myLastSelectedNode;
 
   public AddSupportForFrameworksPanel(final List<FrameworkSupportInModuleProvider> providers, final FrameworkSupportModelBase model) {
     myModel = model;
@@ -75,7 +79,7 @@
     createNodes();
 
     final Splitter splitter = new Splitter(false, 0.30f, 0.1f, 0.7f);
-    myFrameworksTree = new FrameworksTree(myGroups) {
+    myFrameworksTree = new FrameworksTree(myRoots) {
       @Override
       protected void onNodeStateChanged(CheckedTreeNode node) {
         if (!(node instanceof FrameworkSupportNode)) return;
@@ -113,7 +117,7 @@
       updateOptionsPanel();
     }
     
-    final FrameworkSupportNode selectedNode = getSelectedNode();
+    final FrameworkSupportNodeBase selectedNode = getSelectedNode();
     if (!Comparing.equal(selectedNode, myLastSelectedNode)) {
       applyLibraryOptionsForSelected();
 
@@ -126,8 +130,8 @@
   }
 
   private void applyLibraryOptionsForSelected() {
-    if (myLastSelectedNode != null) {
-      final FrameworkSupportOptionsComponent optionsComponent = myInitializedOptionsComponents.get(myLastSelectedNode);
+    if (myLastSelectedNode instanceof FrameworkSupportNode) {
+      final FrameworkSupportOptionsComponent optionsComponent = myInitializedOptionsComponents.get((FrameworkSupportNode)myLastSelectedNode);
       if (optionsComponent != null) {
         final LibraryOptionsPanel optionsPanel = optionsComponent.getLibraryOptionsPanel();
         if (optionsPanel != null) {
@@ -138,34 +142,55 @@
   }
 
   private void updateOptionsPanel() {
-    final FrameworkSupportNode node = getSelectedNode();
-    if (node != null) {
-      initializeOptionsPanel(node);
-      showCard(node.getProvider().getFrameworkType().getId());
-      UIUtil.setEnabled(myOptionsPanel, node.isChecked(), true);
-      node.getConfigurable().onFrameworkSelectionChanged(node.isChecked());
+    final FrameworkSupportNodeBase node = getSelectedNode();
+    if (node instanceof FrameworkSupportNode) {
+      FrameworkSupportNode frameworkSupportNode = (FrameworkSupportNode)node;
+      initializeOptionsPanel(frameworkSupportNode);
+      showCard(frameworkSupportNode.getProvider().getFrameworkType().getId());
+      UIUtil.setEnabled(myOptionsPanel, frameworkSupportNode.isChecked(), true);
+      frameworkSupportNode.getConfigurable().onFrameworkSelectionChanged(node.isChecked());
+    }
+    else if (node instanceof FrameworkGroupNode) {
+      FrameworkGroup group = ((FrameworkGroupNode)node).getGroup();
+      initializeGroupPanel(group);
+      showCard(group.getId());
     }
     else {
       showCard(EMPTY_CARD);
     }
   }
 
+  private void initializeGroupPanel(FrameworkGroup group) {
+    if (!myInitializedGroupPanels.containsKey(group)) {
+      JPanel panel = new JPanel(new VerticalFlowLayout());
+      List<String> versions = group.getGroupVersions();
+      if (!versions.isEmpty()) {
+        ComboBox versionsBox = new ComboBox();
+        for (String version : versions) {
+          versionsBox.addItem(version);
+        }
+        panel.add(FormBuilder.createFormBuilder().addLabeledComponent("Version:", versionsBox).getPanel());
+      }
+      myInitializedGroupPanels.put(group, panel);
+      myOptionsPanel.add(group.getId(), panel);
+    }
+  }
+
   @Nullable
-  private FrameworkSupportNode getSelectedNode() {
-    final FrameworkSupportNode[] nodes = myFrameworksTree.getSelectedNodes(FrameworkSupportNode.class, null);
+  private FrameworkSupportNodeBase getSelectedNode() {
+    final FrameworkSupportNodeBase[] nodes = myFrameworksTree.getSelectedNodes(FrameworkSupportNodeBase.class, null);
     return nodes.length == 1 ? nodes[0] : null;
   }
 
   private void initializeOptionsPanel(final FrameworkSupportNode node) {
     if (!myInitializedOptionsComponents.containsKey(node)) {
-      final FrameworkSupportNode parentNode = node.getParentNode();
-      if (parentNode != null) {
-        initializeOptionsPanel(parentNode);
+      final FrameworkSupportNodeBase parentNode = node.getParentNode();
+      if (parentNode instanceof FrameworkSupportNode) {
+        initializeOptionsPanel((FrameworkSupportNode)parentNode);
       }
 
       FrameworkSupportOptionsComponent optionsComponent = new FrameworkSupportOptionsComponent(myModel, myLibrariesContainer, this,
-                                                                                               node.getProvider(), node.getConfigurable()
-      );
+                                                                                               node.getProvider(), node.getConfigurable());
       final String id = node.getProvider().getFrameworkType().getId();
       myOptionsPanel.add(id, optionsComponent.getMainPanel());
       myInitializedOptionsComponents.put(node, optionsComponent);
@@ -202,47 +227,47 @@
 
   private void createNodes() {
     Map<String, FrameworkSupportNode> nodes = new HashMap<String, FrameworkSupportNode>();
-    MultiValuesMap<String, FrameworkSupportNode> groups = new MultiValuesMap<String, FrameworkSupportNode>(true);
+    Map<FrameworkGroup, FrameworkGroupNode> groups = new HashMap<FrameworkGroup, FrameworkGroupNode>();
+    List<FrameworkSupportNodeBase> roots = new ArrayList<FrameworkSupportNodeBase>();
     for (FrameworkSupportInModuleProvider provider : myProviders) {
-      createNode(provider, nodes, groups);
+      createNode(provider, nodes, groups, roots);
     }
 
-    myGroups = new ArrayList<List<FrameworkSupportNode>>();
-    for (String groupId : groups.keySet()) {
-      final Collection<FrameworkSupportNode> collection = groups.get(groupId);
-      if (collection != null) {
-        final List<FrameworkSupportNode> group = new ArrayList<FrameworkSupportNode>();
-        for (FrameworkSupportNode node : collection) {
-          if (node.getParentNode() == null) {
-            group.add(node);
-          }
-        }
-        FrameworkSupportNode.sortByName(group);
-        myGroups.add(group);
-      }
-    }
+    FrameworkSupportNodeBase.sortByName(roots);
+    myRoots = roots;
   }
 
   @Nullable
   private FrameworkSupportNode createNode(final FrameworkSupportInModuleProvider provider, final Map<String, FrameworkSupportNode> nodes,
-                                              final MultiValuesMap<String, FrameworkSupportNode> groups) {
+                                          final Map<FrameworkGroup, FrameworkGroupNode> groupNodes,
+                                          List<FrameworkSupportNodeBase> roots) {
     FrameworkSupportNode node = nodes.get(provider.getFrameworkType().getId());
     if (node == null) {
       String underlyingTypeId = provider.getFrameworkType().getUnderlyingFrameworkTypeId();
-      FrameworkSupportNode parentNode = null;
+      FrameworkSupportNodeBase parentNode = null;
+      final FrameworkGroup group = provider.getFrameworkType().getParentGroup();
       if (underlyingTypeId != null) {
         FrameworkSupportInModuleProvider parentProvider = FrameworkSupportUtil.findProvider(underlyingTypeId, myProviders);
         if (parentProvider == null) {
           LOG.info("Cannot find id = " + underlyingTypeId);
           return null;
         }
-        parentNode = createNode(parentProvider, nodes, groups);
+        parentNode = createNode(parentProvider, nodes, groupNodes, roots);
+      }
+      else if (group != null) {
+        parentNode = groupNodes.get(group);
+        if (parentNode == null) {
+          FrameworkGroupNode groupNode = new FrameworkGroupNode(group, null);
+          groupNodes.put(group, groupNode);
+          parentNode = groupNode;
+          roots.add(groupNode);
+        }
       }
       node = new FrameworkSupportNode(provider, parentNode, myModel, this);
       nodes.put(provider.getFrameworkType().getId(), node);
-      final String groupId = provider instanceof OldFrameworkSupportProviderWrapper
-                             ? ((OldFrameworkSupportProviderWrapper)provider).getProvider().getGroupId() : null;
-      groups.put(groupId, node);
+      if (parentNode == null) {
+        roots.add(node);
+      }
     }
     return node;
   }
@@ -260,20 +285,20 @@
   }
 
   private List<FrameworkSupportNode> getFrameworkNodes(final boolean selectedOnly) {
-    ArrayList<FrameworkSupportNode> list = new ArrayList<FrameworkSupportNode>();
-    if (myGroups != null) {
-      for (List<FrameworkSupportNode> group : myGroups) {
-        addChildFrameworks(group, list, selectedOnly);
-      }
+    List<FrameworkSupportNode> list = new ArrayList<FrameworkSupportNode>();
+    if (myRoots != null) {
+      addChildFrameworks(myRoots, list, selectedOnly);
     }
     return list;
   }
 
-  private static void addChildFrameworks(final List<FrameworkSupportNode> list, final List<FrameworkSupportNode> result,
+  private static void addChildFrameworks(final List<FrameworkSupportNodeBase> list, final List<FrameworkSupportNode> result,
                                          final boolean selectedOnly) {
-    for (FrameworkSupportNode node : list) {
+    for (FrameworkSupportNodeBase node : list) {
       if (!selectedOnly || node.isChecked()) {
-        result.add(node);
+        if (node instanceof FrameworkSupportNode) {
+          result.add((FrameworkSupportNode)node);
+        }
         addChildFrameworks(node.getChildren(), result, selectedOnly);
       }
     }
diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkGroupNode.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkGroupNode.java
new file mode 100644
index 0000000..2a513d3
--- /dev/null
+++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkGroupNode.java
@@ -0,0 +1,34 @@
+package com.intellij.ide.util.newProjectWizard;
+
+import com.intellij.framework.FrameworkGroup;
+import org.jetbrains.annotations.NotNull;
+
+import javax.swing.*;
+
+/**
+ * @author nik
+ */
+public class FrameworkGroupNode extends FrameworkSupportNodeBase {
+  private final FrameworkGroup myGroup;
+
+  public FrameworkGroupNode(@NotNull FrameworkGroup group, FrameworkSupportNodeBase parent) {
+    super(group, parent);
+    myGroup = group;
+  }
+
+  public FrameworkGroup getGroup() {
+    return myGroup;
+  }
+
+  @NotNull
+  @Override
+  protected String getTitle() {
+    return myGroup.getPresentableName();
+  }
+
+  @NotNull
+  @Override
+  public Icon getIcon() {
+    return myGroup.getIcon();
+  }
+}
diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNode.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNode.java
index 180e4e5..84d7280 100644
--- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNode.java
+++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNode.java
@@ -20,51 +20,32 @@
 import com.intellij.ide.util.newProjectWizard.impl.FrameworkSupportModelBase;
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.util.Disposer;
-import com.intellij.ui.CheckedTreeNode;
+import org.jetbrains.annotations.NotNull;
 
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.List;
+import javax.swing.*;
 
 /**
 * @author nik
 */
-public class FrameworkSupportNode extends CheckedTreeNode {
+public class FrameworkSupportNode extends FrameworkSupportNodeBase {
   private final FrameworkSupportInModuleProvider myProvider;
-  private final FrameworkSupportNode myParentNode;
   private FrameworkSupportInModuleConfigurable myConfigurable;
-  private final List<FrameworkSupportNode> myChildren = new ArrayList<FrameworkSupportNode>();
   private final FrameworkSupportModelBase myModel;
   private final Disposable myParentDisposable;
 
-  public FrameworkSupportNode(final FrameworkSupportInModuleProvider provider, final FrameworkSupportNode parentNode, final FrameworkSupportModelBase model,
+  public FrameworkSupportNode(final FrameworkSupportInModuleProvider provider, final FrameworkSupportNodeBase parentNode, final FrameworkSupportModelBase model,
                               Disposable parentDisposable) {
-    super(provider);
+    super(provider, parentNode);
     myParentDisposable = parentDisposable;
-    setChecked(false);
     myProvider = provider;
-    myParentNode = parentNode;
     model.registerComponent(provider, this);
     myModel = model;
-    if (parentNode != null) {
-      parentNode.add(this);
-      parentNode.myChildren.add(this);
-    }
-  }
-
-  public List<FrameworkSupportNode> getChildren() {
-    return myChildren;
   }
 
   public FrameworkSupportInModuleProvider getProvider() {
     return myProvider;
   }
 
-  public FrameworkSupportNode getParentNode() {
-    return myParentNode;
-  }
-
   public synchronized FrameworkSupportInModuleConfigurable getConfigurable() {
     if (myConfigurable == null) {
       myConfigurable = myProvider.createConfigurable(myModel);
@@ -73,24 +54,14 @@
     return myConfigurable;
   }
 
-  public static void sortByName(List<FrameworkSupportNode> nodes) {
-    if (nodes.isEmpty()) return;
-
-    Collections.sort(nodes, new Comparator<FrameworkSupportNode>() {
-      public int compare(final FrameworkSupportNode o1, final FrameworkSupportNode o2) {
-        return o1.getTitle().compareToIgnoreCase(o2.getTitle());
-      }
-    });
-    for (FrameworkSupportNode node : nodes) {
-      node.sortChildren();
-    }
-  }
-
+  @NotNull
   public String getTitle() {
     return myProvider.getFrameworkType().getPresentableName();
   }
 
-  private void sortChildren() {
-    sortByName(myChildren);
+  @NotNull
+  @Override
+  public Icon getIcon() {
+    return myProvider.getFrameworkType().getIcon();
   }
 }
diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNodeBase.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNodeBase.java
new file mode 100644
index 0000000..0e737f8
--- /dev/null
+++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworkSupportNodeBase.java
@@ -0,0 +1,59 @@
+package com.intellij.ide.util.newProjectWizard;
+
+import com.intellij.ui.CheckedTreeNode;
+import org.jetbrains.annotations.NotNull;
+
+import javax.swing.*;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * @author nik
+ */
+public abstract class FrameworkSupportNodeBase extends CheckedTreeNode {
+  protected final FrameworkSupportNodeBase myParentNode;
+  protected final List<FrameworkSupportNodeBase> myChildren = new ArrayList<FrameworkSupportNodeBase>();
+
+  public FrameworkSupportNodeBase(Object userObject, final FrameworkSupportNodeBase parentNode) {
+    super(userObject);
+    setChecked(false);
+    myParentNode = parentNode;
+    if (parentNode != null) {
+      parentNode.add(this);
+      parentNode.myChildren.add(this);
+    }
+  }
+
+  public static void sortByName(List<FrameworkSupportNodeBase> nodes) {
+    if (nodes.isEmpty()) return;
+
+    Collections.sort(nodes, new Comparator<FrameworkSupportNodeBase>() {
+      public int compare(final FrameworkSupportNodeBase o1, final FrameworkSupportNodeBase o2) {
+        return o1.getTitle().compareToIgnoreCase(o2.getTitle());
+      }
+    });
+    for (FrameworkSupportNodeBase node : nodes) {
+      node.sortChildren();
+    }
+  }
+
+  @NotNull
+  protected abstract String getTitle();
+
+  @NotNull
+  public abstract Icon getIcon();
+
+  public List<FrameworkSupportNodeBase> getChildren() {
+    return myChildren;
+  }
+
+  public FrameworkSupportNodeBase getParentNode() {
+    return myParentNode;
+  }
+
+  private void sortChildren() {
+    sortByName(myChildren);
+  }
+}
diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworksTree.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworksTree.java
index 30a188a..bed73f5 100644
--- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworksTree.java
+++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/FrameworksTree.java
@@ -33,8 +33,8 @@
 public class FrameworksTree extends CheckboxTree {
   private boolean myProcessingMouseEventOnCheckbox;
 
-  public FrameworksTree(List<List<FrameworkSupportNode>> groups) {
-    super(new FrameworksTreeRenderer(), new FrameworksRootNode(groups), new CheckPolicy(false, true, true, false));
+  public FrameworksTree(List<FrameworkSupportNodeBase> roots) {
+    super(new FrameworksTreeRenderer(), new FrameworksRootNode(roots), new CheckPolicy(false, true, true, false));
     setRootVisible(false);
     setShowsRootHandles(false);
     TreeUtil.expandAll(this);
@@ -71,8 +71,8 @@
       @Override
       public String convert(TreePath path) {
         final Object node = path.getLastPathComponent();
-        if (node instanceof FrameworkSupportNode) {
-          return ((FrameworkSupportNode)node).getTitle();
+        if (node instanceof FrameworkSupportNodeBase) {
+          return ((FrameworkSupportNodeBase)node).getTitle();
         }
         return "";
       }
@@ -90,21 +90,20 @@
 
     @Override
     public void customizeRenderer(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
-      if (value instanceof FrameworkSupportNode) {
-        final FrameworkSupportNode node = (FrameworkSupportNode)value;
+      if (value instanceof FrameworkSupportNodeBase) {
+        final FrameworkSupportNodeBase node = (FrameworkSupportNodeBase)value;
         getTextRenderer().append(node.getTitle());
-        getTextRenderer().setIcon(node.getProvider().getFrameworkType().getIcon());
+        getTextRenderer().setIcon(node.getIcon());
+        getCheckbox().setVisible(value instanceof FrameworkSupportNode);
       }
     }
   }
 
   private static class FrameworksRootNode extends CheckedTreeNode {
-    public FrameworksRootNode(List<List<FrameworkSupportNode>> groups) {
+    public FrameworksRootNode(List<FrameworkSupportNodeBase> roots) {
       super(null);
-      for (List<FrameworkSupportNode> group : groups) {
-        for (FrameworkSupportNode node : group) {
-          add(node);
-        }
+      for (FrameworkSupportNodeBase node : roots) {
+        add(node);
       }
     }
   }
diff --git a/java/idea-ui/src/com/intellij/platform/templates/ArchivedTemplatesFactory.java b/java/idea-ui/src/com/intellij/platform/templates/ArchivedTemplatesFactory.java
index 1695a82..919f952 100644
--- a/java/idea-ui/src/com/intellij/platform/templates/ArchivedTemplatesFactory.java
+++ b/java/idea-ui/src/com/intellij/platform/templates/ArchivedTemplatesFactory.java
@@ -51,6 +51,7 @@
       IdeaPluginDescriptor[] plugins = PluginManager.getPlugins();
       Map<URL, ClassLoader> urls = new HashMap<URL, ClassLoader>();
       for (IdeaPluginDescriptor plugin : plugins) {
+        if (!plugin.isEnabled()) continue;
         try {
           ClassLoader loader = plugin.getPluginClassLoader();
           Enumeration<URL> resources = loader.getResources("resources/projectTemplates");
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java
index 1e5d68f..3f9bf87 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java
@@ -893,6 +893,7 @@
     return typeParameters[0];
   }
 
+  //http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.9.2
   @Nullable
   public static HighlightInfo checkAccessStaticFieldFromEnumConstructor(PsiReferenceExpression expr, JavaResolveResult result) {
     final PsiElement resolved = result.getElement();
@@ -903,14 +904,17 @@
     if (constructorOrInitializer == null) return null;
     if (constructorOrInitializer.hasModifierProperty(PsiModifier.STATIC)) return null;
     final PsiClass aClass = constructorOrInitializer.getContainingClass();
-    if (aClass == null) return null;
-    if (!aClass.isEnum()) return null;
+    if (aClass == null || !(aClass.isEnum() || aClass instanceof PsiEnumConstantInitializer)) return null;
     final PsiField field = (PsiField)resolved;
-    if (field.getContainingClass() != aClass) return null;
-    final PsiType type = field.getType();
+    if (aClass instanceof PsiEnumConstantInitializer) {
+      if (field.getContainingClass() != aClass.getSuperClass()) return null;
+    } else if (field.getContainingClass() != aClass) return null;
 
-    //TODO is access to enum constant is allowed ?
-    if (type instanceof PsiClassType && ((PsiClassType)type).resolve() == aClass) return null;
+
+    if (!JavaVersionService.getInstance().isAtLeast(field, JavaSdkVersion.JDK_1_6)) {
+      final PsiType type = field.getType();
+      if (type instanceof PsiClassType && ((PsiClassType)type).resolve() == aClass) return null;
+    }
 
     if (PsiUtil.isCompileTimeConstant(field)) return null;
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java
index 2487c3d..58e2acc 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightClassUtil.java
@@ -778,7 +778,7 @@
           if (!PsiUtil.isInnerClass(base)) return;
 
           if (resolve == resolved && baseClass != null && (!PsiTreeUtil.isAncestor(baseClass, extendRef, true) || aClass.hasModifierProperty(PsiModifier.STATIC)) &&
-              !hasEnclosingInstanceInScope(baseClass, extendRef, true, true) && !qualifiedNewCalledInConstructors(aClass, baseClass)) {
+              !hasEnclosingInstanceInScope(baseClass, extendRef, !aClass.hasModifierProperty(PsiModifier.STATIC), true) && !qualifiedNewCalledInConstructors(aClass, baseClass)) {
             String description = JavaErrorMessages.message("no.enclosing.instance.in.scope", HighlightUtil.formatClass(baseClass));
             infos[0] = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(extendRef).descriptionAndTooltip(description).create();
           }
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java
index 7a4ca78..5a0f156 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -41,7 +41,7 @@
 
 /**
  * @author cdr
- * Date: Aug 8, 2002
+ * @since Aug 8, 2002
  */
 public class HighlightControlFlowUtil {
   private static final QuickFixFactory QUICK_FIX_FACTORY = QuickFixFactory.getInstance();
@@ -50,48 +50,42 @@
 
   @Nullable
   public static HighlightInfo checkMissingReturnStatement(PsiCodeBlock body, PsiType returnType) {
-    
-    if (body == null
-        || returnType == null
-        || PsiType.VOID.equals(returnType)) {
+    if (body == null || returnType == null || PsiType.VOID.equals(returnType.getDeepComponentType())) {
       return null;
     }
+
     // do not compute constant expressions for if() statement condition
     // see JLS 14.20 Unreachable Statements
     try {
-      final ControlFlow controlFlow = getControlFlowNoConstantEvaluate(body);
+      ControlFlow controlFlow = getControlFlowNoConstantEvaluate(body);
       if (!ControlFlowUtil.returnPresent(controlFlow)) {
-        final PsiJavaToken rBrace = body.getRBrace();
-        final PsiElement context = rBrace == null
-                                   ? body.getLastChild()
-                                   : rBrace;
-        String description = JavaErrorMessages.message("missing.return.statement");
-        final HighlightInfo highlightInfo =
-          HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(context).descriptionAndTooltip(description).create();
-        final PsiElement parent = body.getParent();
+        PsiJavaToken rBrace = body.getRBrace();
+        PsiElement context = rBrace == null ? body.getLastChild() : rBrace;
+        String message = JavaErrorMessages.message("missing.return.statement");
+        HighlightInfo info = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(context).descriptionAndTooltip(message).create();
+        PsiElement parent = body.getParent();
         if (parent instanceof PsiMethod) {
-          final PsiMethod method = (PsiMethod)parent;
-          QuickFixAction.registerQuickFixAction(highlightInfo, new AddReturnFix(method));
+          PsiMethod method = (PsiMethod)parent;
+          QuickFixAction.registerQuickFixAction(info, new AddReturnFix(method));
           IntentionAction fix = QUICK_FIX_FACTORY.createMethodReturnFix(method, PsiType.VOID, true);
-          QuickFixAction.registerQuickFixAction(highlightInfo, fix);
+          QuickFixAction.registerQuickFixAction(info, fix);
         }
-        return highlightInfo;
+        return info;
       }
     }
-    catch (AnalysisCanceledException e) {
-      // incomplete code
-    }
+    catch (AnalysisCanceledException ignored) { }
+
     return null;
-
   }
 
-  public static ControlFlow getControlFlowNoConstantEvaluate(final PsiElement body) throws AnalysisCanceledException {
-    return ControlFlowFactory.getInstance(body.getProject()).getControlFlow(body,
-                                                                      LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance(),
-                                                                      false);
+  public static ControlFlow getControlFlowNoConstantEvaluate(PsiElement body) throws AnalysisCanceledException {
+    LocalsOrMyInstanceFieldsControlFlowPolicy policy = LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance();
+    return ControlFlowFactory.getInstance(body.getProject()).getControlFlow(body, policy, false);
   }
-  private static ControlFlow getControlFlow(final PsiElement context) throws AnalysisCanceledException {
-    return ControlFlowFactory.getInstance(context.getProject()).getControlFlow(context, LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance());
+
+  private static ControlFlow getControlFlow(PsiElement context) throws AnalysisCanceledException {
+    LocalsOrMyInstanceFieldsControlFlowPolicy policy = LocalsOrMyInstanceFieldsControlFlowPolicy.getInstance();
+    return ControlFlowFactory.getInstance(context.getProject()).getControlFlow(context, policy);
   }
 
   public static HighlightInfo checkUnreachableStatement(PsiCodeBlock codeBlock) {
@@ -683,12 +677,12 @@
     if (innerClass != null) {
       if (variable instanceof PsiParameter) {
         final PsiElement parent = variable.getParent();
-        if (parent instanceof PsiParameterList && parent.getParent() instanceof PsiLambdaExpression && 
+        if (parent instanceof PsiParameterList && parent.getParent() instanceof PsiLambdaExpression &&
             notAccessedForWriting(variable, new LocalSearchScope(((PsiParameter)variable).getDeclarationScope()))) {
           return null;
         }
       }
-      if (PsiUtil.getLanguageLevel(variable).isAtLeast(LanguageLevel.JDK_1_8) && 
+      if (PsiUtil.getLanguageLevel(variable).isAtLeast(LanguageLevel.JDK_1_8) &&
           isEffectivelyFinal(variable, innerClass, context)) {
         return null;
       }
@@ -738,7 +732,7 @@
     }
     return effectivelyFinal;
   }
-  
+
   private static boolean notAccessedForWriting(PsiVariable variable, final LocalSearchScope searchScope) {
     for (PsiReference reference : ReferencesSearch.search(variable, searchScope)) {
       final PsiElement element = reference.getElement();
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
index 2098dd6..8fc4b73 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
@@ -32,6 +32,8 @@
 import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.projectRoots.JavaSdkVersion;
+import com.intellij.openapi.projectRoots.JavaVersionService;
 import com.intellij.openapi.roots.ProjectFileIndex;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Condition;
@@ -52,7 +54,10 @@
 import com.intellij.psi.templateLanguages.OuterLanguageElement;
 import com.intellij.psi.tree.IElementType;
 import com.intellij.psi.util.*;
-import com.intellij.util.*;
+import com.intellij.util.ArrayUtil;
+import com.intellij.util.ArrayUtilRt;
+import com.intellij.util.Function;
+import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.ui.UIUtil;
 import com.intellij.xml.util.XmlStringUtil;
@@ -1806,10 +1811,10 @@
         return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(typeElement).descriptionAndTooltip(description).create();
       }
     }
+
     return null;
   }
 
-
   @Nullable
   public static HighlightInfo checkIllegalVoidType(@NotNull PsiKeyword type) {
     if (!PsiKeyword.VOID.equals(type.getText())) return null;
@@ -1817,15 +1822,17 @@
     PsiElement parent = type.getParent();
     if (parent instanceof PsiTypeElement) {
       PsiElement typeOwner = parent.getParent();
-      if (typeOwner instanceof PsiMethod) {
-        if (((PsiMethod)typeOwner).getReturnTypeElement() == parent) return null;
-      }
-      else if (// like in Class c = void.class;
-        typeOwner instanceof PsiClassObjectAccessExpression &&
-        TypeConversionUtil.isVoidType(((PsiClassObjectAccessExpression)typeOwner).getOperand().getType()) ||
+      if (typeOwner != null) {
         // do not highlight incomplete declarations
-        typeOwner != null && PsiUtilCore.hasErrorElementChild(typeOwner)) {
-        return null;
+        if (PsiUtilCore.hasErrorElementChild(typeOwner)) return null;
+      }
+
+      if (typeOwner instanceof PsiMethod) {
+        PsiMethod method = (PsiMethod)typeOwner;
+        if (method.getReturnTypeElement() == parent && PsiType.VOID.equals(method.getReturnType())) return null;
+      }
+      else if (typeOwner instanceof PsiClassObjectAccessExpression) {
+        if (TypeConversionUtil.isVoidType(((PsiClassObjectAccessExpression)typeOwner).getOperand().getType())) return null;
       }
       else if (typeOwner instanceof JavaCodeFragment) {
         if (typeOwner.getUserData(PsiUtil.VALID_VOID_TYPE_IN_CODE_FRAGMENT) != null) return null;
@@ -2002,6 +2009,7 @@
 
   @Nullable
   public static HighlightInfo checkImplicitThisReferenceBeforeSuper(@NotNull PsiClass aClass) {
+    if (JavaVersionService.getInstance().isAtLeast(aClass, JavaSdkVersion.JDK_1_7)) return null;
     if (aClass instanceof PsiAnonymousClass) return null;
     PsiClass superClass = aClass.getSuperClass();
     if (superClass == null || !PsiUtil.isInnerClass(superClass)) return null;
@@ -2636,6 +2644,19 @@
     return null;
   }
 
+  @Nullable
+  static HighlightInfo checkForStatement(@NotNull PsiForStatement statement) {
+    PsiStatement init = statement.getInitialization();
+    if (!(init == null || init instanceof PsiEmptyStatement ||
+          init instanceof PsiDeclarationStatement ||
+          init instanceof PsiExpressionStatement || init instanceof PsiExpressionListStatement)) {
+      String message = JavaErrorMessages.message("invalid.statement");
+      return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(init).descriptionAndTooltip(message).create();
+    }
+
+    return null;
+  }
+
   private enum Feature {
     GENERICS(LanguageLevel.JDK_1_5, "feature.generics"),
     ANNOTATIONS(LanguageLevel.JDK_1_5, "feature.annotations"),
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
index 44b5431..f611668 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
@@ -469,6 +469,11 @@
   }
 
   @Override
+  public void visitForStatement(PsiForStatement statement) {
+    myHolder.add(HighlightUtil.checkForStatement(statement));
+  }
+
+  @Override
   public void visitForeachStatement(final PsiForeachStatement statement) {
     myHolder.add(HighlightUtil.checkForEachFeature(statement));
   }
diff --git a/java/java-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspection.java b/java/java-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspection.java
index fdfb716..bc9195dc 100644
--- a/java/java-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspection.java
+++ b/java/java-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspection.java
@@ -425,7 +425,10 @@
   private static LocalQuickFix createChangeDefaultNotNullFix(NullableNotNullManager nullableManager, PsiModifierListOwner modifierListOwner) {
     final PsiAnnotation annotation = AnnotationUtil.findAnnotation(modifierListOwner, nullableManager.getNotNulls());
     if (annotation != null) {
-      return new ChangeNullableDefaultsFix(annotation.getQualifiedName(), null, nullableManager);
+      final PsiJavaCodeReferenceElement referenceElement = annotation.getNameReferenceElement();
+      if (referenceElement != null && referenceElement.resolve() != null) {
+        return new ChangeNullableDefaultsFix(annotation.getQualifiedName(), null, nullableManager);
+      }
     }
     return null;
   }
diff --git a/java/java-impl/src/com/intellij/refactoring/replaceConstructorWithFactory/ReplaceConstructorWithFactoryHandler.java b/java/java-impl/src/com/intellij/refactoring/replaceConstructorWithFactory/ReplaceConstructorWithFactoryHandler.java
index c9480d3..470c5d6 100644
--- a/java/java-impl/src/com/intellij/refactoring/replaceConstructorWithFactory/ReplaceConstructorWithFactoryHandler.java
+++ b/java/java-impl/src/com/intellij/refactoring/replaceConstructorWithFactory/ReplaceConstructorWithFactoryHandler.java
@@ -112,7 +112,7 @@
     final PsiMethod[] constructors = aClass.getConstructors();
     if (constructors.length > 0) {
       String message =
-              RefactoringBundle.message("class.does.not.have.implicit.default.consructor", aClass.getQualifiedName()) ;
+              RefactoringBundle.message("class.does.not.have.implicit.default.constructor", aClass.getQualifiedName()) ;
       CommonRefactoringUtil.showErrorHint(myProject, editor, message, REFACTORING_NAME, HelpID.REPLACE_CONSTRUCTOR_WITH_FACTORY);
       return;
     }
diff --git a/java/java-impl/src/com/intellij/refactoring/util/InlineUtil.java b/java/java-impl/src/com/intellij/refactoring/util/InlineUtil.java
index b053945d..db3e95b 100644
--- a/java/java-impl/src/com/intellij/refactoring/util/InlineUtil.java
+++ b/java/java-impl/src/com/intellij/refactoring/util/InlineUtil.java
@@ -216,6 +216,9 @@
         PsiElement lastInitializerSibling = initializers[initializers.length - 1];
         while (lastInitializerSibling != null) {
           final PsiElement nextSibling = lastInitializerSibling.getNextSibling();
+          if (nextSibling == null) {
+            break;
+          }
           if (nextSibling.getNode().getElementType() == JavaTokenType.RBRACE) break;
           lastInitializerSibling = nextSibling;
         }
diff --git a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java
index 8a6bb46..06d40370d 100644
--- a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java
@@ -234,8 +234,16 @@
   }
 
   @Nullable
-  public static PsiType getVariableTypeByExpressionType(@Nullable final PsiType type) {
+  public static PsiType getVariableTypeByExpressionType(@Nullable PsiType type) {
+    return getVariableTypeByExpressionType(type, true);
+  }
+
+  @Nullable
+  public static PsiType getVariableTypeByExpressionType(@Nullable PsiType type, final boolean openCaptured) {
     if (type == null) return null;
+    if (type instanceof PsiCapturedWildcardType) {
+      type = ((PsiCapturedWildcardType)type).getWildcard();
+    }
     PsiType transformed = type.accept(new PsiTypeVisitor<PsiType>() {
       @Override
       public PsiType visitArrayType(PsiArrayType arrayType) {
@@ -271,7 +279,7 @@
 
       @Override
       public PsiType visitCapturedWildcardType(PsiCapturedWildcardType capturedWildcardType) {
-        return capturedWildcardType.getWildcard().accept(this);
+        return openCaptured ? capturedWildcardType.getWildcard().accept(this) : capturedWildcardType;
       }
 
       @Override
diff --git a/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java b/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java
index 672a013..9cce64d 100644
--- a/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/util/TypeConversionUtil.java
@@ -325,7 +325,7 @@
     PsiClass[] supers = derived.getSupers();
     if (manager.areElementsEquivalent(base, derived)) {
       derivedSubstitutor = getSuperClassSubstitutor(derived, derived, derivedSubstitutor);
-      return areSameArgumentTypes(derived, baseResult.getSubstitutor(), derivedSubstitutor);
+      return areSameArgumentTypes(derived, baseResult.getSubstitutor(), derivedSubstitutor, 1);
     }
     else if (base.isInheritor(derived, true)) {
       derivedSubstitutor = getSuperClassSubstitutor(derived, derived, derivedSubstitutor);
@@ -355,11 +355,18 @@
   }
 
   private static boolean areSameArgumentTypes(PsiClass aClass, PsiSubstitutor substitutor1, PsiSubstitutor substitutor2) {
+    return areSameArgumentTypes(aClass, substitutor1, substitutor2, 0);
+  }
+
+  private static boolean areSameArgumentTypes(PsiClass aClass,
+                                              PsiSubstitutor substitutor1,
+                                              PsiSubstitutor substitutor2,
+                                              int level) {
     for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(aClass)) {
       PsiType typeArg1 = substitutor1.substitute(typeParameter);
       PsiType typeArg2 = substitutor2.substitute(typeParameter);
       if (typeArg1 == null || typeArg2 == null) return true;
-      if (TypesDistinctProver.provablyDistinct(typeArg1, typeArg2)) return false;
+      if (TypesDistinctProver.provablyDistinct(typeArg1, typeArg2, level)) return false;
 
       final PsiClass class1 = PsiUtil.resolveClassInType(typeArg1);
       if (class1 instanceof PsiTypeParameter) {
diff --git a/java/java-psi-api/src/com/intellij/psi/util/TypesDistinctProver.java b/java/java-psi-api/src/com/intellij/psi/util/TypesDistinctProver.java
index 5d2c6aa..df1be58 100644
--- a/java/java-psi-api/src/com/intellij/psi/util/TypesDistinctProver.java
+++ b/java/java-psi-api/src/com/intellij/psi/util/TypesDistinctProver.java
@@ -35,7 +35,7 @@
     return provablyDistinct(type1, type2, 0);
   }
 
-  private static boolean provablyDistinct(PsiType type1, PsiType type2, int level) {
+  protected static boolean provablyDistinct(PsiType type1, PsiType type2, int level) {
     if (type1 instanceof PsiClassType && ((PsiClassType)type1).resolve() instanceof PsiTypeParameter) return false;
     if (type2 instanceof PsiClassType && ((PsiClassType)type2).resolve() instanceof PsiTypeParameter) return false;
     if (type1 instanceof PsiWildcardType) {
@@ -43,9 +43,9 @@
         return provablyDistinct((PsiWildcardType)type1, (PsiWildcardType)type2);
       }
 
+      if (level > 1) return true;
       if (type2 instanceof PsiCapturedWildcardType) {
-        return ((PsiWildcardType)type1).isExtends() && level > 0 ||
-               provablyDistinct((PsiWildcardType)type1, ((PsiCapturedWildcardType)type2).getWildcard());
+        return provablyDistinct((PsiWildcardType)type1, ((PsiCapturedWildcardType)type2).getWildcard());
       }
 
       if (type2 instanceof PsiClassType) {
diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java
index 914a300..c616597 100644
--- a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java
+++ b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java
@@ -657,6 +657,11 @@
           }
           buffer.append("&nbsp;");
         }
+      } else {
+        buffer.append("<font color=red>");
+        buffer.append(annotation.getText());
+        buffer.append("</font>");
+        buffer.append("&nbsp;");
       }
     }
   }
diff --git a/java/java-psi-impl/src/com/intellij/externalSystem/JavaProjectDataService.java b/java/java-psi-impl/src/com/intellij/externalSystem/JavaProjectDataService.java
index 05132a8..cc9ff3b 100644
--- a/java/java-psi-impl/src/com/intellij/externalSystem/JavaProjectDataService.java
+++ b/java/java-psi-impl/src/com/intellij/externalSystem/JavaProjectDataService.java
@@ -48,11 +48,14 @@
 
   @Override
   public void importData(@NotNull Collection<DataNode<JavaProjectData>> toImport, @NotNull Project project, boolean synchronous) {
+    if (!ExternalSystemApiUtil.isNewProjectConstruction()) {
+      return;
+    }
     if (toImport.size() != 1) {
       throw new IllegalArgumentException(String.format("Expected to get a single project but got %d: %s", toImport.size(), toImport));
     }
     JavaProjectData projectData = toImport.iterator().next().getData();
-    
+
     // JDK.
     JavaSdkVersion version = projectData.getJdkVersion();
     JavaSdk javaSdk = JavaSdk.getInstance();
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java
index 0e1e343..d0f0548 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/PsiImplUtil.java
@@ -491,6 +491,10 @@
       toplevel = (PsiExpression)toplevel.getParent();
     }
 
+    if (toplevel instanceof PsiArrayAccessExpression && !PsiUtil.isAccessedForWriting(toplevel)) {
+      return PsiUtil.captureToplevelWildcards(type, expression);
+    }
+
     final PsiType normalized = doNormalizeWildcardByPosition(type, expression, toplevel);
     LOG.assertTrue(normalized.isValid(), type);
     if (normalized instanceof PsiClassType && !PsiUtil.isAccessedForWriting(toplevel)) {
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsClassImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsClassImpl.java
index f17fb5b..8f0e58d 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsClassImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsClassImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -406,9 +406,17 @@
     setMirror(getExtendsList(), mirror.getExtendsList());
     setMirror(getImplementsList(), mirror.getImplementsList());
 
-    setMirrors(getOwnFields(), mirror.getFields());
-    setMirrors(getOwnMethods(), mirror.getMethods());
-    setMirrors(getOwnInnerClasses(), mirror.getInnerClasses());
+    if (mirror instanceof PsiExtensibleClass) {
+      PsiExtensibleClass extMirror = (PsiExtensibleClass)mirror;
+      setMirrors(getOwnFields(), extMirror.getOwnFields());
+      setMirrors(getOwnMethods(), extMirror.getOwnMethods());
+      setMirrors(getOwnInnerClasses(), extMirror.getOwnInnerClasses());
+    }
+    else {
+      setMirrors(getOwnFields(), mirror.getFields());
+      setMirrors(getOwnMethods(), mirror.getMethods());
+      setMirrors(getOwnInnerClasses(), mirror.getInnerClasses());
+    }
   }
 
   @Override
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsElementImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsElementImpl.java
index c435f97..060ed38 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsElementImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsElementImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -310,20 +310,19 @@
   }
 
   protected static <T extends  PsiElement> void setMirrors(@NotNull T[] stubs, @NotNull T[] mirrors) throws InvalidMirrorException {
-    if (stubs.length != mirrors.length) {
-      throw new InvalidMirrorException(stubs, mirrors);
-    }
-    for (int i = 0; i < stubs.length; i++) {
-      setMirror(stubs[i], mirrors[i]);
-    }
+    setMirrors(Arrays.asList(stubs), Arrays.asList(mirrors));
   }
 
   protected static <T extends  PsiElement> void setMirrors(@NotNull List<T> stubs, @NotNull T[] mirrors) throws InvalidMirrorException {
-    if (stubs.size() != mirrors.length) {
+    setMirrors(stubs, Arrays.asList(mirrors));
+  }
+
+  protected static <T extends  PsiElement> void setMirrors(@NotNull List<T> stubs, @NotNull List<T> mirrors) throws InvalidMirrorException {
+    if (stubs.size() != mirrors.size()) {
       throw new InvalidMirrorException(stubs, mirrors);
     }
     for (int i = 0; i < stubs.size(); i++) {
-      setMirror(stubs.get(i), mirrors[i]);
+      setMirror(stubs.get(i), mirrors.get(i));
     }
   }
 
@@ -340,8 +339,8 @@
       this("stub:" + Arrays.toString(stubElements) + "; mirror:" + Arrays.toString(mirrorElements));
     }
 
-    public InvalidMirrorException(@NotNull List<? extends PsiElement> stubElements, @NotNull PsiElement[] mirrorElements) {
-      this("stub:" + stubElements + "; mirror:" + Arrays.toString(mirrorElements));
+    public InvalidMirrorException(@NotNull List<? extends PsiElement> stubElements, @NotNull List<? extends PsiElement> mirrorElements) {
+      this("stub:" + stubElements + "; mirror:" + mirrorElements);
     }
   }
 }
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/StubBuildingVisitor.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/StubBuildingVisitor.java
index 95daf33..8e79478 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/StubBuildingVisitor.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/StubBuildingVisitor.java
@@ -340,7 +340,7 @@
 
     byte flags = PsiFieldStubImpl.packFlags((access & Opcodes.ACC_ENUM) != 0, (access & Opcodes.ACC_DEPRECATED) != 0, false);
     TypeInfo type = fieldType(desc, signature);
-    String initializer = constToString(value, "boolean".equals(type.text.getString()));
+    String initializer = constToString(value, "boolean".equals(type.text.getString()), false);
     PsiFieldStub stub = new PsiFieldStubImpl(myResult, name, type, initializer, flags);
     PsiModifierListStub modList = new PsiModifierListStubImpl(stub, packFieldFlags(access));
     return new AnnotationCollectingVisitor(modList);
@@ -371,7 +371,8 @@
     return new TypeInfo(getTypeText(type), (byte)dim, false, Collections.<PsiAnnotationStub>emptyList()); //todo read annos from .class file
   }
 
-  private static final String[] parameterNames = {"p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9",};
+  private static final String[] parameterNames = {"p1", "p2", "p3", "p4", "p5", "p6", "p7", "p8", "p9"};
+
   @Override
   @Nullable
   public MethodVisitor visitMethod(final int access,
@@ -536,7 +537,7 @@
     @Override
     public void visit(final String name, final Object value) {
       valuePairPrefix(name);
-      myBuilder.append(constToString(value, false));
+      myBuilder.append(constToString(value, false, true));
     }
 
     @Override
@@ -696,7 +697,7 @@
   }
 
   @Nullable
-  private static String constToString(@Nullable Object value, boolean isBoolean) {
+  private static String constToString(@Nullable Object value, boolean isBoolean, boolean anno) {
     if (value == null) return null;
 
     if (value instanceof String) return "\"" + StringUtil.escapeStringCharacters((String)value) + "\"";
@@ -747,6 +748,10 @@
       return buffer.toString();
     }
 
+    if (anno && value instanceof Type) {
+      return getTypeText((Type)value) + ".class";
+    }
+
     return null;
   }
 
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiArrayAccessExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiArrayAccessExpressionImpl.java
index cead445..f9b2a93 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiArrayAccessExpressionImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiArrayAccessExpressionImpl.java
@@ -46,7 +46,7 @@
   public PsiType getType() {
     PsiType arrayType = getArrayExpression().getType();
     if (!(arrayType instanceof PsiArrayType)) return null;
-    return GenericsUtil.getVariableTypeByExpressionType(((PsiArrayType)arrayType).getComponentType());
+    return GenericsUtil.getVariableTypeByExpressionType(((PsiArrayType)arrayType).getComponentType(), false);
   }
 
   @Override
diff --git a/java/java-psi-impl/src/messages/JavaErrorMessages.properties b/java/java-psi-impl/src/messages/JavaErrorMessages.properties
index a20e3c2..e108e58 100644
--- a/java/java-psi-impl/src/messages/JavaErrorMessages.properties
+++ b/java/java-psi-impl/src/messages/JavaErrorMessages.properties
@@ -217,6 +217,7 @@
 exception.never.thrown.try=Exception ''{0}'' is never thrown in the corresponding try block
 exception.already.caught.warn=Unreachable section: {1, choice, 0#exception|2#exceptions} ''{0}'' {1, choice, 0#has|2#have} already been caught
 not.a.statement=Not a statement
+invalid.statement=Invalid statement
 incompatible.types=Incompatible types. Found: ''{1}'', required: ''{0}''
 valid.switch.selector.types=byte, char, short or int
 dot.expected.after.super.or.this='.' expected
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IDEA60875.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IDEA60875.java
new file mode 100644
index 0000000..8c2d86e
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IDEA60875.java
@@ -0,0 +1,16 @@
+class A {
+
+    class B {
+
+        private void foo() {}
+    }
+    class C extends B {
+
+        class D {
+
+            void bar() {
+                C.this.<error descr="'foo()' has private access in 'A.B'">foo</error>();
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IDEA67829.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IDEA67829.java
new file mode 100644
index 0000000..ba40610
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IDEA67829.java
@@ -0,0 +1,4 @@
+class A{
+    void foo(String s){}
+    static void foo(Object s){<error descr="Non-static method 'foo(java.lang.String)' cannot be referenced from a static context">foo</error>("");}
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IDEA71645.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IDEA71645.java
new file mode 100644
index 0000000..6c23dcd
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IDEA71645.java
@@ -0,0 +1,20 @@
+class Component {
+    void addChild( Component b ) {
+    }
+}
+
+class Panel extends Component {
+    public Panel( Component pNode ) {
+    }
+
+    Panel() {
+    }
+}
+
+class VerticalPanel extends Panel {
+    public VerticalPanel() {
+        super( new Component() {{
+            addChild( new Panel() );
+        }} );
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IgnoreImplicitThisReferenceBeforeSuperSinceJdk7.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IgnoreImplicitThisReferenceBeforeSuperSinceJdk7.java
new file mode 100644
index 0000000..2dc8d2c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IgnoreImplicitThisReferenceBeforeSuperSinceJdk7.java
@@ -0,0 +1,4 @@
+class Test {
+    class Test1 extends Test {}
+    class Test2 extends Test1 {}
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IllegalVoidType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IllegalVoidType.java
index 206be90..6852b0f 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IllegalVoidType.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/IllegalVoidType.java
@@ -1,18 +1,18 @@
-class s {
-  void f() {
-    // illegal type
+class C {
+  <error descr="Illegal type: 'void'">void</error>[] m1() { }
+  <error descr="Illegal type: 'void'">void</error> m2()[] { }
+  void m3(<error descr="Illegal type: 'void'">void</error> p) {}
+
+  {
     <error descr="Illegal type: 'void'">void</error>[] va;
     <error descr="Illegal type: 'void'">void</error> vv;
-    class loc {
-      void f(<error descr="Illegal type: 'void'">void</error> i) {}
-    }
-    Object o = new <error descr="Illegal type: 'void'">void</error>[1];
+    Object oo = new <error descr="Illegal type: 'void'">void</error>[1];
 
     // this is the only valid void usage
     Class voidClass = void.class;
   }
 
-  {
+  void f() {
     <error descr="Incompatible types. Found: 'void', required: 'java.lang.Object'">Object o = f();</error>
   }
 }
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Loop.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Loop.java
index 600bae3..5dd2c92 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Loop.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/Loop.java
@@ -1,54 +1,54 @@
-// continue outside of.../loop label
-public class a {
+class a {
+  class ff { }
 
   void f() {
     <error descr="Continue outside of loop">continue;</error>
+
     while (true) {
       continue;
     }
     do { continue; } while (true);
+
     switch (1) {
       case 1: <error descr="Continue outside of loop">continue;</error>
     }
+
     for (;;) {
       continue;
     }
 
     for (;;) {
       new ff() {
-        void f() { 
+        void f() {
           <error descr="Continue outside of loop">continue;</error>
         }
       };
       continue;
     }
 
-
     while (true) {
       class s {
-       {
-         <error descr="Continue outside of loop">continue;</error>
-       }
+        {
+          <error descr="Continue outside of loop">continue;</error>
+        }
       }
       continue;
     }
 
     do {
       class s {
-       {
-         <error descr="Continue outside of loop">continue;</error>
-       }
+        {
+          <error descr="Continue outside of loop">continue;</error>
+        }
       }
       continue;
     } while (true);
 
-
-
     a:
     if (2==4) {
-    for (;;) {
-      <error descr="Not a loop label: 'a'">continue a;</error>
-    }
+      for (;;) {
+        <error descr="Not a loop label: 'a'">continue a;</error>
+      }
     }
 
     a:
@@ -56,12 +56,10 @@
     for (;;) {
       <error descr="Not a loop label: 'a'">continue a;</error>
     }
-    
 
-
+    int i = 0;
+    for (<error descr="Not a statement">i==0?7:8;</error> ; ) ;
+    for (<error descr="Invalid statement">if (i<0) i++;</error> ; ) ;
+    for (new ff(), new ff(); ; ) ;
   }
 }
-
-class ff {
-
-}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/NoEnclosingInstanceWhenStaticNestedInheritsFromContainingClass.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/NoEnclosingInstanceWhenStaticNestedInheritsFromContainingClass.java
new file mode 100644
index 0000000..3c38d3c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting/NoEnclosingInstanceWhenStaticNestedInheritsFromContainingClass.java
@@ -0,0 +1,8 @@
+class Test {
+    class Test1 extends Test {}
+    static class Test2 extends <error descr="No enclosing instance of type 'Test' is in scope">Test1</error> {}
+
+
+    static class Test11 extends Test {}
+    static class Test21 extends Test11 {}
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/IDEA62056.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/IDEA62056.java
new file mode 100644
index 0000000..13d4aa9
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/IDEA62056.java
@@ -0,0 +1,10 @@
+class Test {
+    public static void rotate(S<?> s) {
+        Object[] o = new Object[0];
+        s.call(o);
+    }
+}
+
+interface S<T>{
+    void call(T... elements);
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/IDEA63731.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/IDEA63731.java
new file mode 100644
index 0000000..a204a57
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/IDEA63731.java
@@ -0,0 +1,6 @@
+class Test {
+  {
+    Integer i = 9;
+    byte b = (byte) (i >> 2);
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/IDEA70890.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/IDEA70890.java
new file mode 100644
index 0000000..c5283294
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/IDEA70890.java
@@ -0,0 +1,10 @@
+import java.util.*;
+
+public class Test {
+        static <E extends Exception, T> void foo(List<T> l, Class<E> ec) throws E {
+        }
+
+        public static void main(String[] s) {
+                foo(new ArrayList(), RuntimeException.class); //IDEA says we have an unhandled exception here
+        }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67841/pck/AmbiguousMethodCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67841/pck/AmbiguousMethodCall.java
new file mode 100644
index 0000000..c79d7c8
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67841/pck/AmbiguousMethodCall.java
@@ -0,0 +1,21 @@
+package pck;
+
+import java.util.Collection;
+import java.util.List;
+
+import static pck.D.foo;
+import static pck.C.foo;
+
+public class C {
+    static <T extends Collection<S>, S> void foo(T x) { }
+}
+
+class D {
+    static <T extends List<S>, S> String foo(T x) { return null; }
+}
+
+class B{
+    public static void bar(){
+        foo(null).toLowerCase();
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/DisableCastingToNestedWildcards.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/DisableCastingToNestedWildcards.java
new file mode 100644
index 0000000..9c076ab
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/DisableCastingToNestedWildcards.java
@@ -0,0 +1,32 @@
+import java.util.List;
+
+public class Test {
+
+    interface P {
+
+    }
+
+    public abstract class AP implements P {
+
+    }
+
+    public class AP1 extends AP {
+
+    }
+
+    public class AP2 extends AP {
+
+    }
+
+    private static final List<Class<AP1>> AP_LIST = listOf(AP1.class);
+
+
+    private static <T> List<T> listOf(T... ts) {
+        return null;
+    }
+
+    public static void test() {
+        List<Class<? extends AP>> apList1 = <error descr="Inconvertible types; cannot cast 'java.util.List<java.lang.Class<Test.AP1>>' to 'java.util.List<java.lang.Class<? extends Test.AP>>'">(List<Class<? extends AP>>) AP_LIST</error>;
+        List<Class<? super AP1>> apList2 = <error descr="Inconvertible types; cannot cast 'java.util.List<java.lang.Class<Test.AP1>>' to 'java.util.List<java.lang.Class<? super Test.AP1>>'">(List<Class<? super AP1>>) AP_LIST</error>;
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/Enum56239.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/Enum56239.java
new file mode 100644
index 0000000..9f7d0b8
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/Enum56239.java
@@ -0,0 +1,34 @@
+enum IDEA56239 {
+  A, B() {
+    {
+      System.out.println(<error descr="It is illegal to access static member 'A' from enum constructor or instance initializer">A</error>);
+      System.out.println(<error descr="It is illegal to access static member 'FOO' from enum constructor or instance initializer">FOO</error>);
+      System.out.println(FOO1);
+      System.out.println(<error descr="It is illegal to access static member 'C' from enum constructor or instance initializer">C</error>);
+    }
+  }, C(<error descr="Illegal forward reference">D</error>), D;
+
+  public static String FOO = "";
+  public static final String FOO1 = "";
+
+  IDEA56239() {
+  }
+
+  IDEA56239(IDEA56239 t) {
+    System.out.println(<error descr="It is illegal to access static member 'A' from enum constructor or instance initializer">A</error>);
+    System.out.println(<error descr="It is illegal to access static member 'FOO' from enum constructor or instance initializer">FOO</error>);
+    System.out.println(FOO1);
+  }
+
+  {
+    System.out.println(<error descr="It is illegal to access static member 'A' from enum constructor or instance initializer">A</error>);
+    System.out.println(<error descr="It is illegal to access static member 'FOO' from enum constructor or instance initializer">FOO</error>);
+    System.out.println(FOO1);
+  }
+
+  void foo() {
+    System.out.println(A);
+    System.out.println(FOO);
+    System.out.println(FOO1);
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA18425.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA18425.java
new file mode 100644
index 0000000..4308a92
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA18425.java
@@ -0,0 +1,15 @@
+public abstract class BiFunction<A,B> {
+    public abstract B apply(A a);
+    public abstract A unapply(B b);
+    public BiFunction<B,A> flip() {
+        return new BiFunction<B, A>() {
+            public A apply(B b) {
+                return BiFunction.this.unapply(b);
+            }
+
+            public B unapply(A a) {
+                return BiFunction.this.apply(a);
+            }
+        };
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA20244.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA20244.java
new file mode 100644
index 0000000..ee5235a
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA20244.java
@@ -0,0 +1,23 @@
+import java.util.Collection;
+class Test {
+    public static final UnaryFunction<Object, Object, RuntimeException> unaryFunction = new UnaryFunction<Object, Object, RuntimeException>() {
+        public Object execute(Object o) throws RuntimeException {
+            return null;
+        }
+    };
+
+    public static <A, B, X extends Throwable> void someMethod() {
+        transformCollection(null, unaryFunction, null);
+    }
+
+    public static <A, B, X extends Throwable> void transformCollection(Collection<? extends A> input, UnaryFunction<A, B, X> transform, Collection<? super B> output) throws X {
+        for (A a : input) {
+            B b = transform.execute(a);
+            output.add(b);
+        }
+    }
+}
+
+interface UnaryFunction<A, B, X extends Throwable> {
+    public B execute(A a) throws X;
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA20573.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA20573.java
new file mode 100644
index 0000000..22bd7a3
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA20573.java
@@ -0,0 +1,26 @@
+public class GoodCodeIsRed {
+
+    public void test() {
+        FileIF file = new FileImpl();
+        file.getInputStream();
+    }
+}
+
+class FileImpl implements FileIF {
+
+    public void getInputStream() {
+    }
+
+}
+
+interface FileIF extends BasicFileIF, DataSource {
+}
+
+interface BasicFileIF {
+    void getInputStream();
+}
+
+
+interface DataSource {
+    void getInputStream() throws java.io.IOException;
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA21597.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA21597.java
new file mode 100644
index 0000000..b26f491
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA21597.java
@@ -0,0 +1,7 @@
+interface Foo<A> {}
+interface Bar extends Foo<Boolean> {}
+class FooFactory {
+    public <A> Foo<A> getFoo() {
+        return (Foo<A>) new Bar() {};
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA21602.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA21602.java
new file mode 100644
index 0000000..c02ceaa
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA21602.java
@@ -0,0 +1,17 @@
+import java.util.Collection;
+import java.util.Collections;
+
+public class IDEABug {
+
+  static class ClassA {
+    static <T> void sayHello(Collection<? extends T> msg) {}
+  }
+
+  static class ClassB extends ClassA {
+    static <T extends String> void sayHello(Collection<? extends T> msg) {}
+  }
+
+  public static void main(String[] args) {
+    ClassB.sayHello(Collections.<String>emptyList());
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA21602_7.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA21602_7.java
new file mode 100644
index 0000000..0496f3a
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA21602_7.java
@@ -0,0 +1,17 @@
+import java.util.Collection;
+import java.util.Collections;
+
+public class IDEABug {
+
+  static class ClassA {
+    static <T> void sayHello(Collection<? extends T> msg) {}
+  }
+
+  static class ClassB extends ClassA {
+    <error descr="'sayHello(Collection<? extends T>)' in 'IDEABug.ClassB' clashes with 'sayHello(Collection<? extends T>)' in 'IDEABug.ClassA'; both methods have same erasure, yet neither hides the other">static <T extends String> void sayHello(Collection<? extends T> msg)</error> {}
+  }
+
+  public static void main(String[] args) {
+    ClassB.sayHello(Collections.<String>emptyList());
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA22005.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA22005.java
new file mode 100644
index 0000000..78aad3c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA22005.java
@@ -0,0 +1,13 @@
+class Test {
+    interface Foo<T> {
+        void boo(T t);
+    }
+
+    private static void f(Foo<?>... fs) {
+         fs[0].boo<error descr="'boo(capture<?>)' in 'Test.Foo' cannot be applied to '(java.lang.String)'">("hey!")</error>;
+    }
+
+    private static void f1(Foo<? extends String>... fs) {
+         fs[0].boo<error descr="'boo(capture<? extends java.lang.String>)' in 'Test.Foo' cannot be applied to '(java.lang.String)'">("hey!")</error>;
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA22079.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA22079.java
new file mode 100644
index 0000000..f3b25c9
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA22079.java
@@ -0,0 +1,18 @@
+import java.util.List;
+
+public class SubClass extends BaseClass<String> {
+    public static void main(String[] args) {
+        new SubClass().method(null);
+    }
+
+    @Override
+    public void method(List list) {}
+}
+
+class BaseClass<E> implements EntityListListener<E> {
+    public void method(List list) {}
+}
+
+interface EntityListListener<E> {
+   public void method(List<E> list);
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA27080.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA27080.java
new file mode 100644
index 0000000..7e9168d
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA27080.java
@@ -0,0 +1,9 @@
+abstract class TypeToken<T> {
+    private <T> TypeToken<T> tt(Class<T> t) { return null; }
+    private <T> void checkedTestInexactSupertype(TypeToken<T> expectedSuperclass, TypeToken<? extends T> type) {}
+    TypeToken<? super Integer> ft = null;
+
+    {
+        checkedTestInexactSupertype(ft, tt(Integer.class));
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA27185.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA27185.java
new file mode 100644
index 0000000..3afbc3c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA27185.java
@@ -0,0 +1,13 @@
+import java.io.Serializable;
+interface A<T extends Serializable>
+{
+    <S extends T> S foo(S s);
+}
+class B implements A<Number>
+{
+    @Override
+    public <S extends Number> S foo(S s)
+    {
+        return s;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57265.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57265.java
new file mode 100644
index 0000000..9a74ac7
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57265.java
@@ -0,0 +1,5 @@
+class A<T> {
+  class B<S> {
+    <error descr="Improper formed type; some type parameters are missing">A<T>.B</error> x;
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57271.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57271.java
new file mode 100644
index 0000000..3dc042f
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57271.java
@@ -0,0 +1,9 @@
+abstract class A<S> {
+    abstract <T> T foo(T x, T y);
+
+    {
+        A<? extends A<? extends Throwable>> a = null;
+        A<? extends A<?>> b = null;
+        foo(a, b);
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57272.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57272.java
new file mode 100644
index 0000000..c91867c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57272.java
@@ -0,0 +1,8 @@
+abstract class A<S> {
+    abstract <T extends A<? extends Throwable>> T foo(T y);
+
+    {
+        A<?> a = null;
+        <error descr="Inferred type 'A<capture<?>>' for type parameter 'T' is not within its bound; should extend 'A<? extends java.lang.Throwable>'">foo(a)</error>;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57285.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57285.java
new file mode 100644
index 0000000..5498f79
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57285.java
@@ -0,0 +1,12 @@
+package pck;
+
+abstract class A<S> {
+    S y;
+    void bar(A<? extends int[]> x){
+        Object obj = <error descr="Array type expected; found: 'capture<? extends int[]>'">x.y</error>[0];
+    }
+
+    void baz(A<? super int[]> x){
+        Object obj = <error descr="Array type expected; found: 'capture<? super int[]>'">x.y</error>[0];
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57413.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57413.java
new file mode 100644
index 0000000..99b34aa
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57413.java
@@ -0,0 +1,7 @@
+class A<T> {
+    <T extends A<T>> void foo(T x){}
+
+    void bar(A<?> x){
+        <error descr="Inferred type 'A<capture<?>>' for type parameter 'T' is not within its bound; should extend 'A<A<capture<?>>>'">foo(x)</error>;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57482.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57482.java
new file mode 100644
index 0000000..8b1471b
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57482.java
@@ -0,0 +1,9 @@
+class C<T>{
+    static class D{
+        class E{
+            <error descr="'C.this' cannot be referenced from a static context">T</error> x;
+        }
+    }
+}
+
+class T{}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57534.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57534.java
new file mode 100644
index 0000000..ea3e242
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA57534.java
@@ -0,0 +1,15 @@
+abstract class C{
+    abstract <T extends Cloneable> void foo(T x);
+    abstract <T extends Object & Cloneable> void foo(T x);
+    void bar(Cloneable x){
+        foo<error descr="Ambiguous method call: both 'C.foo(Cloneable)' and 'C.foo(Cloneable)' match">(x)</error>;
+    }
+}
+
+abstract class D {
+    abstract <T extends Iterable<? extends Exception>> void foo(T x);
+    abstract <T extends Object & Iterable<? super Exception>> void foo(T x);
+    void bar(Iterable<Exception> x){
+        foo<error descr="Ambiguous method call: both 'D.foo(Iterable<Exception>)' and 'D.foo(Iterable<Exception>)' match">(x)</error>;
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA65066.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA65066.java
new file mode 100644
index 0000000..3078f60
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA65066.java
@@ -0,0 +1,19 @@
+import java.util.List;
+
+class Generics {
+    public static void main( String[] args ) {
+        Outer<? extends List<? extends Nested<?>>, ?> var = OuterImpl.create(); //marked red
+    }
+
+    private static interface Outer<I, O> {
+    }
+
+    private static class OuterImpl<T> implements Outer<T, T> {
+        public static <T> OuterImpl<T> create() {
+            return new OuterImpl<T>();
+        }
+    }
+
+    private static class Nested<T> {
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67571.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67571.java
new file mode 100644
index 0000000..14d2d29
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67571.java
@@ -0,0 +1,17 @@
+interface A
+{
+    abstract <T> void foo();
+}
+
+interface B
+{
+    abstract <T,S> void foo();
+}
+
+class C<<error descr="'foo()' in 'B' clashes with 'foo()' in 'A'; both methods have same erasure, yet neither overrides the other"></error>T extends A & B>
+{
+    void bar(T x)
+    {
+        x.foo<error descr="Ambiguous method call: both 'A.foo()' and 'B.foo()' match">()</error>;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67577.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67577.java
new file mode 100644
index 0000000..3c34161
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67577.java
@@ -0,0 +1,7 @@
+class X<T>{}
+
+class A<T,S extends X<T>>  {}
+
+class C {
+    void foo(A<?, <error descr="Type parameter 'X' is not within its bound; should extend 'X<?>'">X</error>> a){  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67998.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67998.java
new file mode 100644
index 0000000..3fede9c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67998.java
@@ -0,0 +1,22 @@
+class TestClass {
+    public final class TestMapper<X>  {
+
+        public <U, T extends Mapping<X, U>> T mapType() {
+            SimpleMapping<X, U> mapping = new SimpleMapping<X, U>();
+            return (T) mapping;   //This is reports "Inconvertible types; cannot cast TestClass.SimpleMapping<X,U> to 'T'"
+        }
+    }
+    private final class SimpleMapping<X, U> implements Mapping<X, U> {}
+    public interface Mapping<F, U> {}
+}
+class TestClass1 {
+    public final class TestMapper<X>  {
+
+        public <U, T extends Mapping<X, U>> T mapType() {
+            Mapping<X, U> mapping = new SimpleMapping<X, U>(); //Changed type to interface
+            return (T) mapping;
+        }
+    }
+    private final class SimpleMapping<X, U> implements Mapping<X, U> {}
+    public interface Mapping<F, U> {}
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/WildcardCastConversion.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/WildcardCastConversion.java
index ac8d53b..f610bac 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/WildcardCastConversion.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/WildcardCastConversion.java
@@ -529,4 +529,20 @@
 }
 
 class FixedChildDescriptionImpl extends AbstractDomChildDescriptionImpl {
-}
\ No newline at end of file
+}
+
+class CaptureSymmetry {
+  interface Collection<A> {}
+  interface List<A> extends Collection<A>{}
+  class ArrayList<A> implements List<A> {}
+
+  public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c) {
+    return null;
+  }
+
+  public <B extends List<?>> Collection<? extends B> getBreakpoints (List<B> b) {
+    Collection<? extends ArrayList<?>> breakpoints = null;
+    Collection<? extends B> regular = breakpoints != null ? unmodifiableCollection((Collection<? extends B>)breakpoints) : b;
+    return null;
+  }
+}
diff --git a/java/java-tests/testData/psi/cls/mirror/Booleans.txt b/java/java-tests/testData/psi/cls/mirror/Booleans.txt
index 24d533f..8def7d9 100644
--- a/java/java-tests/testData/psi/cls/mirror/Booleans.txt
+++ b/java/java-tests/testData/psi/cls/mirror/Booleans.txt
@@ -5,11 +5,14 @@
 package pkg;
 
 class Booleans {
-    public static final boolean RELEASE = true;
-    public static final boolean DEBUG = false;
-    public static final boolean PROFILE = false;
-    public static final boolean LOGV = false;
-    public static final boolean LOGD = true;
+    public static final boolean TRUE = true;
+    public static final boolean FALSE = false;
 
     Booleans() { /* compiled code */ }
+
+    @pkg.BooleanAnno(true)
+    public static boolean TRUE() { /* compiled code */ }
+
+    @pkg.BooleanAnno(false)
+    public static boolean FALSE() { /* compiled code */ }
 }
\ No newline at end of file
diff --git a/java/java-tests/testData/psi/cls/mirror/ClassRefs.txt b/java/java-tests/testData/psi/cls/mirror/ClassRefs.txt
new file mode 100644
index 0000000..ce11e0e
--- /dev/null
+++ b/java/java-tests/testData/psi/cls/mirror/ClassRefs.txt
@@ -0,0 +1,12 @@
+
+  // IntelliJ API Decompiler stub source generated from a class file
+  // Implementation of methods is not available
+
+package pkg;
+
+class ClassRefs {
+    @pkg.AnnWithTypeLocal(type = java.lang.String.class)
+    public static final java.lang.Class<?> cls;
+
+    ClassRefs() { /* compiled code */ }
+}
diff --git a/java/java-tests/testData/psi/cls/mirror/pkg/AnnWithTypeLocal.class b/java/java-tests/testData/psi/cls/mirror/pkg/AnnWithTypeLocal.class
new file mode 100644
index 0000000..9252a8e
--- /dev/null
+++ b/java/java-tests/testData/psi/cls/mirror/pkg/AnnWithTypeLocal.class
Binary files differ
diff --git a/java/java-tests/testData/psi/cls/mirror/pkg/BooleanAnno.class b/java/java-tests/testData/psi/cls/mirror/pkg/BooleanAnno.class
new file mode 100644
index 0000000..64ba86f
--- /dev/null
+++ b/java/java-tests/testData/psi/cls/mirror/pkg/BooleanAnno.class
Binary files differ
diff --git a/java/java-tests/testData/psi/cls/mirror/pkg/Booleans.class b/java/java-tests/testData/psi/cls/mirror/pkg/Booleans.class
index d2a2fc0..1a71ca0 100644
--- a/java/java-tests/testData/psi/cls/mirror/pkg/Booleans.class
+++ b/java/java-tests/testData/psi/cls/mirror/pkg/Booleans.class
Binary files differ
diff --git a/java/java-tests/testData/psi/cls/mirror/pkg/ClassRefs.class b/java/java-tests/testData/psi/cls/mirror/pkg/ClassRefs.class
new file mode 100644
index 0000000..ca03e1b
--- /dev/null
+++ b/java/java-tests/testData/psi/cls/mirror/pkg/ClassRefs.class
Binary files differ
diff --git a/java/java-tests/testData/psi/cls/mirror/src/pkg/Booleans.java b/java/java-tests/testData/psi/cls/mirror/src/pkg/Booleans.java
index dac1d2c..495e1ac 100644
--- a/java/java-tests/testData/psi/cls/mirror/src/pkg/Booleans.java
+++ b/java/java-tests/testData/psi/cls/mirror/src/pkg/Booleans.java
@@ -1,9 +1,13 @@
 package pkg;
 
 class Booleans  {
-  public static final boolean RELEASE = true;
-  public static final boolean DEBUG = false;
-  public static final boolean PROFILE = false;
-  public static final boolean LOGV = false;
-  public static final boolean LOGD = true;
+  public static final boolean TRUE = true;
+  public static final boolean FALSE = false;
+
+  @BooleanAnno(true) public static boolean TRUE() { return TRUE; }
+  @BooleanAnno(false) public static boolean FALSE() { return FALSE; }
 }
+
+@interface BooleanAnno {
+  boolean value();
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/psi/cls/mirror/src/pkg/ClassRefs.java b/java/java-tests/testData/psi/cls/mirror/src/pkg/ClassRefs.java
new file mode 100644
index 0000000..af3784c
--- /dev/null
+++ b/java/java-tests/testData/psi/cls/mirror/src/pkg/ClassRefs.java
@@ -0,0 +1,10 @@
+package pkg;
+
+class ClassRefs {
+  @AnnWithTypeLocal(type = String.class)
+  public static final Class<?> cls = String.class;  // class refs are set from class initaializer
+}
+
+@interface AnnWithTypeLocal {
+  Class type();
+}
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy
index 507f3d5..11cfb31 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy
@@ -1253,6 +1253,8 @@
   protected void tearDown() {
     CodeInsightSettings.instance.SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS = false
     CodeInsightSettings.instance.COMPLETION_CASE_SENSITIVE = CodeInsightSettings.FIRST_LETTER
+    UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = false
+
     super.tearDown()
   }
 
@@ -1384,4 +1386,23 @@
 
   }
 
+  public void testPreselectMostRelevantInTheMiddleAlpha() {
+    UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = true;
+    CodeInsightSettings.instance.SELECT_AUTOPOPUP_SUGGESTIONS_BY_CHARS = false
+
+    myFixture.configureByText 'a.java', '''
+class Foo {
+  void setText() {}
+  void setHorizontalText() {}
+  void foo() {
+    <caret>
+  }
+
+}
+'''
+    type 'sette'
+    myFixture.assertPreferredCompletionItems 1, 'setHorizontalText', 'setText'
+  }
+
+
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/AdvHighlightingJdk7Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/AdvHighlightingJdk7Test.java
index 25bb907..352048d 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/AdvHighlightingJdk7Test.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/AdvHighlightingJdk7Test.java
@@ -152,6 +152,10 @@
     doTestAmbiguous();
   }
 
+  public void testAmbiguousIDEA67841() throws Exception {
+    doTestAmbiguous();
+  }
+
   public void testAmbiguousIDEA57535() throws Exception {
     doTestAmbiguous();
   }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
index 03ff60b..37163f2 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
@@ -73,7 +73,10 @@
   public void testAutoboxingMethods() { doTest5(false); }
   public void testAutoboxingConstructors() { doTest5(false); }
   public void testEnumWithAbstractMethods() { doTest5(false); }
-  public void testEnum() { doTest5(false); }
+  public void testEnum() {
+    doTest(LanguageLevel.JDK_1_5, JavaSdkVersion.JDK_1_5, false);
+  }
+  public void testEnum56239() { doTest(LanguageLevel.JDK_1_6, JavaSdkVersion.JDK_1_6, false); }
   public void testSameErasure() { doTest5(false); }
   public void testMethods() { doTest5(false); }
   public void testFields() { doTest5(false); }
@@ -211,12 +214,39 @@
   public void testIDEA57446(){ doTest5(false); }
   public void testIDEA67677(){ doTest5(false); }
   public void testIDEA67798(){ doTest5(false); }
+  public void testIDEA57534(){ doTest5(false); }
+  public void testIDEA57482(){ doTest5(false); }
+  public void testIDEA67577(){ doTest5(false); }
+  public void testIDEA57413(){ doTest5(false); }
+  public void testIDEA57265(){ doTest5(false); }
+  public void testIDEA57271(){ doTest5(false); }
+  public void testIDEA57272(){ doTest5(false); }
+  public void testIDEA57285(){ doTest5(false); }
+  public void testIDEA65066(){ doTest5(false); }
+  public void testIDEA67998(){ doTest5(false); }
+  public void testIDEA18425(){ doTest5(false); }
+  public void testIDEA27080(){ doTest5(false); }
+  public void testIDEA22079(){ doTest5(false); }
+  public void testIDEA21602(){ doTest5(false); }
+  public void testIDEA21602_7(){ doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
+
+  public void testIDEA21597() throws Exception { doTest5(false);}
+  public void testIDEA20573() throws Exception { doTest5(false);}
+  public void testIDEA20244() throws Exception { doTest5(false);}
+  public void testIDEA22005() throws Exception { doTest5(false);}
+
+  public void testIDEA27185(){ doTest(LanguageLevel.JDK_1_6, JavaSdkVersion.JDK_1_6, false); }
+  public void testIDEA67571(){ doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
 
   public void testWildcardsOnRawTypes() { doTest5(false); }
   public void testDisableWithinBoundsCheckForSuperWildcards() {
     doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false);
   }
 
+  public void testDisableCastingToNestedWildcards() throws Exception {
+    doTest5(false);
+  }
+
   public void testBooleanInferenceFromIfCondition() throws Exception {
     doTest5(false);
   }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java
index 0bc2fd4..fb4fede 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingJdk7Test.java
@@ -176,4 +176,7 @@
   public void testInstanceMemberNotAccessibleInStaticContext() { doTest(false, false); }
   public void testRejectedTypeParamsForConstructor() { doTest(false, false); }
   public void testAnnotationArgs() throws Exception { doTest(false, false);}
+  public void testIDEA70890() { doTest(false, false); }
+  public void testIDEA63731() { doTest(false, false); }
+  public void testIDEA62056() { doTest(false, false); }
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java
index ed66f5f..b573214 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/LightAdvHighlightingTest.java
@@ -38,6 +38,9 @@
 import com.intellij.openapi.extensions.ExtensionPoint;
 import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.fileTypes.StdFileTypes;
+import com.intellij.openapi.projectRoots.JavaSdkVersion;
+import com.intellij.openapi.projectRoots.JavaVersionService;
+import com.intellij.openapi.projectRoots.JavaVersionServiceImpl;
 import com.intellij.openapi.roots.LanguageLevelProjectExtension;
 import com.intellij.openapi.vfs.VfsUtil;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -63,7 +66,7 @@
 
   private UnusedSymbolLocalInspection myUnusedSymbolLocalInspection;
 
-  private void doTest(boolean checkWarnings, boolean checkInfos) throws Exception {
+  private void doTest(boolean checkWarnings, boolean checkInfos) {
     doTest(BASE_PATH + "/" + getTestName(false) + ".java", checkWarnings, checkInfos);
   }
 
@@ -87,125 +90,134 @@
     };
   }
 
-  public void testCanHaveBody() throws Exception { doTest(false, false); }
-  public void testInheritFinal() throws Exception { doTest(false, false); }
-  public void testBreakOutside() throws Exception { doTest(false, false); }
-  public void testLoop() throws Exception { doTest(false, false); }
-  public void testIllegalModifiersCombination() throws Exception { doTest(false, false); }
-  public void testModifierAllowed() throws Exception { doTest(false, false); }
-  public void testAbstractMethods() throws Exception { doTest(false, false); }
-  public void testInstantiateAbstract() throws Exception { doTest(false, false); }
-  public void testDuplicateClassMethod() throws Exception { doTest(false, false); }
-  public void testStringLiterals() throws Exception { doTest(false, false); }
-  public void testStaticInInner() throws Exception { doTest(false, false); }
-  public void testInvalidExpressions() throws Exception { doTest(false, false); }
-  public void testIllegalVoidType() throws Exception { doTest(false, false); }
-  public void testIllegalType() throws Exception { doTest(false, false); }
-  public void testOperatorApplicability() throws Exception { doTest(false, false); }
-  public void testIncompatibleTypes() throws Exception { doTest(false, false); }
-  public void testCtrCallIsFirst() throws Exception { doTest(false, false); }
-  public void testAccessLevelClash() throws Exception { doTest(false, false); }
-  public void testCasts() throws Exception { doTest(false, false); }
-  public void testOverrideConflicts() throws Exception { doTest(false, false); }
-  public void testOverriddenMethodIsFinal() throws Exception { doTest(false, false); }
-  public void testMissingReturn() throws Exception { doTest(false, false); }
-  public void testUnreachable() throws Exception { doTest(false, false); }
-  public void testFinalFieldInit() throws Exception { doTest(false, false); }
-  public void testLocalVariableInitialization() throws Exception { doTest(false, false); }
-  public void testVarDoubleInitialization() throws Exception { doTest(false, false); }
-  public void testFieldDoubleInitialization() throws Exception { doTest(false, false); }
-  public void testAssignToFinal() throws Exception { doTest(false, false); }
-  public void testUnhandledExceptionsInSuperclass() throws Exception { doTest(false, false); }
-  public void testAssignmentCompatible () throws Exception { doTest(false, false); }
-  public void testMustBeBoolean() throws Exception { doTest(false, false); }
+  public void testCanHaveBody() { doTest(false, false); }
+  public void testInheritFinal() { doTest(false, false); }
+  public void testBreakOutside() { doTest(false, false); }
+  public void testLoop() { doTest(false, false); }
+  public void testIllegalModifiersCombination() { doTest(false, false); }
+  public void testModifierAllowed() { doTest(false, false); }
+  public void testAbstractMethods() { doTest(false, false); }
+  public void testInstantiateAbstract() { doTest(false, false); }
+  public void testDuplicateClassMethod() { doTest(false, false); }
+  public void testStringLiterals() { doTest(false, false); }
+  public void testStaticInInner() { doTest(false, false); }
+  public void testInvalidExpressions() { doTest(false, false); }
+  public void testIllegalVoidType() { doTest(false, false); }
+  public void testIllegalType() { doTest(false, false); }
+  public void testOperatorApplicability() { doTest(false, false); }
+  public void testIncompatibleTypes() { doTest(false, false); }
+  public void testCtrCallIsFirst() { doTest(false, false); }
+  public void testAccessLevelClash() { doTest(false, false); }
+  public void testCasts() { doTest(false, false); }
+  public void testOverrideConflicts() { doTest(false, false); }
+  public void testOverriddenMethodIsFinal() { doTest(false, false); }
+  public void testMissingReturn() { doTest(false, false); }
+  public void testUnreachable() { doTest(false, false); }
+  public void testFinalFieldInit() { doTest(false, false); }
+  public void testLocalVariableInitialization() { doTest(false, false); }
+  public void testVarDoubleInitialization() { doTest(false, false); }
+  public void testFieldDoubleInitialization() { doTest(false, false); }
+  public void testAssignToFinal() { doTest(false, false); }
+  public void testUnhandledExceptionsInSuperclass() { doTest(false, false); }
+  public void testAssignmentCompatible () { doTest(false, false); }
+  public void testMustBeBoolean() { doTest(false, false); }
 
-  public void testNumericLiterals() throws Exception { doTest(false, false); }
-  public void testInitializerCompletion() throws Exception { doTest(false, false); }
+  public void testNumericLiterals() { doTest(false, false); }
+  public void testInitializerCompletion() { doTest(false, false); }
 
-  public void testUndefinedLabel() throws Exception { doTest(false, false); }
-  public void testDuplicateSwitchLabels() throws Exception { doTest(false, false); }
-  public void testStringSwitchLabels() throws Exception { doTest(false, false); }
-  public void testIllegalForwardReference() throws Exception { doTest(false, false); }
-  public void testStaticOverride() throws Exception { doTest(false, false); }
-  public void testCyclicInheritance() throws Exception { doTest(false, false); }
-  public void testReferenceMemberBeforeCtrCalled() throws Exception { doTest(false, false); }
-  public void testLabels() throws Exception { doTest(false, false); }
-  public void testUnclosedBlockComment() throws Exception { doTest(false, false); }
-  public void testUnclosedComment() throws Exception { doTest(false, false); }
-  public void testUnclosedDecl() throws Exception { doTest(false, false); }
-  public void testSillyAssignment() throws Exception { doTest(true, false); }
-  public void testTernary() throws Exception { doTest(false, false); }
-  public void testDuplicateClass() throws Exception { doTest(false, false); }
-  public void testCatchType() throws Exception { doTest(false, false); }
-  public void testMustBeThrowable() throws Exception { doTest(false, false); }
-  public void testUnhandledMessingWithFinally() throws Exception { doTest(false, false); }
-  public void testSerializableStuff() throws Exception { doTest(true, false); }
-  public void testDeprecated() throws Exception { doTest(true, false); }
-  public void testJavadoc() throws Exception { enableInspectionTool(new JavaDocLocalInspection()); doTest(true, false); }
-  public void testExpressionsInSwitch () throws Exception { doTest(false, false); }
-  public void testAccessInner () throws Exception { doTest(false, false); }
+  public void testUndefinedLabel() { doTest(false, false); }
+  public void testDuplicateSwitchLabels() { doTest(false, false); }
+  public void testStringSwitchLabels() { doTest(false, false); }
+  public void testIllegalForwardReference() { doTest(false, false); }
+  public void testStaticOverride() { doTest(false, false); }
+  public void testCyclicInheritance() { doTest(false, false); }
+  public void testReferenceMemberBeforeCtrCalled() { doTest(false, false); }
+  public void testLabels() { doTest(false, false); }
+  public void testUnclosedBlockComment() { doTest(false, false); }
+  public void testUnclosedComment() { doTest(false, false); }
+  public void testUnclosedDecl() { doTest(false, false); }
+  public void testSillyAssignment() { doTest(true, false); }
+  public void testTernary() { doTest(false, false); }
+  public void testDuplicateClass() { doTest(false, false); }
+  public void testCatchType() { doTest(false, false); }
+  public void testMustBeThrowable() { doTest(false, false); }
+  public void testUnhandledMessingWithFinally() { doTest(false, false); }
+  public void testSerializableStuff() { doTest(true, false); }
+  public void testDeprecated() { doTest(true, false); }
+  public void testJavadoc() { enableInspectionTool(new JavaDocLocalInspection()); doTest(true, false); }
+  public void testExpressionsInSwitch () { doTest(false, false); }
+  public void testAccessInner () { doTest(false, false); }
 
-  public void testExceptionNeverThrown() throws Exception { doTest(true, false); }
-  public void testExceptionNeverThrownInTry() throws Exception { doTest(false, false); }
+  public void testExceptionNeverThrown() { doTest(true, false); }
+  public void testExceptionNeverThrownInTry() { doTest(false, false); }
 
-  public void testSwitchStatement() throws Exception { doTest(false, false); }
-  public void testAssertExpression() throws Exception { doTest(false, false); }
+  public void testSwitchStatement() { doTest(false, false); }
+  public void testAssertExpression() { doTest(false, false); }
 
-  public void testSynchronizedExpression() throws Exception { doTest(false, false); }
-  public void testExtendMultipleClasses() throws Exception { doTest(false, false); }
-  public void testRecursiveConstructorInvocation() throws Exception { doTest(false, false); }
-  public void testMethodCalls() throws Exception { doTest(false, false); }
-  public void testSingleTypeImportConflicts() throws Exception { doTest(false, false); }
-  public void testMultipleSingleTypeImports() throws Exception { doTest(true, false); } //duplicate imports
-  public void testNotAllowedInInterface() throws Exception { doTest(false, false); }
-  public void testQualifiedNew() throws Exception { doTest(false, false); }
-  public void testEnclosingInstance() throws Exception { doTest(false, false); }
+  public void testSynchronizedExpression() { doTest(false, false); }
+  public void testExtendMultipleClasses() { doTest(false, false); }
+  public void testRecursiveConstructorInvocation() { doTest(false, false); }
+  public void testMethodCalls() { doTest(false, false); }
+  public void testSingleTypeImportConflicts() { doTest(false, false); }
+  public void testMultipleSingleTypeImports() { doTest(true, false); } //duplicate imports
+  public void testNotAllowedInInterface() { doTest(false, false); }
+  public void testQualifiedNew() { doTest(false, false); }
+  public void testEnclosingInstance() { doTest(false, false); }
 
-  public void testStaticViaInstance() throws Exception { doTest(true, false); } // static via instance
-  public void testQualifiedThisSuper() throws Exception { doTest(true, false); } //illegal qualified this or super
+  public void testStaticViaInstance() { doTest(true, false); } // static via instance
+  public void testQualifiedThisSuper() { doTest(true, false); } //illegal qualified this or super
 
-  public void testAmbiguousMethodCall() throws Exception { doTest(false, false); }
+  public void testAmbiguousMethodCall() { doTest(false, false); }
 
-  public void testImplicitConstructor() throws Exception { doTest(false, false); }
-  public void testDotBeforeDecl() throws Exception { doTest(false, false); }
-  public void testComputeConstant() throws Exception { doTest(false, false); }
+  public void testImplicitConstructor() { doTest(false, false); }
+  public void testDotBeforeDecl() { doTest(false, false); }
+  public void testComputeConstant() { doTest(false, false); }
 
-  public void testAnonInAnon() throws Exception { doTest(false, false); }
-  public void testAnonBaseRef() throws Exception { doTest(false, false); }
-  public void testReturn() throws Exception { doTest(false, false); }
-  public void testInterface() throws Exception { doTest(false, false); }
-  public void testExtendsClause() throws Exception { doTest(false, false); }
-  public void testMustBeFinal() throws Exception { doTest(false, false); }
+  public void testAnonInAnon() { doTest(false, false); }
+  public void testAnonBaseRef() { doTest(false, false); }
+  public void testReturn() { doTest(false, false); }
+  public void testInterface() { doTest(false, false); }
+  public void testExtendsClause() { doTest(false, false); }
+  public void testMustBeFinal() { doTest(false, false); }
 
-  public void testXXX() throws Exception { doTest(false, false); }
-  public void testUnused() throws Exception { doTest(true, false); }
-  public void testQualifierBeforeClassName() throws Exception { doTest(false, false); }
-  public void testQualifiedSuper() throws Exception { doTest(false, false); }
-  public void testCastFromVoid() throws Exception { doTest(false, false); }
-  public void testCatchUnknownMethod() throws Exception { doTest(false, false); }
-  public void testIDEADEV8822() throws Exception { doTest(false, false); }
-  public void testIDEADEV9201() throws Exception { doTest(false, false); }
-  public void testIDEADEV25784() throws Exception { doTest(false, false); }
-  public void testIDEADEV13249() throws Exception { doTest(false, false); }
-  public void testIDEADEV11919() throws Exception { doTest(false, false); }
-  public void testMethodCannotBeApplied() throws Exception { doTest(false, false); }
-  public void testDefaultPackageClassInStaticImport() throws Exception { doTest(false, false); }
+  public void testXXX() { doTest(false, false); }
+  public void testUnused() { doTest(true, false); }
+  public void testQualifierBeforeClassName() { doTest(false, false); }
+  public void testQualifiedSuper() {
+    ((JavaVersionServiceImpl)JavaVersionService.getInstance()).setTestVersion(JavaSdkVersion.JDK_1_6, myTestRootDisposable);
+    doTest(false, false); 
+  }
 
-  public void testUnusedParamsOfPublicMethod() throws Exception { doTest(true, false); }
-  public void testInnerClassesShadowing() throws Exception { doTest(false, false); }
+  public void testIgnoreImplicitThisReferenceBeforeSuperSinceJdk7() throws Exception {
+    doTest(false, false);
+  }
 
-  public void testUnusedParamsOfPublicMethodDisabled() throws Exception {
+  public void testCastFromVoid() { doTest(false, false); }
+  public void testCatchUnknownMethod() { doTest(false, false); }
+  public void testIDEADEV8822() { doTest(false, false); }
+  public void testIDEADEV9201() { doTest(false, false); }
+  public void testIDEADEV25784() { doTest(false, false); }
+  public void testIDEADEV13249() { doTest(false, false); }
+  public void testIDEADEV11919() { doTest(false, false); }
+  public void testIDEA67829() { doTest(false, false); }
+  public void testMethodCannotBeApplied() { doTest(false, false); }
+  public void testDefaultPackageClassInStaticImport() { doTest(false, false); }
+
+  public void testUnusedParamsOfPublicMethod() { doTest(true, false); }
+  public void testInnerClassesShadowing() { doTest(false, false); }
+
+  public void testUnusedParamsOfPublicMethodDisabled() {
     myUnusedSymbolLocalInspection.REPORT_PARAMETER_FOR_PUBLIC_METHODS = false;
     doTest(true, false);
   }
 
-  public void testUnusedNonPrivateMembers() throws Exception {
+  public void testUnusedNonPrivateMembers() {
     UnusedDeclarationInspection deadCodeInspection = new UnusedDeclarationInspection();
     enableInspectionTool(deadCodeInspection);
     doTest(true, false);
   }
 
-  public void testUnusedNonPrivateMembers2() throws Exception {
+  public void testUnusedNonPrivateMembers2() {
     ExtensionPoint<EntryPoint> point = Extensions.getRootArea().getExtensionPoint(ExtensionPoints.DEAD_CODE_TOOL);
     EntryPoint extension = new EntryPoint() {
       @NotNull
@@ -251,7 +263,7 @@
       point.unregisterExtension(extension);
     }
   }
-  public void testUnusedNonPrivateMembersReferencedFromText() throws Exception {
+  public void testUnusedNonPrivateMembersReferencedFromText() {
     UnusedDeclarationInspection deadCodeInspection = new UnusedDeclarationInspection();
     enableInspectionTool(deadCodeInspection);
 
@@ -277,12 +289,12 @@
     assertEmpty(infos);
   }
 
-  public void testNamesHighlighting() throws Exception {
+  public void testNamesHighlighting() {
     LanguageLevelProjectExtension.getInstance(getJavaFacade().getProject()).setLanguageLevel(LanguageLevel.JDK_1_5);
     doTestFile(BASE_PATH + "/" + getTestName(false) + ".java").checkSymbolNames().test();
   }
 
-  public void testMultiFieldDeclNames() throws Exception {
+  public void testMultiFieldDeclNames() {
     doTestFile(BASE_PATH + "/" + getTestName(false) + ".java").checkSymbolNames().test();
   }
 
@@ -306,7 +318,7 @@
     }
   }
 
-  public void testInjectedAnnotator() throws Exception {
+  public void testInjectedAnnotator() {
     Annotator annotator = new MyAnnotator();
     Language xml = StdFileTypes.XML.getLanguage();
     LanguageAnnotators.INSTANCE.addExplicitExtension(xml, annotator);
@@ -354,14 +366,21 @@
     doHighlighting();
   }
 
-  public void testClassicRethrow() throws Exception { doTest(false, false); }
-  public void testRegexp() throws Exception { doTest(false, false); }
-  public void testUnsupportedFeatures() throws Exception { doTest(false, false); }
-  public void testThisBeforeSuper() throws Exception { doTest(false, false); }
-  public void testExplicitConstructorInvocation() throws Exception { doTest(false, false); }
-  public void testThisInInterface() throws Exception { doTest(false, false); }
-  public void testInnerClassConstantReference() throws Exception { doTest(false, false); }
-  public void testStaticMethodCalls() throws Exception {
+  public void testClassicRethrow() { doTest(false, false); }
+  public void testRegexp() { doTest(false, false); }
+  public void testUnsupportedFeatures() { doTest(false, false); }
+  public void testThisBeforeSuper() { doTest(false, false); }
+  public void testExplicitConstructorInvocation() { doTest(false, false); }
+  public void testThisInInterface() { doTest(false, false); }
+  public void testInnerClassConstantReference() { doTest(false, false); }
+  public void testIDEA60875() { doTest(false, false); }
+  public void testIDEA71645() { doTest(false, false); }
+
+  public void testNoEnclosingInstanceWhenStaticNestedInheritsFromContainingClass() throws Exception {
+    doTest(false, false);
+  }
+
+  public void testStaticMethodCalls() {
     doTestFile(BASE_PATH + "/" + getTestName(false) + ".java").checkSymbolNames().test();
   }
 }
diff --git a/java/java-tests/testSrc/com/intellij/psi/ClsMirrorBuildingTest.java b/java/java-tests/testSrc/com/intellij/psi/ClsMirrorBuildingTest.java
index f15637e..14c2e29 100644
--- a/java/java-tests/testSrc/com/intellij/psi/ClsMirrorBuildingTest.java
+++ b/java/java-tests/testSrc/com/intellij/psi/ClsMirrorBuildingTest.java
@@ -41,6 +41,7 @@
   public void testPackageInfo() { doTest("package-info"); }
   public void testEA40568() { doTest(); }
   public void testBooleans() { doTest(); }
+  public void testClassRefs() { doTest(); }
 
   private void doTest() {
     doTest(getTestName(false));
diff --git a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java
index 4d9e581..a447fa1 100644
--- a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java
+++ b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java
@@ -177,7 +177,7 @@
   }
 
   public void testSCR40281() throws Exception {
-    doTest(new MockIntroduceVariableHandler("temp", false, false, false, "Set<? extends Map<?,String>.Entry<?,String>>"));
+    doTest(new MockIntroduceVariableHandler("temp", false, false, false, "Set<? extends Map<?,java.lang.String>.Entry<?,java.lang.String>>"));
   }
 
   public void testWithIfBranches() throws Exception {
@@ -189,7 +189,7 @@
   }
 
   public void testDuplicateGenericExpressions() throws Exception {
-    doTest(new MockIntroduceVariableHandler("temp", true, false, false, "Foo2<? extends Runnable>"));
+    doTest(new MockIntroduceVariableHandler("temp", true, false, false, "Foo2<? extends java.lang.Runnable>"));
   }
 
   public void testStaticImport() throws Exception {
diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MockIntroduceVariableHandler.java b/java/java-tests/testSrc/com/intellij/refactoring/MockIntroduceVariableHandler.java
index f355849..008f3f9 100644
--- a/java/java-tests/testSrc/com/intellij/refactoring/MockIntroduceVariableHandler.java
+++ b/java/java-tests/testSrc/com/intellij/refactoring/MockIntroduceVariableHandler.java
@@ -52,7 +52,7 @@
                                                PsiElement anchor, final OccurrencesChooser.ReplaceChoice replaceChoice) {
     final PsiType type = myLookForType ? findType(typeSelectorManager.getTypesForAll(), typeSelectorManager.getDefaultType())
                                        : typeSelectorManager.getDefaultType();
-    Assert.assertTrue(type.getCanonicalText(), type.equalsToText(myExpectedTypeCanonicalName));
+    Assert.assertTrue(type.getInternalCanonicalText(), type.getInternalCanonicalText().equals(myExpectedTypeCanonicalName));
     IntroduceVariableSettings introduceVariableSettings = new IntroduceVariableSettings() {
       @Override
       public String getEnteredName() {
diff --git a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java
index 240e7e5..71e2bb7 100644
--- a/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java
+++ b/java/testFramework/src/com/intellij/codeInsight/CodeInsightTestCase.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -108,6 +108,7 @@
   protected void configureByFile(@NonNls String filePath) throws Exception {
     configureByFile(filePath, null);
   }
+
   protected VirtualFile configureByFiles(@Nullable String projectRoot,String... files) throws Exception {
     final VirtualFile[] vFiles = new VirtualFile[files.length];
     for (int i = 0; i < files.length; i++) {
@@ -122,6 +123,7 @@
 
     return configureByFiles(projectFile, vFiles);
   }
+
   protected VirtualFile configureByFile(@NonNls String filePath, String projectRoot) throws Exception {
     String fullPath = getTestDataPath() + filePath;
 
diff --git a/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java b/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java
index ae80acc..6d40070c 100644
--- a/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java
+++ b/java/testFramework/src/com/intellij/codeInsight/daemon/DaemonAnalyzerTestCase.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -255,10 +255,11 @@
   @NotNull
   @SuppressWarnings("TestMethodWithIncorrectSignature")
   protected HighlightTestInfo testFile(@NonNls @NotNull String... filePath) {
-    return new HighlightTestInfo(getTestRootDisposable(), filePath){
+    return new HighlightTestInfo(getTestRootDisposable(), filePath) {
       @Override
-      public HighlightTestInfo doTest() throws Exception {
-        configureByFiles(projectRoot, filePaths);
+      public HighlightTestInfo doTest() {
+        try { configureByFiles(projectRoot, filePaths); }
+        catch (Exception e) { throw new RuntimeException(e); }
         ExpectedHighlightingData data = new ExpectedHighlightingData(myEditor.getDocument(), checkWarnings, checkWeakWarnings, checkInfos, myFile);
         if (checkSymbolNames) data.checkSymbolNames();
         checkHighlighting(data);
diff --git a/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java b/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java
index 548e7af..1416e81 100644
--- a/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java
+++ b/java/testFramework/src/com/intellij/codeInsight/daemon/LightDaemonAnalyzerTestCase.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -117,9 +117,9 @@
   }
 
   protected HighlightTestInfo doTestFile(@NonNls @NotNull String filePath) {
-    return new HighlightTestInfo(getTestRootDisposable(), filePath){
+    return new HighlightTestInfo(getTestRootDisposable(), filePath) {
       @Override
-      public HighlightTestInfo doTest() throws Exception {
+      public HighlightTestInfo doTest() {
         String path = assertOneElement(filePaths);
         configureByFile(path);
         ExpectedHighlightingData data = new ExpectedHighlightingData(myEditor.getDocument(), checkWarnings, checkWeakWarnings, checkInfos, myFile);
diff --git a/platform/core-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java b/platform/core-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java
index edad97c..e0c4a22 100644
--- a/platform/core-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java
+++ b/platform/core-impl/src/com/intellij/psi/impl/file/impl/FileManagerImpl.java
@@ -31,6 +31,7 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.FileIndexFacade;
 import com.intellij.openapi.util.Disposer;
+import com.intellij.openapi.util.LowMemoryWatcher;
 import com.intellij.openapi.vfs.VfsUtilCore;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.openapi.vfs.VirtualFileVisitor;
@@ -68,6 +69,13 @@
 
   private final FileDocumentManager myFileDocumentManager;
   private final MessageBusConnection myConnection;
+  @SuppressWarnings("UnusedDeclaration")
+  private final LowMemoryWatcher myLowMemoryWatcher = LowMemoryWatcher.register(new Runnable() {
+    @Override
+    public void run() {
+      processQueue();
+    }
+  });
 
   public FileManagerImpl(PsiManagerImpl manager, FileDocumentManager fileDocumentManager, FileIndexFacade fileIndex) {
     myManager = manager;
diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java b/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java
index 8100221..221fd75 100644
--- a/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java
+++ b/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java
@@ -57,7 +57,6 @@
 import com.intellij.psi.tree.IStubFileElementType;
 import com.intellij.psi.tree.TokenSet;
 import com.intellij.reference.SoftReference;
-import com.intellij.testFramework.LightVirtualFile;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.PatchedWeakReference;
 import com.intellij.util.containers.ContainerUtil;
@@ -406,9 +405,9 @@
 
     synchronized (PsiLock.LOCK) {
       clearStub();
-      if (tree != null) {
-        tree.putUserData(STUB_TREE_IN_PARSED_TREE, null);
-      }
+    }
+    if (tree != null) {
+      tree.putUserData(STUB_TREE_IN_PARSED_TREE, null);
     }
 
     clearCaches();
@@ -946,13 +945,15 @@
   }
 
   private static final Key<StubTree> STUB_TREE_IN_PARSED_TREE = new Key<StubTree>("STUB_TREE_IN_PARSED_TREE");
+  private final Object myStubFromTreeLock = new Object();
 
   public StubTree calcStubTree() {
     FileElement fileElement = calcTreeElement();
-    synchronized (PsiLock.LOCK) {
+    synchronized (myStubFromTreeLock) {
       StubTree tree = fileElement.getUserData(STUB_TREE_IN_PARSED_TREE);
 
       if (tree == null) {
+        ApplicationManager.getApplication().assertReadAccessAllowed();
         IElementType contentElementType = getContentElementType();
         if (!(contentElementType instanceof IStubFileElementType)) {
           VirtualFile vFile = getVirtualFile();
diff --git a/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties b/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties
index 1b8f1f9..bcc54db 100644
--- a/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties
+++ b/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties
@@ -1,30 +1,13 @@
-# Entity type.
-entity.type.module=module
-entity.type.content.root=content-root
-entity.type.jar=jar
-entity.type.library.dependency=library dependency
-entity.type.module.dependency=module dependency
-entity.type.dependencies=dependencies
-entity.type.modules=modules
-entity.type.libraries=libraries
-
-# Change.
-change.dependency.exported='exported' value change for {0}
-change.dependency.scope=scope change for {0}
-change.project.language.level=project language level change
-change.project.name=project name
-
 # Settings.
 setting.type.location.deduced={0} location is deduced
 setting.type.location.unknown={0} location is unknown
 setting.type.location.explicit.correct={0} location is defined
 setting.type.location.explicit.incorrect={0} location is incorrect
-<<<<<<< HEAD
-<<<<<<< HEAD
-=======
->>>>>>> 5fd2c47... IDEA-104500 Gradle: Allow to reuse common logic for other external systems
 settings.label.select.project={0} project:
 settings.label.use.auto.import=Use auto-import
+settings.title.linked.projects=Linked {0} projects
+settings.title.project.settings=Project-level settings
+settings.title.system.settings=Global {0} settings
 
 # Progress.
 progress.import.text=Building {0} project info
@@ -37,11 +20,4 @@
 error.resolve.generic.without.reason=Can''t resolve target {0} project at ''{1}''.\nConsult IDE log for more details (Help | Show Log)
 error.cannot.parse.project=Can not parse {0} project
 error.resolve.with.reason={0}\n\nConsult IDE log for more details (Help | Show Log)
-<<<<<<< HEAD
-error.resolve.generic=Resolve error
-=======
-settings.label.select.project={0} project:
->>>>>>> 38a9775... IDEA-104500 Gradle: Allow to reuse common logic for other external systems
-=======
-error.resolve.generic=Resolve error
->>>>>>> 5fd2c47... IDEA-104500 Gradle: Allow to reuse common logic for other external systems
+error.resolve.generic=Resolve error
\ No newline at end of file
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/ExternalSystemManager.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/ExternalSystemManager.java
index 84eb746..783a04b0 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/ExternalSystemManager.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/ExternalSystemManager.java
@@ -8,8 +8,10 @@
 import com.intellij.openapi.externalSystem.service.project.ExternalSystemProjectResolver;
 import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemLocalSettings;
 import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
+import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
 import com.intellij.openapi.externalSystem.settings.ExternalSystemSettingsListener;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Pair;
 import com.intellij.util.Function;
 import org.jetbrains.annotations.NotNull;
 
@@ -25,8 +27,9 @@
  * @since 4/4/13 4:05 PM
  */
 public interface ExternalSystemManager<
-  SettingsListener extends ExternalSystemSettingsListener,
-  Settings extends AbstractExternalSystemSettings<SettingsListener, Settings>,
+  ProjectSettings extends ExternalProjectSettings,
+  SettingsListener extends ExternalSystemSettingsListener<ProjectSettings>,
+  Settings extends AbstractExternalSystemSettings<ProjectSettings, SettingsListener>,
   LocalSettings extends AbstractExternalSystemLocalSettings<LocalSettings>,
   ExecutionSettings extends ExternalSystemExecutionSettings>
   extends ParametersEnhancer
@@ -41,17 +44,6 @@
   ProjectSystemId getSystemId();
 
   /**
-   * Allows to answer if target external system is ready to use for the given project.
-   * <p/>
-   * A negative answer might be returned if, say, target external system config path is not defined at the given ide project.
-   * 
-   * @param project  target ide project
-   * @return         <code>true</code> if target external system is configured for the given ide project;
-   *                 <code>false</code> otherwise
-   */
-  boolean isReady(@NotNull Project project);
-  
-  /**
    * @return    a strategy which can be queried for external system settings to use with the given project
    */
   @NotNull
@@ -67,7 +59,7 @@
    * @return    a strategy which can be queried for external system execution settings to use with the given project
    */
   @NotNull
-  Function<Project, ExecutionSettings> getExecutionSettingsProvider();
+  Function<Pair<Project, String/*linked project path*/>, ExecutionSettings> getExecutionSettingsProvider();
 
   /**
    * Allows to retrieve information about {@link ExternalSystemProjectResolver project resolver} to use for the target external
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ProjectData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ProjectData.java
index bd10e16..5355a7b 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ProjectData.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ProjectData.java
@@ -14,28 +14,37 @@
 
   private static final long serialVersionUID = 1L;
 
-  @NotNull private String myProjectFileDirectoryPath;
+  @NotNull private final String myLinkedExternalProjectPath;
+
+  @NotNull private String myIdeProjectFileDirectoryPath;
 
   public ProjectData(@NotNull ProjectSystemId owner,
-                     @NotNull String projectFileDirectoryPath)
+                     @NotNull String ideProjectFileDirectoryPath,
+                     @NotNull String linkedExternalProjectPath)
   {
     super(owner, "unnamed");
-    myProjectFileDirectoryPath = ExternalSystemApiUtil.toCanonicalPath(projectFileDirectoryPath);
+    myLinkedExternalProjectPath = linkedExternalProjectPath;
+    myIdeProjectFileDirectoryPath = ExternalSystemApiUtil.toCanonicalPath(ideProjectFileDirectoryPath);
   }
 
   @NotNull
-  public String getProjectFileDirectoryPath() {
-    return myProjectFileDirectoryPath;
+  public String getIdeProjectFileDirectoryPath() {
+    return myIdeProjectFileDirectoryPath;
   }
 
-  public void setProjectFileDirectoryPath(@NotNull String projectFileDirectoryPath) {
-    myProjectFileDirectoryPath = ExternalSystemApiUtil.toCanonicalPath(projectFileDirectoryPath);
+  public void setIdeProjectFileDirectoryPath(@NotNull String ideProjectFileDirectoryPath) {
+    myIdeProjectFileDirectoryPath = ExternalSystemApiUtil.toCanonicalPath(ideProjectFileDirectoryPath);
+  }
+
+  @NotNull
+  public String getLinkedExternalProjectPath() {
+    return myLinkedExternalProjectPath;
   }
 
   @Override
   public int hashCode() {
     int result = super.hashCode();
-    result = 31 * result + myProjectFileDirectoryPath.hashCode();
+    result = 31 * result + myIdeProjectFileDirectoryPath.hashCode();
     return result;
   }
 
@@ -47,7 +56,7 @@
 
     ProjectData project = (ProjectData)o;
 
-    if (!myProjectFileDirectoryPath.equals(project.myProjectFileDirectoryPath)) return false;
+    if (!myIdeProjectFileDirectoryPath.equals(project.myIdeProjectFileDirectoryPath)) return false;
 
     return true;
   }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataService.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataService.java
index e6f9f63..1a67a1f 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataService.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataService.java
@@ -57,6 +57,25 @@
   @NotNull
   Key<T> getTargetDataKey();
 
+  /**
+   * It's assumed that given data nodes present at the ide when this method returns. I.e. the method should behave as below for
+   * every of the given data nodes:
+   * <pre>
+   * <ul>
+   *   <li>there is an existing project entity for the given data node and it has the same state. Do nothing for it then;</li>
+   *   <li>
+   *     there is an existing project entity for the given data node but it has different state (e.g. a module dependency
+   *     is configured as 'exported' at the ide but not at external system). Reset the state to the external system's one then;
+   *   </li>
+   *   <li> there is no corresponding project entity at the ide side. Create it then; </li>
+   * </ul>
+   * </pre>
+   * are created, updated or left as-is if they have the
+   * 
+   * @param toImport
+   * @param project
+   * @param synchronous
+   */
   void importData(@NotNull Collection<DataNode<T>> toImport, @NotNull Project project, boolean synchronous);
 
   void removeData(@NotNull Collection<DataNode<T>> toRemove, @NotNull Project project, boolean synchronous);
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemLocalSettings.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemLocalSettings.java
index 28fb7b4..a783c56 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemLocalSettings.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemLocalSettings.java
@@ -31,7 +31,7 @@
 import java.util.concurrent.atomic.AtomicReference;
 
 /**
- * Holds local project-level gradle-related settings (should be kept at the '*.iws' or 'workspace.xml').
+ * Holds local project-level external system-related settings (should be kept at the '*.iws' or 'workspace.xml').
  * <p/>
  * For example, we don't want to store recent tasks list at common external system settings, hence, that data
  * is kept at user-local settings (workspace settings).
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java
index 3148530..ba6fc15 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java
@@ -15,15 +15,14 @@
  */
 package com.intellij.openapi.externalSystem.settings;
 
-import com.intellij.openapi.components.PersistentStateComponent;
-import com.intellij.openapi.components.State;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.Comparing;
+import com.intellij.util.containers.ContainerUtilRt;
 import com.intellij.util.messages.Topic;
-import com.intellij.util.xmlb.XmlSerializerUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.util.*;
+
 /**
  * Common base class for external system settings. Defines a minimal api which is necessary for the common external system
  * support codebase.
@@ -33,62 +32,90 @@
  * @author Denis Zhdanov
  * @since 4/3/13 4:04 PM
  */
-public abstract class AbstractExternalSystemSettings<L extends ExternalSystemSettingsListener, S extends AbstractExternalSystemSettings<L,S>>
-{
-
+public abstract class AbstractExternalSystemSettings<S extends ExternalProjectSettings, L extends ExternalSystemSettingsListener<S>> {
+  
   @NotNull private final Topic<L> myChangesTopic;
   @NotNull private final Project  myProject;
 
-  @Nullable private String myLinkedExternalProjectPath;
-
-  private boolean myUseAutoImport = true; // Turned on by default.
+  @NotNull private final Map<String/* project path */, S> myLinkedProjectsSettings = ContainerUtilRt.newHashMap();
 
   protected AbstractExternalSystemSettings(@NotNull Topic<L> topic, @NotNull Project project) {
     myChangesTopic = topic;
     myProject = project;
   }
+  
+  @SuppressWarnings("unchecked")
+  @NotNull
+  public Collection<S> getLinkedProjectsSettings() {
+    return myLinkedProjectsSettings.values();
+  }
 
   @Nullable
-  public String getLinkedExternalProjectPath() {
-    return myLinkedExternalProjectPath;
+  public S getLinkedProjectSettings(@NotNull String linkedProjectPath) {
+    return myLinkedProjectsSettings.get(linkedProjectPath);
   }
 
-  public void setLinkedExternalProjectPath(@Nullable String linkedProjectPath) {
-    if (!Comparing.equal(myLinkedExternalProjectPath, linkedProjectPath)) {
-      final String oldPath = myLinkedExternalProjectPath;
-      myLinkedExternalProjectPath = linkedProjectPath;
-      myProject.getMessageBus().syncPublisher(myChangesTopic).onLinkedProjectPathChange(oldPath, linkedProjectPath);
+  public void setLinkedProjectsSettings(@NotNull Collection<S> settings) {
+    List<S> added = ContainerUtilRt.newArrayList();
+    Map<String, S> removed = ContainerUtilRt.newHashMap(myLinkedProjectsSettings);
+    myLinkedProjectsSettings.clear();
+    for (S current : settings) {
+      myLinkedProjectsSettings.put(current.getExternalProjectPath(), current);
+    }
+    
+    for (S current : settings) {
+      S old = removed.remove(current.getExternalProjectPath());
+      if (old == null) {
+        added.add(current);
+      }
+      else {
+        if (current.isUseAutoImport() != old.isUseAutoImport()) {
+          getPublisher().onUseAutoImportChange(current.isUseAutoImport(), current.getExternalProjectPath());
+        }
+        checkSettings(old, current);
+      }
+    }
+    if (!added.isEmpty()) {
+      getPublisher().onProjectsLinked(added);
+    }
+    if (!removed.isEmpty()) {
+      getPublisher().onProjectsUnlinked(removed.keySet());
     }
   }
 
-  public boolean isUseAutoImport() {
-    return myUseAutoImport;
-  }
-
-  public void setUseAutoImport(boolean useAutoImport) {
-    if (myUseAutoImport != useAutoImport) {
-      myUseAutoImport = useAutoImport;
-      myProject.getMessageBus().syncPublisher(myChangesTopic).onUseAutoImportChange(useAutoImport);
-    }
-  }
+  /**
+   * Is assumed to check if given old settings external system-specific state differs from the given new one
+   * and {@link #getPublisher() notify} listeners in case of the positive answer.
+   * 
+   * @param old      old settings state
+   * @param current  current settings state
+   */
+  protected abstract void checkSettings(@NotNull S old, @NotNull S current);
 
   @NotNull
-  protected L getPublisher() {
+  public L getPublisher() {
     return myProject.getMessageBus().syncPublisher(myChangesTopic);
   }
 
-  protected void fillState(@NotNull State state) {
-    state.linkedExternalProjectPath = myLinkedExternalProjectPath;
-    state.useAutoImport = myUseAutoImport;
+  protected void fillState(@NotNull State<S> state) {
+    state.setLinkedExternalProjectsSettings(ContainerUtilRt.newTreeSet(myLinkedProjectsSettings.values()));
   }
 
-  protected void loadState(@NotNull State state) {
-    myLinkedExternalProjectPath = state.linkedExternalProjectPath;
-    myUseAutoImport = state.useAutoImport;
+  @SuppressWarnings("unchecked")
+  protected void loadState(@NotNull State<S> state) {
+    Set<S> settings = state.getLinkedExternalProjectsSettings();
+    if (settings != null) {
+      myLinkedProjectsSettings.clear();
+      for (S s : settings) {
+        myLinkedProjectsSettings.put(s.getExternalProjectPath(), s);
+      }
+    }
   }
-  
-  public static class State {
-    public String linkedExternalProjectPath;
-    public boolean useAutoImport;
+
+  public interface State<S> {
+    
+    Set<S> getLinkedExternalProjectsSettings();
+
+    void setLinkedExternalProjectsSettings(Set<S> settings);
   }
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java
new file mode 100644
index 0000000..c7a6ecb
--- /dev/null
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2000-2013 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.openapi.externalSystem.settings;
+
+import com.intellij.openapi.util.Comparing;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * Holds settings specific to a particular project imported from an external system.
+ *
+ * @author Denis Zhdanov
+ * @since 4/24/13 11:41 AM
+ */
+public abstract class ExternalProjectSettings implements Comparable<ExternalProjectSettings>, Cloneable {
+
+  private String  myExternalProjectPath;
+  private boolean myUseAutoImport;
+
+  public String getExternalProjectPath() {
+    return myExternalProjectPath;
+  }
+
+  public void setExternalProjectPath(@NotNull String externalProjectPath) {
+    myExternalProjectPath = externalProjectPath;
+  }
+
+  public boolean isUseAutoImport() {
+    return myUseAutoImport;
+  }
+
+  public void setUseAutoImport(boolean useAutoImport) {
+    myUseAutoImport = useAutoImport;
+  }
+
+  @Override
+  public int compareTo(@NotNull ExternalProjectSettings that) {
+    return Comparing.compare(myExternalProjectPath, that.myExternalProjectPath);
+  }
+
+  @Override
+  public int hashCode() {
+    return myExternalProjectPath != null ? myExternalProjectPath.hashCode() : 0;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    ExternalProjectSettings that = (ExternalProjectSettings)o;
+
+    return myExternalProjectPath == null ? that.myExternalProjectPath == null : myExternalProjectPath.equals(that.myExternalProjectPath);
+  }
+
+  @Override
+  public String toString() {
+    return myExternalProjectPath;
+  }
+
+  @NotNull
+  public abstract ExternalProjectSettings clone();
+
+  protected void copyTo(@NotNull ExternalProjectSettings receiver) {
+    receiver.myExternalProjectPath = myExternalProjectPath;
+    receiver.myUseAutoImport = myUseAutoImport;
+  }
+}
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalSystemSettingsListener.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalSystemSettingsListener.java
index 8089672a..8f9514c 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalSystemSettingsListener.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalSystemSettingsListener.java
@@ -15,7 +15,9 @@
  */
 package com.intellij.openapi.externalSystem.settings;
 
-import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.Collection;
 
 /**
  * Defines callback for external system settings change.
@@ -25,19 +27,13 @@
  * @author Denis Zhdanov
  * @since 4/3/13 4:13 PM
  */
-public interface ExternalSystemSettingsListener {
+public interface ExternalSystemSettingsListener<S extends ExternalProjectSettings> {
+  
+  void onProjectsLinked(@NotNull Collection<S> settings);
 
-  /**
-   * Is expected to be invoked when linked external project path is changed.
-   * <p/>
-   * <b>Note:</b> this callback is executed <b>after</b> the actual config change.
-   *
-   * @param oldPath  old path (if any)
-   * @param newPath  new path (if any)
-   */
-  void onLinkedProjectPathChange(@Nullable String oldPath, @Nullable String newPath);
-
-  void onUseAutoImportChange(boolean currentValue);
+  void onProjectsUnlinked(@NotNull Collection<String> linkedProjectPaths);
+  
+  void onUseAutoImportChange(boolean currentValue, @NotNull String linkedProjectPath);
 
   /**
    * External system settings changes might affect project structure, e.g. switching from one external system version to another
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemApiUtil.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemApiUtil.java
index bb954b8..74095e6 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemApiUtil.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemApiUtil.java
@@ -24,6 +24,7 @@
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.fileTypes.FileTypes;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.project.ProjectManager;
 import com.intellij.openapi.roots.OrderRootType;
 import com.intellij.openapi.roots.libraries.Library;
 import com.intellij.openapi.util.AtomicNotNullLazyValue;
@@ -56,12 +57,12 @@
 
   @NotNull private static final Pattern ARTIFACT_PATTERN = Pattern.compile("(?:.*/)?(.+?)(?:-([\\d+](?:\\.[\\d]+)*))?(?:\\.[^\\.]+?)?");
 
-  @NotNull private static final NotNullLazyValue<Map<ProjectSystemId, ExternalSystemManager<?, ?, ?, ?>>> MANAGERS =
-    new AtomicNotNullLazyValue<Map<ProjectSystemId, ExternalSystemManager<?, ?, ?, ?>>>() {
+  @NotNull private static final NotNullLazyValue<Map<ProjectSystemId, ExternalSystemManager<?, ?, ?, ?, ?>>> MANAGERS =
+    new AtomicNotNullLazyValue<Map<ProjectSystemId, ExternalSystemManager<?, ?, ?, ?, ?>>>() {
       @NotNull
       @Override
-      protected Map<ProjectSystemId, ExternalSystemManager<?, ?, ?, ?>> compute() {
-        Map<ProjectSystemId, ExternalSystemManager<?, ?, ?, ?>> result = ContainerUtilRt.newHashMap();
+      protected Map<ProjectSystemId, ExternalSystemManager<?, ?, ?, ?, ?>> compute() {
+        Map<ProjectSystemId, ExternalSystemManager<?, ?, ?, ?, ?>> result = ContainerUtilRt.newHashMap();
         for (ExternalSystemManager manager : ExternalSystemManager.EP_NAME.getExtensions()) {
           result.put(manager.getSystemId(), manager);
         }
@@ -178,7 +179,7 @@
   }
 
   @Nullable
-  public static ExternalSystemManager<?, ?, ?, ?> getManager(@NotNull ProjectSystemId externalSystemId) {
+  public static ExternalSystemManager<?, ?, ?, ?, ?> getManager(@NotNull ProjectSystemId externalSystemId) {
     return MANAGERS.getValue().get(externalSystemId);
   }
 
@@ -350,4 +351,26 @@
     }
     classPath.add(PathManager.getResourceRoot(contextClass, pathToUse));
   }
+
+  @Nullable
+  public static String normalizePath(@Nullable String s) {
+    return StringUtil.isEmpty(s) ? null : s;
+  }
+
+  /**
+   * We can divide all 'import from external system' use-cases into at least as below:
+   * <pre>
+   * <ul>
+   *   <li>this is a new project being created (import project from external model);</li>
+   *   <li>a new module is being imported from an external project into an existing ide project;</li>
+   * </ul>
+   * </pre>
+   * This method allows to differentiate between them (e.g. we don't want to change language level when new module is imported to
+   * an existing project).
+   * 
+   * @return    <code>true</code> if new project is being imported; <code>false</code> if new module is being imported
+   */
+  public static boolean isNewProjectConstruction() {
+    return ProjectManager.getInstance().getOpenProjects().length == 0;
+  }
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemConstants.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemConstants.java
index e6c23d0..b495879 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemConstants.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemConstants.java
@@ -22,7 +22,10 @@
  * @since 4/16/13 11:44 AM
  */
 public class ExternalSystemConstants {
-  @NonNls @NotNull public static final String NEWLY_IMPORTED_PROJECT = "external.system.newly.imported";
+
+  @NonNls @NotNull public static final String NEWLY_IMPORTED_PROJECT  = "external.system.newly.imported";
+  @NonNls @NotNull public static final String EXTERNAL_SYSTEM_ID_KEY  = "external.system.id";
+  @NonNls @NotNull public static final String LINKED_PROJECT_PATH_KEY = "external.linked.project.path";
 
   // Order.
   public static final int BUILTIN_SERVICE_ORDER = 42;
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/IntegrationKey.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/IntegrationKey.java
index 1ff43e6..4973c28 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/IntegrationKey.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/IntegrationKey.java
@@ -20,7 +20,7 @@
 import org.jetbrains.annotations.NotNull;
 
 /**
- * Unique key which encapsulates information about target ide project and external project management system.
+ * Unique key which encapsulates information about target ide and external projects.
  * <p/>
  * Thread-safe.
  * 
@@ -32,18 +32,21 @@
   @NotNull private final String          myIdeProjectName;
   @NotNull private final String          myIdeProjectLocationHash;
   @NotNull private final ProjectSystemId myExternalSystemId;
+  @NotNull private final String          myExternalProjectConfigPath;
 
-  public IntegrationKey(@NotNull Project ideProject, @NotNull ProjectSystemId externalSystemId) {
-    this(ideProject.getName(), ideProject.getLocationHash(), externalSystemId);
+  public IntegrationKey(@NotNull Project ideProject, @NotNull ProjectSystemId externalSystemId, @NotNull String externalProjectConfigPath) {
+    this(ideProject.getName(), ideProject.getLocationHash(), externalSystemId, externalProjectConfigPath);
   }
 
   public IntegrationKey(@NotNull String ideProjectName,
                         @NotNull String ideProjectLocationHash,
-                        @NotNull ProjectSystemId externalSystemId)
+                        @NotNull ProjectSystemId externalSystemId,
+                        @NotNull String externalProjectConfigPath)
   {
     myIdeProjectName = ideProjectName;
     myIdeProjectLocationHash = ideProjectLocationHash;
     myExternalSystemId = externalSystemId;
+    myExternalProjectConfigPath = externalProjectConfigPath;
   }
 
   @NotNull
@@ -61,11 +64,17 @@
     return myExternalSystemId;
   }
 
+  @NotNull
+  public String getExternalProjectConfigPath() {
+    return myExternalProjectConfigPath;
+  }
+
   @Override
   public int hashCode() {
     int result = myIdeProjectName.hashCode();
     result = 31 * result + myIdeProjectLocationHash.hashCode();
     result = 31 * result + myExternalSystemId.hashCode();
+    result = 31 * result + myExternalProjectConfigPath.hashCode();
     return result;
   }
 
@@ -79,6 +88,7 @@
     if (!myExternalSystemId.equals(key.myExternalSystemId)) return false;
     if (!myIdeProjectLocationHash.equals(key.myIdeProjectLocationHash)) return false;
     if (!myIdeProjectName.equals(key.myIdeProjectName)) return false;
+    if (!myExternalProjectConfigPath.equals(key.myExternalProjectConfigPath)) return false;
 
     return true;
   }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/settings/LocationSettingType.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/settings/LocationSettingType.java
index e546176..113ed09 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/settings/LocationSettingType.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/settings/LocationSettingType.java
@@ -6,6 +6,9 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.PropertyKey;
 
+import javax.swing.*;
+import java.awt.*;
+
 /**
  * Enumerates possible types of 'gradle home' location setting.
  *
@@ -15,7 +18,7 @@
 public enum LocationSettingType {
 
   /** User hasn't defined gradle location but the IDE discovered it automatically. */
-  DEDUCED("setting.type.location.deduced"),
+  DEDUCED("setting.type.location.deduced", "TextField.inactiveForeground"),
 
   /** User hasn't defined gradle location and the IDE was unable to discover it automatically. */
   UNKNOWN("setting.type.location.unknown"),
@@ -25,16 +28,29 @@
 
   EXPLICIT_CORRECT("setting.type.location.explicit.incorrect");
 
-  private final String myKey;
+  @NotNull private final String myDescriptionKey;
+  @NotNull private final String myColorKey;
 
-  LocationSettingType(@NotNull @PropertyKey(resourceBundle = ExternalSystemBundle.PATH_TO_BUNDLE) String key) {
-    myKey = key;
+  LocationSettingType(@NotNull String descriptionKey) {
+    this(descriptionKey, "TextField.foreground");
+  }
+
+  LocationSettingType(@NotNull @PropertyKey(resourceBundle = ExternalSystemBundle.PATH_TO_BUNDLE) String descriptionKey,
+                      @NotNull String colorKey)
+  {
+    myDescriptionKey = descriptionKey;
+    myColorKey = colorKey;
   }
 
   /**
-   * @return    human-readable description of the current setting type
+   * @return human-readable description of the current setting type
    */
   public String getDescription(@NotNull ProjectSystemId externalSystemId) {
-    return ExternalSystemBundle.message(myKey, ExternalSystemApiUtil.toReadableName(externalSystemId));
+    return ExternalSystemBundle.message(myDescriptionKey, ExternalSystemApiUtil.toReadableName(externalSystemId));
+  }
+
+  @NotNull
+  public Color getColor() {
+    return UIManager.getColor(myColorKey);
   }
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/task/AbstractExternalSystemTask.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/task/AbstractExternalSystemTask.java
index ce4c9e23..abbc694 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/task/AbstractExternalSystemTask.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/task/AbstractExternalSystemTask.java
@@ -35,13 +35,17 @@
 
   @NotNull private final ExternalSystemTaskId myId;
   @NotNull private final ProjectSystemId      myExternalSystemId;
+  @NotNull private final String               myExernalProjectPath;
 
   protected AbstractExternalSystemTask(@NotNull ProjectSystemId id,
                                        @NotNull ExternalSystemTaskType type,
-                                       @NotNull Project project) {
+                                       @NotNull Project project,
+                                       @NotNull String externalProjectPath)
+  {
     myExternalSystemId = id;
     myIdeProject = project;
     myId = ExternalSystemTaskId.create(type);
+    myExernalProjectPath = externalProjectPath;
   }
 
   @NotNull
@@ -79,7 +83,7 @@
     }
     final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class);
     try {
-      final RemoteExternalSystemFacade facade = manager.getFacade(myIdeProject, myExternalSystemId);
+      final RemoteExternalSystemFacade facade = manager.getFacade(myIdeProject, myExernalProjectPath, myExternalSystemId);
       setState(facade.isTaskInProgress(getId()) ? ExternalSystemTaskState.IN_PROGRESS : ExternalSystemTaskState.FAILED);
     }
     catch (Throwable e) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemResolveProjectTask.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemResolveProjectTask.java
index ef808df..6b8a59c 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemResolveProjectTask.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemResolveProjectTask.java
@@ -34,7 +34,7 @@
                                           @NotNull String projectPath,
                                           boolean resolveLibraries)
   {
-    super(externalSystemId, ExternalSystemTaskType.RESOLVE_PROJECT, project);
+    super(externalSystemId, ExternalSystemTaskType.RESOLVE_PROJECT, project, projectPath);
     myProjectPath = projectPath;
     myResolveLibraries = resolveLibraries;
   }
@@ -43,11 +43,11 @@
   protected void doExecute() throws Exception {
     final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class);
     Project ideProject = getIdeProject();
-    RemoteExternalSystemProjectResolver resolver = manager.getFacade(ideProject, getExternalSystemId()).getResolver();
+    RemoteExternalSystemProjectResolver resolver = manager.getFacade(ideProject, myProjectPath, getExternalSystemId()).getResolver();
     setState(ExternalSystemTaskState.IN_PROGRESS);
 
     ExternalSystemSettingsManager settingsManager = ServiceManager.getService(ExternalSystemSettingsManager.class);
-    ExternalSystemExecutionSettings settings = settingsManager.getExecutionSettings(ideProject, getExternalSystemId());
+    ExternalSystemExecutionSettings settings = settingsManager.getExecutionSettings(ideProject, myProjectPath, getExternalSystemId());
     DataNode<ProjectData> project = resolver.resolveProjectInfo(getId(), myProjectPath, myResolveLibraries, settings);
     
     if (project == null) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeImpl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeImpl.java
index 3208413..e7825a1 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeImpl.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeImpl.java
@@ -236,10 +236,8 @@
   public void applyProgressManager(@NotNull RemoteExternalSystemProgressNotificationManager progressManager) throws RemoteException {
     ExternalSystemTaskNotificationListener listener = new SwallowingNotificationListener(progressManager);
     myNotificationListener.set(listener);
-    List<RemoteExternalSystemService> services = new ArrayList<RemoteExternalSystemService>(myRemotes.values());
-    for (RemoteExternalSystemService service : services) {
-      service.setNotificationListener(listener);
-    }
+    myProjectResolver.setNotificationListener(listener);
+    myBuildManager.setNotificationListener(listener);
   }
   
   /**
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeManager.java
index b9b8b41..3531a82 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeManager.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeManager.java
@@ -174,7 +174,7 @@
 
         ProjectSystemId externalSystemId = myTargetExternalSystemId.get();
         if (externalSystemId != null) {
-          ExternalSystemManager<?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(externalSystemId);
+          ExternalSystemManager<?, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(externalSystemId);
           if (manager != null) {
             params.getProgramParametersList().add(manager.getProjectResolverClass().getName());
             params.getProgramParametersList().add(manager.getBuildManagerClass().getName());
@@ -226,11 +226,14 @@
    * @throws Exception    in case of inability to return the facade
    */
   @NotNull
-  public RemoteExternalSystemFacade getFacade(@Nullable Project project, @NotNull ProjectSystemId externalSystemId) throws Exception {
+  public RemoteExternalSystemFacade getFacade(@Nullable Project project,
+                                              @NotNull String externalProjectPath,
+                                              @NotNull ProjectSystemId externalSystemId) throws Exception
+  {
     if (project == null) {
       project = ProjectManager.getInstance().getDefaultProject();
     }
-    IntegrationKey key = new IntegrationKey(project, externalSystemId);
+    IntegrationKey key = new IntegrationKey(project, externalSystemId, externalProjectPath);
     final RemoteExternalSystemFacade facade = myFacadeWrappers.get(key);
     if (facade == null) {
       final RemoteExternalSystemFacade newFacade = (RemoteExternalSystemFacade)Proxy.newProxyInstance(
@@ -263,7 +266,7 @@
   @NotNull
   private RemoteExternalSystemFacade doGetFacade(@NotNull IntegrationKey key, @NotNull Project project) throws Exception {
     ExternalSystemManager manager = ExternalSystemApiUtil.getManager(key.getExternalSystemId());
-    if (project.isDisposed() || manager == null || !manager.isReady(project)) {
+    if (project.isDisposed() || manager == null) {
       return RemoteExternalSystemFacade.NULL_OBJECT;
     }
     Pair<RemoteExternalSystemFacade, ExternalSystemExecutionSettings> pair = myRemoteFacades.get(key);
@@ -307,7 +310,8 @@
       }
     });
     final RemoteExternalSystemFacade result = new ExternalSystemFacadeWrapper(facade, myProgressManager);
-    ExternalSystemExecutionSettings settings = mySettingsManager.getExecutionSettings(project, key.getExternalSystemId());
+    ExternalSystemExecutionSettings settings
+      = mySettingsManager.getExecutionSettings(project, key.getExternalProjectConfigPath(), key.getExternalSystemId());
     Pair<RemoteExternalSystemFacade, ExternalSystemExecutionSettings> newPair = Pair.create(result, settings);
     myRemoteFacades.put(key, newPair);
     result.applySettings(newPair.second);
@@ -339,7 +343,8 @@
     try {
       pair.first.getResolver();
 
-      ExternalSystemExecutionSettings currentSettings = mySettingsManager.getExecutionSettings(project, key.getExternalSystemId());
+      ExternalSystemExecutionSettings currentSettings
+        = mySettingsManager.getExecutionSettings(project, key.getExternalProjectConfigPath(), key.getExternalSystemId());
       if (!currentSettings.equals(pair.second)) {
         pair.first.applySettings(currentSettings);
         myRemoteFacades.put(key, Pair.create(pair.first, currentSettings));
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemStartupActivity.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemStartupActivity.java
new file mode 100644
index 0000000..3cd313d
--- /dev/null
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemStartupActivity.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2000-2013 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.openapi.externalSystem.service;
+
+import com.intellij.openapi.externalSystem.ExternalSystemManager;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
+import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.startup.StartupActivity;
+import com.intellij.openapi.startup.StartupManager;
+import com.intellij.util.SystemProperties;
+
+/**
+ * @author Denis Zhdanov
+ * @since 5/2/13 9:23 PM
+ */
+public class ExternalSystemStartupActivity implements StartupActivity {
+
+  @Override
+  public void runActivity(final Project project) {
+    Runnable task = new Runnable() {
+      @SuppressWarnings("unchecked")
+      @Override
+      public void run() {
+        if (SystemProperties.getBooleanProperty(ExternalSystemConstants.NEWLY_IMPORTED_PROJECT, false)) {
+          System.setProperty(ExternalSystemConstants.NEWLY_IMPORTED_PROJECT, Boolean.toString(false));
+        }
+        else {
+          for (ExternalSystemManager manager : ExternalSystemManager.EP_NAME.getExtensions()) {
+            ExternalSystemUtil.refreshProjects(project, manager.getSystemId());
+          }
+        }
+      }
+    };
+
+    if (project.isInitialized()) {
+      task.run();
+    }
+    else {
+      StartupManager.getInstance(project).registerPostStartupActivity(task);
+    } 
+  }
+}
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ExternalProjectRefreshCallback.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ExternalProjectRefreshCallback.java
new file mode 100644
index 0000000..760d1c1
--- /dev/null
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ExternalProjectRefreshCallback.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2000-2013 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.openapi.externalSystem.service.project;
+
+import com.intellij.openapi.externalSystem.model.DataNode;
+import com.intellij.openapi.externalSystem.model.project.ProjectData;
+import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings;
+import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
+import com.intellij.openapi.externalSystem.service.project.ExternalSystemProjectResolver;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+* @author Denis Zhdanov
+* @since 5/2/13 10:37 PM
+*/
+public interface ExternalProjectRefreshCallback {
+
+  /**
+   * Is expected to be called when
+   * {@link ExternalSystemProjectResolver#resolveProjectInfo(ExternalSystemTaskId, String, boolean, ExternalSystemExecutionSettings)}
+   * returns without exception.
+   * 
+   * @param externalProject  target external project (if available)
+   */
+  void onSuccess(@Nullable DataNode<ProjectData> externalProject);
+
+  void onFailure(@NotNull String errorMessage, @Nullable String errorDetails);
+}
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/AbstractDependencyDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/AbstractDependencyDataService.java
index 3b5edec..c0e9df6 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/AbstractDependencyDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/AbstractDependencyDataService.java
@@ -18,6 +18,8 @@
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.project.AbstractDependencyData;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
+import com.intellij.openapi.externalSystem.util.Order;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.*;
@@ -30,6 +32,7 @@
  * @author Denis Zhdanov
  * @since 4/14/13 11:21 PM
  */
+@Order(ExternalSystemConstants.BUILTIN_SERVICE_ORDER)
 public abstract class AbstractDependencyDataService<T extends AbstractDependencyData<?>> implements ProjectDataService<T> {
 
   public void removeData(@NotNull Collection<ExportableOrderEntry> toRemove, @NotNull final Module module, boolean synchronous) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java
index cbf1992..cd9177d 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java
@@ -11,12 +11,13 @@
 import com.intellij.openapi.externalSystem.service.project.ModuleAwareContentRoot;
 import com.intellij.openapi.externalSystem.service.project.ProjectStructureHelper;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
+import com.intellij.openapi.externalSystem.util.Order;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.roots.ContentEntry;
-import com.intellij.openapi.roots.ModifiableRootModel;
-import com.intellij.openapi.roots.ModuleRootManager;
+import com.intellij.openapi.roots.*;
 import com.intellij.openapi.vfs.LocalFileSystem;
+import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.containers.ContainerUtilRt;
 import org.jetbrains.annotations.NotNull;
 
@@ -30,6 +31,7 @@
  * @author Denis Zhdanov
  * @since 2/7/12 3:20 PM
  */
+@Order(ExternalSystemConstants.BUILTIN_SERVICE_ORDER)
 public class ContentRootDataService implements ProjectDataService<ContentRootData> {
 
   private static final Logger LOG = Logger.getInstance("#" + ContentRootDataService.class.getName());
@@ -84,28 +86,16 @@
         try {
           for (DataNode<ContentRootData> data : datas) {
             ContentRootData contentRoot = data.getData();
-            ContentEntry contentEntry = model.addContentEntry(toVfsUrl(contentRoot.getRootPath()));
+            ContentEntry contentEntry = findOrCreateContentRoot(model, contentRoot.getRootPath());
             LOG.info(String.format("Importing content root '%s' for module '%s'", contentRoot.getRootPath(), module.getName()));
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.SOURCE)) {
-              contentEntry.addSourceFolder(toVfsUrl(path), false);
-              LOG.info(String.format(
-                "Importing source root '%s' for content root '%s' of module '%s'",
-                path, contentRoot.getRootPath(), module.getName()
-              ));
+              createSourceRootIfAbsent(contentEntry, path, module.getName());
             }
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.TEST)) {
-              contentEntry.addSourceFolder(toVfsUrl(path), true);
-              LOG.info(String.format(
-                "Importing test root '%s' for content root '%s' of module '%s'",
-                path, contentRoot.getRootPath(), module.getName()
-              ));
+              createTestRootIfAbsent(contentEntry, path, module.getName());
             }
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.EXCLUDED)) {
-              contentEntry.addExcludeFolder(toVfsUrl(path));
-              LOG.info(String.format(
-                "Importing excluded root '%s' for content root '%s' of module '%s'",
-                path, contentRoot.getRootPath(), module.getName()
-              ));
+              createExcludedRootIfAbsent(contentEntry, path, module.getName());
             }
           }
         }
@@ -116,6 +106,91 @@
     });
   }
 
+  @NotNull
+  private static ContentEntry findOrCreateContentRoot(@NotNull ModifiableRootModel model, @NotNull String path) {
+    ContentEntry[] entries = model.getContentEntries();
+    if (entries == null) {
+      return model.addContentEntry(toVfsUrl(path));
+    }
+    
+    for (ContentEntry entry : entries) {
+      VirtualFile file = entry.getFile();
+      if (file == null) {
+        continue;
+      }
+      if (ExternalSystemApiUtil.getLocalFileSystemPath(file).equals(path)) {
+        return entry;
+      }
+    }
+    return model.addContentEntry(toVfsUrl(path));
+  }
+
+  private static void createSourceRootIfAbsent(@NotNull ContentEntry entry, @NotNull String path, @NotNull String moduleName) {
+    SourceFolder[] folders = entry.getSourceFolders();
+    if (folders == null) {
+      LOG.info(String.format("Importing source root '%s' for content root '%s' of module '%s'", path, entry.getUrl(), moduleName));
+      entry.addSourceFolder(toVfsUrl(path), false);
+      return;
+    }
+    for (SourceFolder folder : folders) {
+      if (folder.isTestSource()) {
+        continue;
+      }
+      VirtualFile file = folder.getFile();
+      if (file == null) {
+        continue;
+      }
+      if (ExternalSystemApiUtil.getLocalFileSystemPath(file).equals(path)) {
+        return;
+      }
+    }
+    LOG.info(String.format("Importing source root '%s' for content root '%s' of module '%s'", path, entry.getUrl(), moduleName));
+    entry.addSourceFolder(toVfsUrl(path), false);
+  }
+
+  private static void createExcludedRootIfAbsent(@NotNull ContentEntry entry, @NotNull String path, @NotNull String moduleName) {
+    ExcludeFolder[] folders = entry.getExcludeFolders();
+    if (folders == null) {
+      LOG.info(String.format("Importing excluded root '%s' for content root '%s' of module '%s'", path, entry.getUrl(), moduleName));
+      entry.addExcludeFolder(toVfsUrl(path));
+      return;
+    }
+    for (ExcludeFolder folder : folders) {
+      VirtualFile file = folder.getFile();
+      if (file == null) {
+        continue;
+      }
+      if (ExternalSystemApiUtil.getLocalFileSystemPath(file).equals(path)) {
+        return;
+      }
+    }
+    LOG.info(String.format("Importing excluded root '%s' for content root '%s' of module '%s'", path, entry.getUrl(), moduleName));
+    entry.addExcludeFolder(toVfsUrl(path));
+  }
+
+  private static void createTestRootIfAbsent(@NotNull ContentEntry entry, @NotNull String path, @NotNull String moduleName) {
+    SourceFolder[] folders = entry.getSourceFolders();
+    if (folders == null) {
+      LOG.info(String.format("Importing test root '%s' for content root '%s' of module '%s'", path, entry.getUrl(), moduleName));
+      entry.addSourceFolder(toVfsUrl(path), true);
+      return;
+    }
+    for (SourceFolder folder : folders) {
+      if (!folder.isTestSource()) {
+        continue;
+      }
+      VirtualFile file = folder.getFile();
+      if (file == null) {
+        continue;
+      }
+      if (ExternalSystemApiUtil.getLocalFileSystemPath(file).equals(path)) {
+        return;
+      }
+    }
+    LOG.info(String.format("Importing test root '%s' for content root '%s' of module '%s'", path, entry.getUrl(), moduleName));
+    entry.addSourceFolder(toVfsUrl(path), true);
+  }
+
   @Override
   public void removeData(@NotNull Collection<DataNode<ContentRootData>> toRemove, @NotNull Project project, boolean synchronous) {
     if (toRemove.isEmpty()) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDataService.java
index 7cec027..4b7bbbf 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDataService.java
@@ -11,7 +11,9 @@
 import com.intellij.openapi.externalSystem.service.project.PlatformFacade;
 import com.intellij.openapi.externalSystem.service.project.ProjectStructureHelper;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
 import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
+import com.intellij.openapi.externalSystem.util.Order;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.OrderRootType;
 import com.intellij.openapi.roots.libraries.Library;
@@ -25,18 +27,23 @@
 import org.jetbrains.annotations.NotNull;
 
 import java.io.File;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
 
 /**
  * @author Denis Zhdanov
  * @since 2/15/12 11:32 AM
  */
+@Order(ExternalSystemConstants.BUILTIN_SERVICE_ORDER)
 public class LibraryDataService implements ProjectDataService<LibraryData> {
 
   private static final Logger LOG = Logger.getInstance("#" + LibraryDataService.class.getName());
+  @NotNull public static final NotNullFunction<String, File> PATH_TO_FILE = new NotNullFunction<String, File>() {
+    @NotNull
+    @Override
+    public File fun(String path) {
+      return new File(path);
+    }
+  };
 
   @NotNull private final PlatformFacade                myPlatformFacade;
   @NotNull private final ProjectStructureHelper        myProjectStructureHelper;
@@ -65,19 +72,19 @@
   }
 
   public void importLibrary(@NotNull final LibraryData toImport, @NotNull final Project project, boolean synchronous) {
-    Map<OrderRootType, Collection<File>> libraryFiles = new HashMap<OrderRootType, Collection<File>>();
+    Map<OrderRootType, Collection<File>> libraryFiles = ContainerUtilRt.newHashMap();
     for (LibraryPathType pathType : LibraryPathType.values()) {
       final Set<String> paths = toImport.getPaths(pathType);
       if (paths.isEmpty()) {
         continue;
       }
-      libraryFiles.put(myLibraryPathTypeMapper.map(pathType), ContainerUtil.map(paths, new NotNullFunction<String, File>() {
-        @NotNull
-        @Override
-        public File fun(String path) {
-          return new File(path);
-        }
-      }));
+      libraryFiles.put(myLibraryPathTypeMapper.map(pathType), ContainerUtil.map(paths, PATH_TO_FILE));
+    }
+
+    Library library = myProjectStructureHelper.findIdeLibrary(toImport, project);
+    if (library != null) {
+      syncPaths(toImport, library, project, synchronous);
+      return;
     }
     importLibrary(toImport.getName(), toImport.getOwner(), libraryFiles, project, synchronous);
   }
@@ -183,13 +190,13 @@
     });
   }
 
-  public void syncPaths(@NotNull LibraryData externalLibrary,
+  public void syncPaths(@NotNull final LibraryData externalLibrary,
                         @NotNull final Library ideLibrary,
                         @NotNull Project project,
                         boolean synchronous)
   {
-    Set<String> toRemove = ContainerUtilRt.newHashSet();
-    Set<String> toAdd = ContainerUtilRt.newHashSet(externalLibrary.getPaths(LibraryPathType.BINARY));
+    final Set<String> toRemove = ContainerUtilRt.newHashSet();
+    final Set<String> toAdd = ContainerUtilRt.newHashSet(externalLibrary.getPaths(LibraryPathType.BINARY));
     for (VirtualFile ideFile : ideLibrary.getFiles(OrderRootType.CLASSES)) {
       String idePath = ExternalSystemApiUtil.getLocalFileSystemPath(ideFile);
       if (!toAdd.remove(idePath)) {
@@ -199,6 +206,22 @@
     if (toRemove.isEmpty() && toAdd.isEmpty()) {
       return;
     }
-    // TODO den implement
+    ExternalSystemApiUtil.executeProjectChangeAction(project, externalLibrary.getOwner(), ideLibrary, synchronous, new Runnable() {
+      @Override
+      public void run() {
+        Library.ModifiableModel model = ideLibrary.getModifiableModel();
+        try {
+          for (String path : toRemove) {
+            model.removeRoot(path, OrderRootType.CLASSES);
+          }
+          Map<OrderRootType, Collection<File>> roots = ContainerUtilRt.newHashMap();
+          roots.put(OrderRootType.CLASSES, ContainerUtil.map(toAdd, PATH_TO_FILE));
+          registerPaths(roots, model, externalLibrary.getName());
+        }
+        finally {
+          model.commit();
+        }
+      }
+    });
   }
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDependencyDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDependencyDataService.java
index 47d0628..4b246a4 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDependencyDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDependencyDataService.java
@@ -28,6 +28,8 @@
 import com.intellij.openapi.externalSystem.service.project.PlatformFacade;
 import com.intellij.openapi.externalSystem.service.project.ProjectStructureHelper;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
+import com.intellij.openapi.externalSystem.util.Order;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.ExportableOrderEntry;
@@ -51,6 +53,7 @@
  * @author Denis Zhdanov
  * @since 4/12/13 6:19 PM
  */
+@Order(ExternalSystemConstants.BUILTIN_SERVICE_ORDER)
 public class LibraryDependencyDataService extends AbstractDependencyDataService<LibraryDependencyData> {
 
   private static final Logger LOG = Logger.getInstance("#" + LibraryDependencyDataService.class.getName());
@@ -135,7 +138,6 @@
         }
 
         for (DataNode<LibraryDependencyData> dependencyNode : nodesToImport) {
-          ProjectStructureHelper helper = ServiceManager.getService(module.getProject(), ProjectStructureHelper.class);
           ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
           final ModifiableRootModel moduleRootModel = moduleRootManager.getModifiableModel();
           try {
@@ -146,7 +148,7 @@
               assert false;
               continue;
             }
-            LibraryOrderEntry orderEntry = helper.findIdeLibraryDependency(dependencyData.getName(), moduleRootModel);
+            LibraryOrderEntry orderEntry = myProjectStructureHelper.findIdeLibraryDependency(dependencyData.getName(), moduleRootModel);
             if (orderEntry == null) {
               // We need to get the most up-to-date Library object due to our project model restrictions.
               orderEntry = moduleRootModel.addLibraryEntry(library);
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDataService.java
index 0df8481..1f6cc95 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDataService.java
@@ -8,8 +8,11 @@
 import com.intellij.openapi.externalSystem.model.ProjectKeys;
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.project.ModuleData;
+import com.intellij.openapi.externalSystem.model.project.ProjectData;
 import com.intellij.openapi.externalSystem.service.project.ProjectStructureHelper;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
+import com.intellij.openapi.externalSystem.util.Order;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleManager;
 import com.intellij.openapi.project.Project;
@@ -24,6 +27,7 @@
 import java.io.File;
 import java.io.IOException;
 import java.util.Collection;
+import java.util.Iterator;
 import java.util.Map;
 import java.util.concurrent.TimeUnit;
 
@@ -33,6 +37,7 @@
  * @author Denis Zhdanov
  * @since 2/7/12 2:49 PM
  */
+@Order(ExternalSystemConstants.BUILTIN_SERVICE_ORDER)
 public class ModuleDataService implements ProjectDataService<ModuleData> {
 
   private static final Logger LOG = Logger.getInstance("#" + ModuleDataService.class.getName());
@@ -71,7 +76,11 @@
     Runnable task = new Runnable() {
       @Override
       public void run() {
-        removeExistingModulesConfigs(toImport, project);
+        final Collection<DataNode<ModuleData>> toCreate = filterExistingModules(toImport, project);
+        if (toCreate.isEmpty()) {
+          return;
+        }
+        removeExistingModulesConfigs(toCreate, project);
         Application application = ApplicationManager.getApplication();
         final Map<DataNode<ModuleData>, Module> moduleMappings = ContainerUtilRt.newHashMap();
         application.runWriteAction(new Runnable() {
@@ -80,7 +89,7 @@
             final ModuleManager moduleManager = ModuleManager.getInstance(project);
             final ProjectEntityChangeListener publisher
               = project.getMessageBus().syncPublisher(ProjectEntityChangeListener.TOPIC);
-            for (DataNode<ModuleData> module : toImport) {
+            for (DataNode<ModuleData> module : toCreate) {
               publisher.onChangeStart(module, module.getData().getOwner());
               try {
                 importModule(moduleManager, module);
@@ -99,6 +108,12 @@
             ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(created);
             final ModifiableRootModel moduleRootModel = moduleRootManager.getModifiableModel();
             moduleRootModel.inheritSdk();
+            created.setOption(ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY, data.getOwner().toString());
+            ProjectData projectData = module.getData(ProjectKeys.PROJECT);
+            if (projectData != null) {
+              created.setOption(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY, projectData.getLinkedExternalProjectPath());
+            }
+            
             RootPolicy<Object> visitor = new RootPolicy<Object>() {
               @Override
               public Object visitLibraryOrderEntry(LibraryOrderEntry libraryOrderEntry, Object value) {
@@ -133,6 +148,19 @@
     }
   }
 
+  @NotNull
+  private Collection<DataNode<ModuleData>> filterExistingModules(@NotNull Collection<DataNode<ModuleData>> modules,
+                                                                 @NotNull Project project)
+  {
+    Collection<DataNode<ModuleData>> result = ContainerUtilRt.newArrayList();
+    for (DataNode<ModuleData> node : modules) {
+      if (myProjectStructureHelper.findIdeModule(node.getData(), project) == null) {
+        result.add(node);
+      }
+    }
+    return result;
+  }
+
   private void removeExistingModulesConfigs(@NotNull final Collection<DataNode<ModuleData>> nodes, @NotNull Project project) {
     if (nodes.isEmpty()) {
       return;
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDependencyDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDependencyDataService.java
index 0b3d4b2..c2a680a 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDependencyDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDependencyDataService.java
@@ -25,6 +25,8 @@
 import com.intellij.openapi.externalSystem.model.project.ProjectData;
 import com.intellij.openapi.externalSystem.service.project.ProjectStructureHelper;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
+import com.intellij.openapi.externalSystem.util.Order;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.ExportableOrderEntry;
@@ -46,6 +48,7 @@
  * @author Denis Zhdanov
  * @since 4/15/13 8:37 AM
  */
+@Order(ExternalSystemConstants.BUILTIN_SERVICE_ORDER)
 public class ModuleDependencyDataService extends AbstractDependencyDataService<ModuleDependencyData> {
 
   private static final Logger LOG = Logger.getInstance("#" + ModuleDependencyDataService.class.getName());
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataServiceImpl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataServiceImpl.java
index 5a304f3..3ba386b 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataServiceImpl.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataServiceImpl.java
@@ -21,6 +21,8 @@
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.project.ProjectData;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
+import com.intellij.openapi.externalSystem.util.Order;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.project.ex.ProjectEx;
 import org.jetbrains.annotations.NotNull;
@@ -31,6 +33,7 @@
  * @author Denis Zhdanov
  * @since 2/21/13 2:40 PM
  */
+@Order(ExternalSystemConstants.BUILTIN_SERVICE_ORDER)
 public class ProjectDataServiceImpl implements ProjectDataService<ProjectData> {
 
   @NotNull
@@ -41,6 +44,9 @@
 
   @Override
   public void importData(@NotNull Collection<DataNode<ProjectData>> toImport, @NotNull Project project, boolean synchronous) {
+    if (!ExternalSystemApiUtil.isNewProjectConstruction()) {
+      return;
+    }
     if (toImport.size() != 1) {
       throw new IllegalArgumentException(String.format("Expected to get a single project but got %d: %s", toImport.size(), toImport));
     }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java
index 464cd56..d5eb306 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java
@@ -6,12 +6,13 @@
 import com.intellij.openapi.externalSystem.model.ProjectKeys;
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.project.LibraryData;
-import com.intellij.openapi.externalSystem.model.project.ModuleData;
 import com.intellij.openapi.externalSystem.model.project.ProjectData;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemResolveProjectTask;
+import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback;
 import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataManager;
-import com.intellij.openapi.externalSystem.service.settings.AbstractExternalProjectConfigurable;
+import com.intellij.openapi.externalSystem.service.settings.AbstractImportFromExternalSystemControl;
 import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
+import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
 import com.intellij.openapi.externalSystem.settings.ExternalSystemSettingsManager;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
 import com.intellij.openapi.externalSystem.util.ExternalSystemBundle;
@@ -50,7 +51,7 @@
  * @since 8/1/11 1:29 PM
  */
 @SuppressWarnings("MethodMayBeStatic")
-public abstract class AbstractExternalProjectImportBuilder<C extends AbstractExternalProjectConfigurable>
+public abstract class AbstractExternalProjectImportBuilder<C extends AbstractImportFromExternalSystemControl>
   extends ProjectImportBuilder<DataNode<ProjectData>>
 {
 
@@ -58,20 +59,19 @@
 
   @NotNull private final ExternalSystemSettingsManager mySettingsManager;
   @NotNull private final ProjectDataManager            myProjectDataManager;
-  @NotNull private final C                             myConfigurable;
+  @NotNull private final C                             myControl;
   @NotNull private final ProjectSystemId               myExternalSystemId;
 
   private DataNode<ProjectData> myExternalProjectNode;
 
   public AbstractExternalProjectImportBuilder(@NotNull ExternalSystemSettingsManager settingsManager,
                                               @NotNull ProjectDataManager projectDataManager,
-                                              @NotNull C configurable,
+                                              @NotNull C control,
                                               @NotNull ProjectSystemId externalSystemId)
   {
     mySettingsManager = settingsManager;
     myProjectDataManager = projectDataManager;
-    myConfigurable = configurable;
-    myConfigurable.setAlwaysShowLinkedProjectControls(true);
+    myControl = control;
     myExternalSystemId = externalSystemId;
   }
 
@@ -94,13 +94,8 @@
   }
 
   @NotNull
-  public C getConfigurable() {
-    return myConfigurable;
-  }
-
-  @NotNull
-  public ProjectSystemId getExternalSystemId() {
-    return myExternalSystemId;
+  public C getControl() {
+    return myControl;
   }
 
   @NotNull
@@ -109,9 +104,9 @@
   }
 
   public void prepare(@NotNull WizardContext context) {
-    myConfigurable.reset();
+    myControl.reset();
     String pathToUse = context.getProjectFileDirectory();
-    myConfigurable.setLinkedExternalProjectPath(pathToUse);
+    myControl.setLinkedProjectPath(pathToUse);
     doPrepare(context);
   }
 
@@ -129,13 +124,16 @@
       beforeCommit(externalProjectNode, project);
     }
     StartupManager.getInstance(project).runWhenProjectIsInitialized(new Runnable() {
+      @SuppressWarnings("unchecked")
       @Override
       public void run() {
-        AbstractExternalSystemSettings settings = mySettingsManager.getSettings(project, myExternalSystemId);
-        final String linkedProjectPath = myConfigurable.getLinkedExternalProjectPath();
+        AbstractExternalSystemSettings systemSettings = mySettingsManager.getSettings(project, myExternalSystemId);
+        ExternalProjectSettings projectSettings = myControl.getProjectSettings().clone();
+        final String linkedProjectPath = projectSettings.getExternalProjectPath();
         assert linkedProjectPath != null;
-        settings.setLinkedExternalProjectPath(linkedProjectPath);
-        settings.setUseAutoImport(myConfigurable.isUseAutoImport());
+        Set<ExternalProjectSettings> projects = ContainerUtilRt.newHashSet(systemSettings.getLinkedProjectsSettings());
+        projects.add(projectSettings);
+        systemSettings.setLinkedProjectsSettings(projects);
         onProjectInit(project);
 
         if (externalProjectNode != null) {
@@ -145,8 +143,7 @@
               ProjectRootManagerEx.getInstanceEx(project).mergeRootsChangesDuring(new Runnable() {
                 @Override
                 public void run() {
-                  Collection<DataNode<ModuleData>> modules = ExternalSystemApiUtil.findAll(externalProjectNode, ProjectKeys.MODULE);
-                  myProjectDataManager.importData(ProjectKeys.MODULE, modules, project, true);
+                  myProjectDataManager.importData(externalProjectNode.getKey(), Collections.singleton(externalProjectNode), project, true);
                 }
               });
             }
@@ -213,56 +210,44 @@
         ProjectRootManagerEx.getInstanceEx(project).mergeRootsChangesDuring(new Runnable() {
           @Override
           public void run() {
-            // Clean existing libraries (if any).
-            LibraryTable projectLibraryTable = ProjectLibraryTable.getInstance(project);
-            if (projectLibraryTable == null) {
-              LOG.warn(
-                "Can't resolve external dependencies of the target gradle project (" + project + "). Reason: project "
-                + "library table is undefined"
-              );
-              return;
-            }
-            LibraryTable.ModifiableModel model = projectLibraryTable.getModifiableModel();
-            try {
-              for (Library library : model.getLibraries()) {
-                model.removeLibrary(library);
+            if (ExternalSystemApiUtil.isNewProjectConstruction()) {
+              // Clean existing libraries (if any).
+              LibraryTable projectLibraryTable = ProjectLibraryTable.getInstance(project);
+              if (projectLibraryTable == null) {
+                LOG.warn(
+                  "Can't resolve external dependencies of the target gradle project (" + project + "). Reason: project "
+                  + "library table is undefined"
+                );
+                return;
               }
-            }
-            finally {
-              model.commit();
+              LibraryTable.ModifiableModel model = projectLibraryTable.getModifiableModel();
+              try {
+                for (Library library : model.getLibraries()) {
+                  model.removeLibrary(library);
+                }
+              }
+              finally {
+                model.commit();
+              }
             }
 
             // Register libraries.
             Set<DataNode<?>> toImport = ContainerUtilRt.newHashSet();
             toImport.add(projectWithResolvedLibraries);
             myProjectDataManager.importData(toImport, project, false);
-            // TODO den uncomment
-            //ProjectStructureChangesModel changesModel = ServiceManager.getService(project, ProjectStructureChangesModel.class);
-            //changesModel.update(projectWithResolvedLibraries);
           }
         });
-        // TODO den uncomment
-        //ServiceManager.getService(project, UserProjectChangesCalculator.class).updateCurrentProjectState();
       }
     });
   }
 
   @Nullable
   private File getProjectFile() {
-    String path = myConfigurable.getLinkedExternalProjectPath();
+    String path = myControl.getProjectSettings().getExternalProjectPath();
     return path == null ? null : new File(path);
   }
 
   /**
-   * Is called to indicate that user changed path to the gradle project to import.
-   * 
-   * @param path      new directory path
-   */
-  public void setCurrentProjectPath(@NotNull String path) {
-    myConfigurable.setLinkedExternalProjectPath(path);
-  }
-
-  /**
    * Asks current builder to ensure that target gradle project is defined.
    *
    * @param wizardContext             current wizard context
@@ -275,30 +260,41 @@
       throw new ConfigurationException(ExternalSystemBundle.message("error.project.undefined"));
     }
     projectFile = getExternalProjectConfigToUse(projectFile);
-    final Ref<String> errorReason = new Ref<String>();
-    final Ref<String> errorDetails = new Ref<String>();
+    final Ref<ConfigurationException> error = new Ref<ConfigurationException>();
+    ExternalProjectRefreshCallback callback = new ExternalProjectRefreshCallback() {
+      @Override
+      public void onSuccess(@Nullable DataNode<ProjectData> externalProject) {
+        myExternalProjectNode = externalProject;
+      }
+
+      @Override
+      public void onFailure(@NotNull String errorMessage, @Nullable String errorDetails) {
+        if (!StringUtil.isEmpty(errorDetails)) {
+          LOG.warn(errorDetails);
+        }
+        error.set(new ConfigurationException(ExternalSystemBundle.message("error.resolve.with.reason", errorMessage),
+                                             ExternalSystemBundle.message("error.resolve.generic")));
+      }
+    };
     try {
       final Project project = getProject(wizardContext);
-      myExternalProjectNode = ExternalSystemUtil.refreshProject(project, myExternalSystemId, projectFile.getAbsolutePath(), errorReason,
-                                                                errorDetails, false, true);
+      ExternalSystemUtil.refreshProject(
+        project,
+        myExternalSystemId,
+        projectFile.getAbsolutePath(),
+        callback,
+        false,
+        true
+      );
     }
     catch (IllegalArgumentException e) {
       throw new ConfigurationException(e.getMessage(), ExternalSystemBundle.message("error.cannot.parse.project", externalSystemName));
     }
     if (myExternalProjectNode == null) {
-      final String details = errorDetails.get();
-      if (!StringUtil.isEmpty(details)) {
-        LOG.warn(details);
+      ConfigurationException exception = error.get();
+      if (exception != null) {
+        throw exception;
       }
-      String errorMessage;
-      String reason = errorReason.get();
-      if (reason == null) {
-        errorMessage = ExternalSystemBundle.message("error.resolve.generic.without.reason", externalSystemName, projectFile.getPath());
-      }
-      else {
-        errorMessage = ExternalSystemBundle.message("error.resolve.with.reason", reason);
-      }
-      throw new ConfigurationException(errorMessage, ExternalSystemBundle.message("error.resolve.generic"));
     }
     else {
       applyProjectSettings(wizardContext);
@@ -319,12 +315,15 @@
    * @param context  storage for the project/module settings.
    */
   public void applyProjectSettings(@NotNull WizardContext context) {
+    if (!ExternalSystemApiUtil.isNewProjectConstruction()) {
+      return;
+    }
     if (myExternalProjectNode == null) {
       assert false;
       return;
     }
     context.setProjectName(myExternalProjectNode.getData().getName());
-    context.setProjectFileDirectory(myExternalProjectNode.getData().getProjectFileDirectoryPath());
+    context.setProjectFileDirectory(myExternalProjectNode.getData().getIdeProjectFileDirectoryPath());
     applyExtraSettings(context);
   }
 
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/SelectExternalProjectStepBase.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/SelectExternalProjectStepBase.java
index b549ce3..98aa584 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/SelectExternalProjectStepBase.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/SelectExternalProjectStepBase.java
@@ -1,10 +1,8 @@
 package com.intellij.openapi.externalSystem.service.project.wizard;
 
 import com.intellij.ide.util.projectWizard.WizardContext;
-import com.intellij.openapi.externalSystem.service.settings.AbstractExternalProjectConfigurable;
-import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil;
+import com.intellij.openapi.externalSystem.service.settings.AbstractImportFromExternalSystemControl;
 import com.intellij.openapi.options.ConfigurationException;
-import com.intellij.openapi.ui.MessageType;
 import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
@@ -27,7 +25,7 @@
 
   private final JPanel myComponent = new JPanel(new BorderLayout());
 
-  @NotNull private AbstractExternalProjectConfigurable myConfigurable;
+  @NotNull private AbstractImportFromExternalSystemControl myControl;
 
   private boolean myGradleSettingsInitialised;
 
@@ -59,10 +57,7 @@
 
   @Override
   public boolean validate() throws ConfigurationException {
-    AbstractExternalProjectConfigurable.ValidationError error = myConfigurable.validate();
-    if (error != null) {
-      ExternalSystemUiUtil.showBalloon(error.problemHolder, MessageType.ERROR, error.message);
-    }
+    myControl.apply();
     storeCurrentSettings();
     AbstractExternalProjectImportBuilder builder = getBuilder();
     if (builder == null) {
@@ -78,10 +73,7 @@
   }
 
   private void storeCurrentSettings() {
-    if (myConfigurable.isModified()) {
-      myConfigurable.apply();
-    }
-    final String projectPath = myConfigurable.getLinkedExternalProjectPath();
+    final String projectPath = myControl.getProjectSettings().getExternalProjectPath();
     if (projectPath != null) {
       final File parent = new File(projectPath).getParentFile();
       if (parent != null) {
@@ -96,8 +88,8 @@
       return;
     }
     builder.prepare(getWizardContext());
-    myConfigurable = builder.getConfigurable();
-    myComponent.add(myConfigurable.createComponent());
+    myControl = builder.getControl();
+    myComponent.add(myControl.getComponent());
     myGradleSettingsInitialised = true;
   }
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectConfigurable.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectConfigurable.java
deleted file mode 100644
index a704f8e..0000000
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectConfigurable.java
+++ /dev/null
@@ -1,309 +0,0 @@
-/*
- * 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.openapi.externalSystem.service.settings;
-
-import com.intellij.openapi.externalSystem.model.ProjectSystemId;
-import com.intellij.openapi.externalSystem.model.settings.LocationSettingType;
-import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
-import com.intellij.openapi.externalSystem.settings.ExternalSystemSettingsListener;
-import com.intellij.openapi.externalSystem.util.ExternalSystemBundle;
-import com.intellij.openapi.fileChooser.FileChooserDescriptor;
-import com.intellij.openapi.options.Configurable;
-import com.intellij.openapi.options.SearchableConfigurable;
-import com.intellij.openapi.project.Project;
-import com.intellij.openapi.project.ProjectManager;
-import com.intellij.openapi.ui.TextComponentAccessor;
-import com.intellij.openapi.ui.TextFieldWithBrowseButton;
-import com.intellij.openapi.util.Comparing;
-import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.ui.components.JBCheckBox;
-import com.intellij.ui.components.JBLabel;
-import com.intellij.util.ui.GridBag;
-import org.jetbrains.annotations.Nls;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import javax.swing.*;
-import java.awt.*;
-
-/**
- * // TODO den add doc
- * Allows to configure gradle settings.
- * <p/>
- * Basically, it has two modes:
- * <pre>
- * <ul>
- *   <li>no information about linked gradle project is available (e.g. gradle settings are opened from welcome screen);</li>
- *   <li>information about linked gradle project is available;</li>
- * </ul>
- * </pre>
- * The difference is in how we handle
- * <a href="http://www.gradle.org/docs/current/userguide/userguide_single.html#gradle_wrapper">gradle wrapper</a> settings - we
- * represent settings like 'use gradle wrapper whenever possible' at the former case and ask to explicitly define whether gradle
- * wrapper or particular local distribution should be used at the latest one.
- *
- * @author peter
- */
-public abstract class AbstractExternalProjectConfigurable
-  <L extends ExternalSystemSettingsListener, S extends AbstractExternalSystemSettings<L, S>>
-  implements SearchableConfigurable, Configurable.NoScroll
-{
-
-  @NotNull private final String myDisplayName;
-
-  @Nullable private final Project myProject;
-
-  @NotNull private JComponent                myComponent;
-  @NotNull private JLabel                    myLinkedExternalProjectLabel;
-  @NotNull private TextFieldWithBrowseButton myLinkedExternalProjectPathField;
-  @NotNull private JBCheckBox                myUseAutoImportBox;
-
-  private final boolean myTestMode;
-  private boolean myAlwaysShowLinkedProjectControls;
-
-  @SuppressWarnings("AbstractMethodCallInConstructor")
-  protected AbstractExternalProjectConfigurable(@Nullable Project project, @NotNull ProjectSystemId externalSystemId, boolean testMode) {
-    myProject = project;
-    myTestMode = testMode;
-    myDisplayName = getSystemName(externalSystemId);
-    myLinkedExternalProjectLabel = new JBLabel(ExternalSystemBundle.message("settings.label.select.project", myDisplayName));
-    myLinkedExternalProjectPathField = initLinkedGradleProjectPathControl(testMode);
-    myUseAutoImportBox = new JBCheckBox(ExternalSystemBundle.message("settings.label.use.auto.import"));
-  }
-
-  @NotNull
-  protected static GridBag getLabelConstraints() {
-    return new GridBag().anchor(GridBagConstraints.WEST).weightx(0);
-  }
-
-  @NotNull
-  protected static GridBag getFillLineConstraints() {
-    return new GridBag().weightx(1).coverLine().fillCellHorizontally().anchor(GridBagConstraints.WEST);
-  }
-
-  @NotNull
-  private static String getSystemName(@NotNull ProjectSystemId externalSystemId) {
-    return StringUtil.capitalize(externalSystemId.toString().toLowerCase());
-  }
-
-  @NotNull
-  public TextFieldWithBrowseButton getLinkedExternalProjectPathField() {
-    return myLinkedExternalProjectPathField;
-  }
-
-  @Nullable
-  public String getLinkedExternalProjectPath() {
-    return myLinkedExternalProjectPathField.getText();
-  }
-
-  public void setLinkedExternalProjectPath(@NotNull String path) {
-    myLinkedExternalProjectPathField.setText(path);
-  }
-
-  public boolean isUseAutoImport() {
-    return myUseAutoImportBox.isSelected();
-  }
-
-  @NotNull
-  public JBCheckBox getUseAutoImportBox() {
-    return myUseAutoImportBox;
-  }
-
-  // TODO den add doc
-  @Nullable
-  public abstract ValidationError validate();
-
-  // TODO den add doc
-  @NotNull
-  protected abstract JComponent buildContent(boolean testMode);
-
-  protected abstract void fillContent(@NotNull JComponent content);
-
-  @NotNull
-  protected abstract FileChooserDescriptor getLinkedProjectConfigDescriptor();
-
-  @NotNull
-  protected abstract S getSettings(@NotNull Project project);
-
-  @NotNull
-  private TextFieldWithBrowseButton initLinkedGradleProjectPathControl(boolean testMode) {
-    TextFieldWithBrowseButton result = new TextFieldWithBrowseButton();
-
-    FileChooserDescriptor fileChooserDescriptor = testMode ? new FileChooserDescriptor(true, false, false, false, false, false)
-                                                           : getLinkedProjectConfigDescriptor();
-
-    result.addBrowseFolderListener(
-      "",
-      ExternalSystemBundle.message("settings.label.select.project", myDisplayName),
-      myProject,
-      fileChooserDescriptor,
-      TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
-      false
-    );
-    return result;
-  }
-
-  @Override
-  public Runnable enableSearch(String option) {
-    return null;
-  }
-
-  @Nullable
-  public Project getProject() {
-    return myProject;
-  }
-
-  @NotNull
-  @Nls
-  @Override
-  public String getDisplayName() {
-    return myDisplayName;
-  }
-
-  @SuppressWarnings("ConstantConditions")
-  @Override
-  public JComponent createComponent() {
-    if (myComponent == null) {
-      myComponent = buildContent(myTestMode);
-      myComponent.add(myLinkedExternalProjectLabel, getLabelConstraints());
-      myComponent.add(myLinkedExternalProjectPathField, getFillLineConstraints());
-      myComponent.add(myUseAutoImportBox, getFillLineConstraints());
-      fillContent(myComponent);
-      myComponent.add(Box.createVerticalGlue(), new GridBag().weightx(1).weighty(1).fillCell().coverLine());
-    }
-    return myComponent;
-  }
-
-  public boolean isAlwaysShowLinkedProjectControls() {
-    return myAlwaysShowLinkedProjectControls;
-  }
-
-  public void setAlwaysShowLinkedProjectControls(boolean alwaysShowLinkedProjectControls) {
-    myAlwaysShowLinkedProjectControls = alwaysShowLinkedProjectControls;
-  }
-
-  @Override
-  public boolean isModified() {
-    if (myProject == null) {
-      return false;
-    }
-
-    S settings = getSettings(myProject);
-
-    if (!Comparing.equal(normalizePath(myLinkedExternalProjectPathField.getText()), normalizePath(settings.getLinkedExternalProjectPath()))) {
-      return true;
-    }
-
-    if (myUseAutoImportBox.isSelected() != settings.isUseAutoImport()) {
-      return true;
-    }
-
-    return isExtraSettingModified();
-  }
-
-  protected abstract boolean isExtraSettingModified();
-
-  @Nullable
-  protected static String normalizePath(@Nullable String s) {
-    return StringUtil.isEmpty(s) ? null : s;
-  }
-
-  @Override
-  public void apply() {
-    if (myProject == null) {
-      return;
-    }
-
-    String linkedProjectPath = myLinkedExternalProjectPathField.getText();
-    boolean useAutoImport = myUseAutoImportBox.isSelected();
-    doApply(linkedProjectPath, useAutoImport);
-  }
-
-  protected void doApply(@NotNull String linkedExternalProjectPath, boolean useAutoImport) {
-    if (myProject == null) {
-      return;
-    }
-    getSettings(myProject).setLinkedExternalProjectPath(linkedExternalProjectPath);
-    getSettings(myProject).setUseAutoImport(useAutoImport);
-  }
-
-  @Nullable
-  protected static String getPathToUse(boolean modifiedByUser, @Nullable String settingsPath, @Nullable String uiPath) {
-    if (modifiedByUser) {
-      return StringUtil.isEmpty(uiPath) ? null : uiPath;
-    }
-    else {
-      // There are two possible cases:
-      //   *) the path is initially set from settings and hasn't been modified; 
-      //   *) the path is undefined at the settings and has been deduced;
-      if (Comparing.equal(normalizePath(settingsPath), normalizePath(uiPath))) {
-        return settingsPath;
-      }
-      else {
-        return null;
-      }
-    }
-  }
-
-  @Override
-  public void reset() {
-    Project project = myProject;
-    if (myProject == null) {
-      project = ProjectManager.getInstance().getDefaultProject();
-    }
-
-    S settings = getSettings(project);
-    String linkedExternalProjectPath = myLinkedExternalProjectPathField.getText();
-    if (StringUtil.isEmpty(linkedExternalProjectPath)) {
-      linkedExternalProjectPath = settings.getLinkedExternalProjectPath();
-    }
-    myLinkedExternalProjectLabel.setVisible(myAlwaysShowLinkedProjectControls || !project.isDefault());
-    myLinkedExternalProjectPathField.setVisible(myAlwaysShowLinkedProjectControls || !project.isDefault());
-    if (linkedExternalProjectPath != null) {
-      myLinkedExternalProjectPathField.setText(linkedExternalProjectPath);
-    }
-
-    myUseAutoImportBox.setSelected(settings.isUseAutoImport());
-    doReset();
-  }
-
-  protected abstract void doReset();
-
-  protected static void useColorForPath(@NotNull LocationSettingType type, @NotNull TextFieldWithBrowseButton pathControl) {
-    Color c = type == LocationSettingType.DEDUCED ? UIManager.getColor("TextField.inactiveForeground")
-                                                  : UIManager.getColor("TextField.foreground");
-    pathControl.getTextField().setForeground(c);
-  }
-
-  @SuppressWarnings("ConstantConditions")
-  @Override
-  public void disposeUIResources() {
-    myComponent = null;
-    myLinkedExternalProjectLabel = null;
-    myLinkedExternalProjectPathField = null;
-    myUseAutoImportBox = null;
-  }
-
-  public static class ValidationError {
-    @NotNull public final String     message;
-    @NotNull public final JComponent problemHolder;
-
-    public ValidationError(@NotNull String message, @NotNull JComponent problemHolder) {
-      this.message = message;
-      this.problemHolder = problemHolder;
-    }
-  }
-}
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java
new file mode 100644
index 0000000..dd01eec
--- /dev/null
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright 2000-2013 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.openapi.externalSystem.service.settings;
+
+import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
+import com.intellij.openapi.externalSystem.util.ExternalSystemBundle;
+import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil;
+import com.intellij.openapi.externalSystem.util.PaintAwarePanel;
+import com.intellij.ui.components.JBCheckBox;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Templates class for managing single external project settings (single ide project might contain multiple bindings to external
+ * projects, e.g. one module is backed by a single external project and couple of others are backed by a single external multi-project).
+ * 
+ * @author Denis Zhdanov
+ * @since 4/24/13 1:19 PM
+ */
+public abstract class AbstractExternalProjectSettingsControl<S extends ExternalProjectSettings> implements ExternalSettingsControl<S> {
+
+  @NotNull private S myInitialSettings;
+
+  private JBCheckBox myUseAutoImportBox;
+
+  protected AbstractExternalProjectSettingsControl(@NotNull S initialSettings) {
+    myInitialSettings = initialSettings;
+  }
+
+  @NotNull
+  protected S getInitialSettings() {
+    return myInitialSettings;
+  }
+
+  @Override
+  public void fillUi(@NotNull PaintAwarePanel canvas, int indentLevel) {
+    myUseAutoImportBox = new JBCheckBox(ExternalSystemBundle.message("settings.label.use.auto.import"));
+    canvas.add(myUseAutoImportBox, ExternalSystemUiUtil.getFillLineConstraints(indentLevel));
+    fillExtraControls(canvas, indentLevel); 
+  }
+  
+  protected abstract void fillExtraControls(@NotNull PaintAwarePanel content, int indentLevel);
+
+  public boolean isModified() {
+    return myUseAutoImportBox.isSelected() != getInitialSettings().isUseAutoImport() || isExtraSettingModified();
+  }
+
+  protected abstract boolean isExtraSettingModified();
+
+  public void reset() {
+    myUseAutoImportBox.setSelected(getInitialSettings().isUseAutoImport());
+    resetExtraSettings();
+  }
+
+  protected abstract void resetExtraSettings();
+
+  @Override
+  @Nullable
+  public String apply(@NotNull S settings) {
+    settings.setUseAutoImport(myUseAutoImportBox.isSelected());
+    settings.setExternalProjectPath(myInitialSettings.getExternalProjectPath());
+    return applyExtraSettings(settings);
+  }
+  
+  @Nullable
+  protected abstract String applyExtraSettings(@NotNull S settings);
+
+  public void disposeUIResources() {
+    myUseAutoImportBox = null;
+    disposeExtraUIControls();
+  }
+  
+  protected abstract void disposeExtraUIControls();
+
+  @Override
+  public void showUi(boolean show) {
+    myUseAutoImportBox.setVisible(show);
+    showExtraUi(show);
+  }
+
+  protected abstract void showExtraUi(boolean show);
+}
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalSystemConfigurable.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalSystemConfigurable.java
new file mode 100644
index 0000000..8bdac11
--- /dev/null
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalSystemConfigurable.java
@@ -0,0 +1,274 @@
+/*
+ * Copyright 2000-2013 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.openapi.externalSystem.service.settings;
+
+import com.intellij.openapi.externalSystem.ExternalSystemManager;
+import com.intellij.openapi.externalSystem.model.ProjectSystemId;
+import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
+import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
+import com.intellij.openapi.externalSystem.settings.ExternalSystemSettingsListener;
+import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemBundle;
+import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil;
+import com.intellij.openapi.externalSystem.util.PaintAwarePanel;
+import com.intellij.openapi.options.Configurable;
+import com.intellij.openapi.options.ConfigurationException;
+import com.intellij.openapi.options.SearchableConfigurable;
+import com.intellij.openapi.project.Project;
+import com.intellij.ui.IdeBorderFactory;
+import com.intellij.ui.components.JBList;
+import com.intellij.ui.components.JBScrollPane;
+import com.intellij.util.containers.ContainerUtil;
+import com.intellij.util.containers.ContainerUtilRt;
+import org.jetbrains.annotations.Nls;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import javax.swing.*;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+import java.awt.*;
+import java.io.File;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Base class that simplifies external system settings management.
+ * <p/>
+ * The general idea is to provide a control which looks like below:
+ * <pre>
+ *    ----------------------------------------------
+ *   |   linked external projects list              |
+ *   |----------------------------------------------
+ *   |   linked project-specific settings           |
+ *   |----------------------------------------------
+ *   |   external system-wide settings (optional)   |
+      ----------------------------------------------
+ * </pre>
+ * 
+ * @author Denis Zhdanov
+ * @since 4/30/13 12:50 PM
+ */
+public abstract class AbstractExternalSystemConfigurable<
+  ProjectSettings extends ExternalProjectSettings,
+  L extends ExternalSystemSettingsListener<ProjectSettings>,
+  SystemSettings extends AbstractExternalSystemSettings<ProjectSettings, L>
+  > implements SearchableConfigurable, Configurable.NoScroll
+{
+
+  @NotNull private final List<ExternalSettingsControl<ProjectSettings>> myProjectSettingsControls = ContainerUtilRt.newArrayList();
+
+  @NotNull private final ProjectSystemId myExternalSystemId;
+  @NotNull private final Project         myProject;
+
+  @Nullable private ExternalSettingsControl<SystemSettings> mySystemSettingsControl;
+  @Nullable private ExternalSettingsControl<ProjectSettings> myActiveProjectSettingsControl;
+
+  private PaintAwarePanel  myComponent;
+  private JBList           myProjectsList;
+  private DefaultListModel myProjectsModel;
+
+  protected AbstractExternalSystemConfigurable(@NotNull Project project, @NotNull ProjectSystemId externalSystemId) {
+    myProject = project;
+    myExternalSystemId = externalSystemId;
+  }
+
+  @Nullable
+  @Override
+  public Runnable enableSearch(String option) {
+    return null;
+  }
+
+  @Nls
+  @Override
+  public String getDisplayName() {
+    return ExternalSystemApiUtil.toReadableName(myExternalSystemId);
+  }
+
+  @Nullable
+  @Override
+  public JComponent createComponent() {
+    if (myComponent == null) {
+      myComponent = new PaintAwarePanel(new GridBagLayout());
+      SystemSettings settings = getSettings();
+      prepareProjectSettings(settings);
+      prepareSystemSettings(settings);
+      ExternalSystemUiUtil.fillBottom(myComponent);
+    }
+    return myComponent;
+  }
+
+  @SuppressWarnings("unchecked")
+  @NotNull
+  private SystemSettings getSettings() {
+    ExternalSystemManager<ProjectSettings, L, SystemSettings, ?, ?> manager
+      = (ExternalSystemManager<ProjectSettings, L, SystemSettings, ?, ?>)ExternalSystemApiUtil.getManager(myExternalSystemId);
+    assert manager != null;
+    return manager.getSettingsProvider().fun(myProject);
+  }
+
+  @SuppressWarnings("unchecked")
+  private void prepareProjectSettings(@NotNull SystemSettings s) {
+    myProjectsModel = new DefaultListModel();
+    myProjectsList = new JBList(myProjectsModel);
+    myProjectsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
+
+    String externalSystemName = ExternalSystemApiUtil.toReadableName(myExternalSystemId);
+    addTitle(ExternalSystemBundle.message("settings.title.linked.projects", externalSystemName));
+    myComponent.add(new JBScrollPane(myProjectsList), ExternalSystemUiUtil.getFillLineConstraints(1));
+    
+    addTitle(ExternalSystemBundle.message("settings.title.project.settings"));
+    List<ProjectSettings> settings = ContainerUtilRt.newArrayList(s.getLinkedProjectsSettings());
+    myProjectsList.setVisibleRowCount(Math.max(3, Math.min(5, settings.size())));
+    ContainerUtil.sort(settings, new Comparator<ProjectSettings>() {
+      @Override
+      public int compare(ProjectSettings s1, ProjectSettings s2) {
+        return getProjectName(s1.getExternalProjectPath()).compareTo(getProjectName(s2.getExternalProjectPath()));
+      }
+    });
+
+    myProjectSettingsControls.clear();
+    for (ProjectSettings setting : settings) {
+      ExternalSettingsControl<ProjectSettings> control = createProjectSettingsControl(setting);
+      control.fillUi(myComponent, 1);
+      myProjectsModel.addElement(getProjectName(setting.getExternalProjectPath()));
+      myProjectSettingsControls.add(control);
+      control.showUi(false);
+    }
+
+    myProjectsList.addListSelectionListener(new ListSelectionListener() {
+      @SuppressWarnings("unchecked")
+      @Override
+      public void valueChanged(ListSelectionEvent e) {
+        if (e.getValueIsAdjusting()) {
+          return;
+        }
+        int i = myProjectsList.getSelectedIndex();
+        if (i < 0) {
+          return;
+        }
+        if (myActiveProjectSettingsControl != null) {
+          myActiveProjectSettingsControl.showUi(false);
+        }
+        myActiveProjectSettingsControl = myProjectSettingsControls.get(i);
+        myActiveProjectSettingsControl.showUi(true);
+      }
+    });
+
+    
+    if (!myProjectsModel.isEmpty()) {
+      addTitle(ExternalSystemBundle.message("settings.title.system.settings", externalSystemName));
+      myProjectsList.setSelectedIndex(0);
+    }
+  }
+  
+  private void addTitle(@NotNull String title) {
+    JPanel panel = new JPanel(new GridBagLayout());
+    panel.setBorder(IdeBorderFactory.createTitledBorder(title, false, new Insets(ExternalSystemUiUtil.INSETS, 0, 0, 0)));
+    myComponent.add(panel, ExternalSystemUiUtil.getFillLineConstraints(0));
+  }
+
+  /**
+   * Creates a control for managing given project settings.
+   * 
+   * @param settings  target external project settings
+   * @return          control for managing given project settings
+   */
+  @NotNull
+  protected abstract ExternalSettingsControl<ProjectSettings> createProjectSettingsControl(@NotNull ProjectSettings settings);
+  
+  @NotNull
+  protected String getProjectName(@NotNull String path) {
+    return new File(path).getParentFile().getName();
+  }
+
+  private void prepareSystemSettings(@NotNull SystemSettings s) {
+    mySystemSettingsControl = createSystemSettingsControl(s);
+    if (mySystemSettingsControl != null) {
+      mySystemSettingsControl.fillUi(myComponent, 1);
+    }
+  }
+
+  /**
+   * Creates a control for managing given system-level settings (if any).
+   * 
+   * @param settings  target system settings
+   * @return          a control for managing given system-level settings;
+   *                  <code>null</code> if current external system doesn't have system-level settings (only project-level settings)
+   */
+  @Nullable
+  protected abstract ExternalSettingsControl<SystemSettings> createSystemSettingsControl(@NotNull SystemSettings settings); 
+
+  @Override
+  public boolean isModified() {
+    for (ExternalSettingsControl<ProjectSettings> control : myProjectSettingsControls) {
+      if (control.isModified()) {
+        return true;
+      }
+    }
+    return mySystemSettingsControl != null && mySystemSettingsControl.isModified();
+  }
+
+  @Override
+  public void apply() throws ConfigurationException {
+    SystemSettings systemSettings = getSettings();
+    L publisher = systemSettings.getPublisher();
+    publisher.onBulkChangeStart();
+    try {
+      List<ProjectSettings> projectSettings = ContainerUtilRt.newArrayList();
+      for (ExternalSettingsControl<ProjectSettings> control : myProjectSettingsControls) {
+        ProjectSettings s = newProjectSettings();
+        control.apply(s);
+        projectSettings.add(s);
+      }
+      systemSettings.setLinkedProjectsSettings(projectSettings);
+      if (mySystemSettingsControl != null) {
+        mySystemSettingsControl.apply(systemSettings);
+      }
+    }
+    finally {
+      publisher.onBulkChangeEnd();
+    }
+  }
+
+  /**
+   * @return    new empty project-level settings object
+   */
+  @NotNull
+  protected abstract ProjectSettings newProjectSettings();
+
+  @Override
+  public void reset() {
+    for (ExternalSettingsControl<ProjectSettings> control : myProjectSettingsControls) {
+      control.reset();
+    }
+    if (mySystemSettingsControl != null) {
+      mySystemSettingsControl.reset();
+    }
+  }
+
+  @Override
+  public void disposeUIResources() {
+    for (ExternalSettingsControl<ProjectSettings> control : myProjectSettingsControls) {
+      control.disposeUIResources();
+    }
+    myProjectSettingsControls.clear();
+    myComponent = null;
+    myProjectsList = null;
+    myProjectsModel = null;
+    mySystemSettingsControl = null;
+  }
+}
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractImportFromExternalSystemControl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractImportFromExternalSystemControl.java
new file mode 100644
index 0000000..097e5cb
--- /dev/null
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractImportFromExternalSystemControl.java
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2000-2013 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.openapi.externalSystem.service.settings;
+
+import com.intellij.openapi.externalSystem.model.ProjectSystemId;
+import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
+import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
+import com.intellij.openapi.externalSystem.settings.ExternalSystemSettingsListener;
+import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemBundle;
+import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil;
+import com.intellij.openapi.externalSystem.util.PaintAwarePanel;
+import com.intellij.openapi.fileChooser.FileChooserDescriptor;
+import com.intellij.openapi.options.ConfigurationException;
+import com.intellij.openapi.ui.TextComponentAccessor;
+import com.intellij.openapi.ui.TextFieldWithBrowseButton;
+import com.intellij.openapi.util.text.StringUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import javax.swing.*;
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+import java.awt.*;
+
+/**
+ * A control which knows how to manage settings of external project being imported.
+ * 
+ * @author Denis Zhdanov
+ * @since 4/30/13 2:33 PM
+ */
+public abstract class AbstractImportFromExternalSystemControl<
+  ProjectSettings extends ExternalProjectSettings,
+  L extends ExternalSystemSettingsListener<ProjectSettings>,
+  SystemSettings extends AbstractExternalSystemSettings<ProjectSettings, L>>
+{
+  @NotNull private final SystemSettings  mySystemSettings;
+  @NotNull private final ProjectSettings myProjectSettings;
+
+  @NotNull private final PaintAwarePanel           myComponent              = new PaintAwarePanel(new GridBagLayout());
+  @NotNull private final TextFieldWithBrowseButton myLinkedProjectPathField = new TextFieldWithBrowseButton();
+
+  @NotNull private final  ExternalSettingsControl<ProjectSettings> myProjectSettingsControl;
+  @Nullable private final ExternalSettingsControl<SystemSettings>  mySystemSettingsControl;
+
+  @SuppressWarnings("AbstractMethodCallInConstructor")
+  protected AbstractImportFromExternalSystemControl(@NotNull ProjectSystemId externalSystemId,
+                                                    @NotNull SystemSettings systemSettings,
+                                                    @NotNull ProjectSettings projectSettings)
+  {
+    mySystemSettings = systemSettings;
+    myProjectSettings = projectSettings;
+    myProjectSettingsControl = createProjectSettingsControl(myProjectSettings);
+    mySystemSettingsControl = createSystemSettingsControl(mySystemSettings);
+
+    String name = ExternalSystemApiUtil.toReadableName(externalSystemId);
+    JLabel linkedProjectPathLabel = new JLabel(ExternalSystemBundle.message("settings.label.select.project", name));
+    FileChooserDescriptor fileChooserDescriptor = getLinkedProjectChooserDescriptor();
+
+    myLinkedProjectPathField.addBrowseFolderListener(
+      "",
+      ExternalSystemBundle.message("settings.label.select.project", ExternalSystemApiUtil.toReadableName(externalSystemId)),
+      null,
+      fileChooserDescriptor,
+      TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
+      false
+    );
+    myLinkedProjectPathField.getTextField().getDocument().addDocumentListener(new DocumentListener() {
+      @Override
+      public void insertUpdate(DocumentEvent e) {
+        onLinkedProjectPathChange(myLinkedProjectPathField.getText());
+      }
+
+      @Override
+      public void removeUpdate(DocumentEvent e) {
+        onLinkedProjectPathChange(myLinkedProjectPathField.getText());
+      }
+
+      @Override
+      public void changedUpdate(DocumentEvent e) {
+        onLinkedProjectPathChange(myLinkedProjectPathField.getText());
+      }
+    });
+    
+    myComponent.add(linkedProjectPathLabel, ExternalSystemUiUtil.getLabelConstraints(0));
+    myComponent.add(myLinkedProjectPathField, ExternalSystemUiUtil.getFillLineConstraints(0));
+    myProjectSettingsControl.fillUi(myComponent, 0);
+    if (mySystemSettingsControl != null) {
+      mySystemSettingsControl.fillUi(myComponent, 0);
+    }
+    ExternalSystemUiUtil.fillBottom(myComponent);
+  }
+
+  @NotNull
+  protected abstract FileChooserDescriptor getLinkedProjectChooserDescriptor();
+
+  protected abstract void onLinkedProjectPathChange(@NotNull String path);
+
+  /**
+   * Creates a control for managing given project settings.
+   *
+   * @param settings  target external project settings
+   * @return          control for managing given project settings
+   */
+  @NotNull
+  protected abstract ExternalSettingsControl<ProjectSettings> createProjectSettingsControl(@NotNull ProjectSettings settings);
+
+  /**
+   * Creates a control for managing given system-level settings (if any).
+   *
+   * @param settings  target system settings
+   * @return          a control for managing given system-level settings;
+   *                  <code>null</code> if current external system doesn't have system-level settings (only project-level settings)
+   */
+  @Nullable
+  protected abstract ExternalSettingsControl<SystemSettings> createSystemSettingsControl(@NotNull SystemSettings settings);
+
+  @NotNull
+  public JComponent getComponent() {
+    return myComponent;
+  }
+
+  @NotNull
+  public ExternalSettingsControl<ProjectSettings> getProjectSettingsControl() {
+    return myProjectSettingsControl;
+  }
+
+  public void setLinkedProjectPath(@NotNull String path) {
+    myProjectSettings.setExternalProjectPath(path);
+    myLinkedProjectPathField.setText(path);
+  }
+
+  @NotNull
+  public ProjectSettings getProjectSettings() {
+    return myProjectSettings;
+  }
+
+  public void reset() {
+    myLinkedProjectPathField.setText("");
+    myProjectSettingsControl.reset();
+    if (mySystemSettingsControl != null) {
+      mySystemSettingsControl.reset();
+    }
+  }
+
+  public void apply() throws ConfigurationException {
+    String linkedProjectPath = myLinkedProjectPathField.getText();
+    if (StringUtil.isEmpty(linkedProjectPath)) {
+      throw new ConfigurationException(ExternalSystemBundle.message("error.project.undefined"));
+    }
+    myProjectSettings.setExternalProjectPath(linkedProjectPath);
+
+    String errorMessage = myProjectSettingsControl.apply(myProjectSettings);
+    if (errorMessage != null) {
+      throw new ConfigurationException(errorMessage);
+    }
+
+    if (mySystemSettingsControl != null) {
+      errorMessage = mySystemSettingsControl.apply(mySystemSettings);
+      if (errorMessage != null) {
+        throw new ConfigurationException(errorMessage);
+      }
+    }
+  }
+}
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/ExternalSettingsControl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/ExternalSettingsControl.java
new file mode 100644
index 0000000..b3f5a93
--- /dev/null
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/ExternalSettingsControl.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2000-2013 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.openapi.externalSystem.service.settings;
+
+import com.intellij.openapi.externalSystem.util.PaintAwarePanel;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.awt.*;
+
+/**
+ * Defines contract for a component which knows how to manage particular settings.
+ * 
+ * @author Denis Zhdanov
+ * @since 4/28/13 12:15 AM
+ * @param <S>  settings type
+ */
+public interface ExternalSettingsControl<S> {
+
+  /**
+   * Adds current control-specific UI controls to the given canvas.
+   * <p/>
+   * <b>Note:</b> given canvas component is expected to be managed by a {@link GridBagLayout}. That is the reason on why we use
+   * this method instead of a method like 'JComponent getComponent()' - there is a possible case that given canvas has components
+   * from more than one control and we might want them to be aligned.
+   * 
+   * @param canvas        container to use as a holder for UI components specific to the current control
+   * @param indentLevel   a hint on how much UI components added by the current control should be indented
+   */
+  void fillUi(@NotNull PaintAwarePanel canvas, int indentLevel);
+
+  /**
+   * Asks current control to reset its state to the initial one.
+   */
+  void reset();
+
+  /**
+   * @return    <code>true</code> if settings exposed by the current control have been modified; <code>false</code> otherwise
+   */
+  boolean isModified();
+
+  /**
+   * Asks current control to fill given settings with the current user-defined values.
+   * 
+   * @param settings  settings holder
+   * @return          <code>null</code> if all is ok; an error message describing the problem otherwise (e.g. an obligatory setting
+   *                  is undefined)
+   */
+  @Nullable
+  String apply(@NotNull S settings);
+
+  void disposeUIResources();
+
+  /**
+   * Hides/shows {@link #fillUi(PaintAwarePanel, int) components added by the current control}.
+   * 
+   * @param show  flag which indicates if current control' components should be visible
+   */
+  void showUi(boolean show);
+}
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/settings/ExternalSystemSettingsManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/settings/ExternalSystemSettingsManager.java
index c3acd21..4aea3bd 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/settings/ExternalSystemSettingsManager.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/settings/ExternalSystemSettingsManager.java
@@ -21,6 +21,7 @@
 import com.intellij.openapi.externalSystem.service.DisposableExternalSystemService;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.NotNullLazyValue;
+import com.intellij.openapi.util.Pair;
 import com.intellij.util.Function;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
@@ -39,7 +40,7 @@
     @Override
     protected Holder compute() {
       Holder result = new Holder();
-      for (ExternalSystemManager<?, ?, ?, ?> manager : ExternalSystemManager.EP_NAME.getExtensions()) {
+      for (ExternalSystemManager<?, ?, ?, ?, ?> manager : ExternalSystemManager.EP_NAME.getExtensions()) {
         result.register(manager);
       }
       return result;
@@ -81,18 +82,20 @@
   
   @SuppressWarnings("unchecked")
   public <S extends ExternalSystemExecutionSettings> S getExecutionSettings(@NotNull Project project,
+                                                                            @NotNull String linkedProjectPath,
                                                                             @NotNull ProjectSystemId externalSystemId)
     throws IllegalArgumentException
   {
     Holder holder = myHolder.getValue();
-    Function<Project, ? extends ExternalSystemExecutionSettings> provider = holder.executionSettingsProviders.get(externalSystemId);
+    Function<Pair<Project, String>, ? extends ExternalSystemExecutionSettings> provider
+      = holder.executionSettingsProviders.get(externalSystemId);
     if (provider == null) {
       throw new IllegalArgumentException(String.format(
         "Can't retrieve execution settings for external system with id '%s'. Reason: no such system is registered. Known systems: %s",
         externalSystemId, holder.executionSettingsProviders.keySet()
       ));
     }
-    return (S)provider.fun(project);
+    return (S)provider.fun(Pair.create(project, linkedProjectPath));
   }
   
   @Override
@@ -110,15 +113,16 @@
       = ContainerUtil.newConcurrentMap();
 
     @NotNull
-    public final ConcurrentMap<ProjectSystemId, Function<Project, ? extends ExternalSystemExecutionSettings>> executionSettingsProviders
+    public final ConcurrentMap<ProjectSystemId, Function<Pair<Project, String>, ? extends ExternalSystemExecutionSettings>>
+      executionSettingsProviders
       = ContainerUtil.newConcurrentMap();
-    
-    public void register(@NotNull ExternalSystemManager<?, ?, ?, ?> manager) {
+
+    public void register(@NotNull ExternalSystemManager<?, ?, ?, ?, ?> manager) {
       settingsProviders.put(manager.getSystemId(), manager.getSettingsProvider());
       localSettingsProviders.put(manager.getSystemId(), manager.getLocalSettingsProvider());
       executionSettingsProviders.put(manager.getSystemId(), manager.getExecutionSettingsProvider());
     }
-    
+
     public void clear(@NotNull ProjectSystemId externalSystemId) {
       settingsProviders.remove(externalSystemId);
       localSettingsProviders.remove(externalSystemId);
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUiUtil.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUiUtil.java
index 8a7135c..d13b309 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUiUtil.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUiUtil.java
@@ -21,6 +21,7 @@
 import com.intellij.openapi.ui.popup.BalloonBuilder;
 import com.intellij.openapi.ui.popup.JBPopupFactory;
 import com.intellij.ui.awt.RelativePoint;
+import com.intellij.util.ui.GridBag;
 import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
@@ -33,6 +34,11 @@
  */
 public class ExternalSystemUiUtil {
 
+  public static final int INSETS = 7;
+
+  private ExternalSystemUiUtil() {
+  }
+
   /**
    * Asks to show balloon that contains information related to the given component.
    *
@@ -42,8 +48,8 @@
    */
   public static void showBalloon(@NotNull JComponent component, @NotNull MessageType messageType, @NotNull String message) {
     final BalloonBuilder builder = JBPopupFactory.getInstance().createHtmlTextBalloonBuilder(message, messageType, null)
-                                                 .setDisposable(ApplicationManager.getApplication())
-                                                 .setFadeoutTime(TimeUnit.SECONDS.toMillis(1));
+      .setDisposable(ApplicationManager.getApplication())
+      .setFadeoutTime(TimeUnit.SECONDS.toMillis(1));
     Balloon balloon = builder.createBalloon();
     Dimension size = component.getSize();
     Balloon.Position position;
@@ -60,4 +66,20 @@
     }
     balloon.show(new RelativePoint(component, new Point(x, y)), position);
   }
+
+  @NotNull
+  public static GridBag getLabelConstraints(int indentLevel) {
+    Insets insets = new Insets(INSETS, INSETS + INSETS * indentLevel, 0, INSETS);
+    return new GridBag().anchor(GridBagConstraints.WEST).weightx(0).insets(insets);
+  }
+
+  @NotNull
+  public static GridBag getFillLineConstraints(int indentLevel) {
+    Insets insets = new Insets(INSETS, INSETS + INSETS * indentLevel, 0, INSETS);
+    return new GridBag().weightx(1).coverLine().fillCellHorizontally().anchor(GridBagConstraints.WEST).insets(insets);
+  }
+
+  public static void fillBottom(@NotNull JComponent component) {
+    component.add(Box.createVerticalGlue(), new GridBag().weightx(1).weighty(1).fillCell().coverLine());
+  }
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java
index 0f5fa14..30f0d69 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java
@@ -20,34 +20,31 @@
 import com.intellij.openapi.actionSystem.DataKey;
 import com.intellij.openapi.actionSystem.DataProvider;
 import com.intellij.openapi.actionSystem.PlatformDataKeys;
-import com.intellij.openapi.application.PathManager;
 import com.intellij.openapi.components.ServiceManager;
-import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.externalSystem.ExternalSystemManager;
 import com.intellij.openapi.externalSystem.model.DataNode;
 import com.intellij.openapi.externalSystem.model.ExternalSystemException;
+import com.intellij.openapi.externalSystem.model.ProjectKeys;
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
+import com.intellij.openapi.externalSystem.model.project.ModuleData;
 import com.intellij.openapi.externalSystem.model.project.ProjectData;
-import com.intellij.openapi.externalSystem.model.project.ProjectEntityData;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemResolveProjectTask;
-import com.intellij.openapi.externalSystem.service.project.ModuleAwareContentRoot;
+import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback;
+import com.intellij.openapi.externalSystem.service.project.PlatformFacade;
+import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataManager;
 import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
-import com.intellij.openapi.externalSystem.settings.ExternalSystemSettingsManager;
+import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.progress.ProgressIndicator;
 import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.progress.Task;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.roots.LibraryOrderEntry;
-import com.intellij.openapi.roots.ModuleOrderEntry;
-import com.intellij.openapi.roots.libraries.Library;
-import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.wm.ToolWindow;
 import com.intellij.openapi.wm.ToolWindowManager;
 import com.intellij.ui.content.Content;
 import com.intellij.ui.content.ContentManager;
-import com.intellij.util.Consumer;
-import com.intellij.util.PathsList;
+import com.intellij.util.containers.ContainerUtilRt;
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -55,6 +52,10 @@
 import javax.swing.*;
 import java.io.PrintWriter;
 import java.io.StringWriter;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
 
 /**
  * @author Denis Zhdanov
@@ -62,58 +63,9 @@
  */
 public class ExternalSystemUtil {
 
-  private static final Logger LOG = Logger.getInstance("#" + ExternalSystemUtil.class.getName());
-
   private ExternalSystemUtil() {
   }
 
-  /**
-   * Tries to dispatch given entity via the given visitor.
-   *
-   * @param entity   intellij project entity candidate to dispatch
-   * @param visitor  dispatch callback to use for the given entity
-   */
-  public static void dispatch(@Nullable Object entity, @NotNull IdeEntityVisitor visitor) {
-    if (entity instanceof Project) {
-      visitor.visit(((Project)entity));
-    }
-    else if (entity instanceof Module) {
-      visitor.visit(((Module)entity));
-    }
-    else if (entity instanceof ModuleAwareContentRoot) {
-      visitor.visit(((ModuleAwareContentRoot)entity));
-    }
-    else if (entity instanceof LibraryOrderEntry) {
-      visitor.visit(((LibraryOrderEntry)entity));
-    }
-    else if (entity instanceof ModuleOrderEntry) {
-      visitor.visit(((ModuleOrderEntry)entity));
-    }
-    else if (entity instanceof Library) {
-      visitor.visit(((Library)entity));
-    }
-  }
-
-  @NotNull
-  public static ProjectSystemId detectOwner(@Nullable ProjectEntityData externalEntity, @Nullable Object ideEntity) {
-    if (ideEntity != null) {
-      return ProjectSystemId.IDE;
-    }
-    else if (externalEntity != null) {
-      return externalEntity.getOwner();
-    }
-    else {
-      throw new RuntimeException(String.format(
-        "Can't detect owner system for the given arguments: external=%s, ide=%s", externalEntity, ideEntity
-      ));
-    }
-  }
-
-  @NotNull
-  public static String getOutdatedEntityName(@NotNull String entityName, @NotNull String gradleVersion, @NotNull String ideVersion) {
-    return String.format("%s (%s -> %s)", entityName, ideVersion, gradleVersion);
-  }
-
   @Nullable
   public static <T> T getToolWindowElement(@NotNull Class<T> clazz,
                                            @Nullable DataContext context,
@@ -199,46 +151,58 @@
     }
   }
 
-  public static void refreshProject(@NotNull Project project, @NotNull ProjectSystemId externalSystemId) {
-    refreshProject(project, externalSystemId, new Ref<String>());
-  }
-
-  public static void refreshProject(@NotNull Project project,
-                                    @NotNull ProjectSystemId externalSystemId,
-                                    @NotNull final Consumer<String> errorCallback)
-  {
-    final Ref<String> errorMessageHolder = new Ref<String>() {
-      @Override
-      public void set(@Nullable String value) {
-        if (value != null) {
-          errorCallback.consume(value);
-        }
-      }
-    };
-    refreshProject(project, externalSystemId, errorMessageHolder);
-  }
-
-  public static void refreshProject(@NotNull Project project,
-                                    @NotNull ProjectSystemId externalSystemId,
-                                    @NotNull final Ref<String> errorMessageHolder)
-  {
-    ExternalSystemSettingsManager settingsManager = ServiceManager.getService(ExternalSystemSettingsManager.class);
-    AbstractExternalSystemSettings settings = settingsManager.getSettings(project, externalSystemId);
-    final String linkedProjectPath = settings.getLinkedExternalProjectPath();
-    if (StringUtil.isEmpty(linkedProjectPath)) {
+  /**
+   * Asks to refresh all external projects of the target external system linked to the given ide project.
+   * <p/>
+   * 'Refresh' here means 'obtain the most up-to-date version and apply it to the ide'. 
+   * 
+   * @param project           target ide project
+   * @param externalSystemId  target external system which projects should be refreshed
+   */
+  public static void refreshProjects(@NotNull final Project project, @NotNull ProjectSystemId externalSystemId) {
+    ExternalSystemManager<?,?,?,?,?> manager = ExternalSystemApiUtil.getManager(externalSystemId);
+    if (manager == null) {
       return;
     }
-    assert linkedProjectPath != null;
-    Ref<String> errorDetailsHolder = new Ref<String>() {
+    AbstractExternalSystemSettings<?, ?> settings = manager.getSettingsProvider().fun(project);
+    Collection<? extends ExternalProjectSettings> projectsSettings = settings.getLinkedProjectsSettings();
+    if (projectsSettings.isEmpty()) {
+      return;
+    }
+
+    final ProjectDataManager projectDataManager = ServiceManager.getService(ProjectDataManager.class);
+    final Set<String> externalModuleNames = ContainerUtilRt.newHashSet();
+    ExternalProjectRefreshCallback callback = new ExternalProjectRefreshCallback() {
       @Override
-      public void set(@Nullable String error) {
-        if (!StringUtil.isEmpty(error)) {
-          assert error != null;
-          LOG.warn(error);
+      public void onSuccess(@Nullable DataNode<ProjectData> externalProject) {
+        if (externalProject == null) {
+          return;
         }
+        Collection<DataNode<ModuleData>> moduleNodes = ExternalSystemApiUtil.findAll(externalProject, ProjectKeys.MODULE);
+        for (DataNode<ModuleData> node : moduleNodes) {
+          externalModuleNames.add(node.getData().getName());
+        }
+        projectDataManager.importData(externalProject.getKey(), Collections.singleton(externalProject), project, false);
+      }
+
+      @Override
+      public void onFailure(@NotNull String errorMessage, @Nullable String errorDetails) {
       }
     };
-    refreshProject(project, externalSystemId, linkedProjectPath, errorMessageHolder, errorDetailsHolder, true, false);
+    for (ExternalProjectSettings setting : projectsSettings) {
+      refreshProject(project, externalSystemId, setting.getExternalProjectPath(), callback, true, false);
+    }
+    PlatformFacade platformFacade = ServiceManager.getService(PlatformFacade.class);
+    List<Module> orphanIdeModules = ContainerUtilRt.newArrayList();
+    String externalSystemIdAsString = externalSystemId.toString();
+    for (Module module : platformFacade.getModules(project)) {
+      String s = module.getOptionValue(ExternalSystemConstants.EXTERNAL_SYSTEM_ID_KEY);
+      if (externalSystemIdAsString.equals(s) && !externalModuleNames.contains(module.getName())) {
+        orphanIdeModules.add(module);
+      }
+    }
+    
+    // TODO den offer to remove orphan modules here
   }
 
   @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
@@ -256,21 +220,17 @@
    *
    * @param project             target intellij project to use
    * @param externalProjectPath path of the target gradle project's file
-   * @param errorMessageHolder  holder for the error message that describes a problem occurred during the refresh (if any)
-   * @param errorDetailsHolder  holder for the error details of the problem occurred during the refresh (if any)
+   * @param callback            callback to be notified on refresh result
    * @param resolveLibraries    flag that identifies whether gradle libraries should be resolved during the refresh
    * @return the most up-to-date gradle project (if any)
    */
-  @Nullable
-  public static DataNode<ProjectData> refreshProject(@NotNull final Project project,
-                                                     @NotNull final ProjectSystemId externalSystemId,
-                                                     @NotNull final String externalProjectPath,
-                                                     @NotNull final Ref<String> errorMessageHolder,
-                                                     @NotNull final Ref<String> errorDetailsHolder,
-                                                     final boolean resolveLibraries,
-                                                     final boolean modal)
+  public static void refreshProject(@NotNull final Project project,
+                                    @NotNull final ProjectSystemId externalSystemId,
+                                    @NotNull final String externalProjectPath,
+                                    @NotNull final ExternalProjectRefreshCallback callback,
+                                    final boolean resolveLibraries,
+                                    final boolean modal)
   {
-    final Ref<DataNode<ProjectData>> externalProject = new Ref<DataNode<ProjectData>>();
     final TaskUnderProgress refreshProjectStructureTask = new TaskUnderProgress() {
       @SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "IOResourceOpenedButNotSafelyClosed"})
       @Override
@@ -278,22 +238,20 @@
         ExternalSystemResolveProjectTask task
           = new ExternalSystemResolveProjectTask(externalSystemId, project, externalProjectPath, resolveLibraries);
         task.execute(indicator);
-        externalProject.set(task.getExternalProject());
         final Throwable error = task.getError();
         if (error == null) {
+          DataNode<ProjectData> externalProject = task.getExternalProject();
+          callback.onSuccess(externalProject);
           return;
         }
-        final String message = buildErrorMessage(error);
+        String message = buildErrorMessage(error);
         if (StringUtil.isEmpty(message)) {
-          errorMessageHolder.set(String.format(
+          message = String.format(
             "Can't resolve %s project at '%s'. Reason: %s",
             ExternalSystemApiUtil.toReadableName(externalSystemId), externalProjectPath, message
-          ));
+          );
         }
-        else {
-          errorMessageHolder.set(message);
-        }
-        errorDetailsHolder.set(extractDetails(error));
+        callback.onFailure(message, extractDetails(error));
       }
     };
 
@@ -335,12 +293,9 @@
         }
       }
     });
-    return externalProject.get();
   }
 
   private interface TaskUnderProgress {
     void execute(@NotNull ProgressIndicator indicator);
   }
-
-  
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/PaintAwarePanel.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/PaintAwarePanel.java
new file mode 100644
index 0000000..6d3d34d
--- /dev/null
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/PaintAwarePanel.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2000-2013 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.openapi.externalSystem.util;
+
+import com.intellij.util.Consumer;
+import com.intellij.util.containers.ContainerUtilRt;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import javax.swing.*;
+import java.awt.*;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * @author Denis Zhdanov
+ * @since 4/30/13 10:17 PM
+ */
+public class PaintAwarePanel extends JPanel {
+
+  @Nullable private Consumer<Graphics> myPaintCallback;
+
+  public PaintAwarePanel(LayoutManager layout) {
+    super(layout);
+  }
+
+  public PaintAwarePanel() {
+  }
+
+  @Override
+  public void paint(Graphics g) {
+    super.paint(g);
+    if (myPaintCallback != null) {
+      myPaintCallback.consume(g);
+    }
+  }
+
+  @Nullable
+  public Consumer<Graphics> getPaintCallback() {
+    return myPaintCallback;
+  }
+
+  public void setPaintCallback(@Nullable Consumer<Graphics> paintCallback) {
+    myPaintCallback = paintCallback;
+  }
+}
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
index 0d6c2d5..65b71c4 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
@@ -222,11 +222,13 @@
     Document document = editor.getDocument();
     int docLength = document.getTextLength();
     int psiLength = psiFile.getTextLength();
-    if (docLength == psiLength) {
+    boolean committed = !PsiDocumentManager.getInstance(psiFile.getProject()).isUncommited(document);
+    if (docLength == psiLength && committed) {
       return;
     }
 
     String message = "unsuccessful commit: (injected=" +(editor instanceof EditorWindow) +")";
+    message += "\ncommitted=" + committed;
     message += "\nfile=" + psiFile.getName();
     message += "\nfile class=" + psiFile.getClass();
     message += "\nlanguage=" + psiFile.getLanguage();
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionLookupArranger.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionLookupArranger.java
index 674a4d8..43b8968 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionLookupArranger.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionLookupArranger.java
@@ -184,7 +184,7 @@
                                     sortByPresentation(items, lookup) :
                                     fillModelByRelevance((LookupImpl)lookup, items, itemsBySorter, relevantSelection);
 
-    int toSelect = getItemToSelect(lookup, listModel, onExplicitAction, relevantSelection);
+    int toSelect = getItemToSelect((LookupImpl)lookup, listModel, onExplicitAction, relevantSelection);
     LOG.assertTrue(toSelect >= 0);
 
     addDummyItems(items.size() - listModel.size(), listModel);
@@ -320,8 +320,8 @@
     return new CompletionLookupArranger(myParameters, myProcess);
   }
 
-  private static int getItemToSelect(Lookup lookup, List<LookupElement> items, boolean onExplicitAction, @Nullable LookupElement mostRelevant) {
-    if (items.isEmpty() || !lookup.isFocused()) {
+  private static int getItemToSelect(LookupImpl lookup, List<LookupElement> items, boolean onExplicitAction, @Nullable LookupElement mostRelevant) {
+    if (items.isEmpty() || !lookup.isFocused() && !lookup.isSemiFocused()) {
       return 0;
     }
 
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByBlockCommentHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByBlockCommentHandler.java
index 0057cf1..7fe93ed 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByBlockCommentHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/generation/CommentByBlockCommentHandler.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -202,7 +202,7 @@
         }
       }
       else {
-        if (!isWhiteSpaceOrComment(element)) {
+        if (!isWhiteSpaceOrComment(element, range)) {
           return false;
         }
       }
@@ -225,17 +225,18 @@
   }
 
   private boolean isWhiteSpaceOrComment(@NotNull PsiElement element, @NotNull TextRange range) {
-    TextRange intersection = range.intersection(element.getTextRange());
+    final TextRange textRange = element.getTextRange();
+    TextRange intersection = range.intersection(textRange);
     if (intersection == null) {
       return false;
     }
-    intersection = TextRange.from(Math.max(intersection.getStartOffset() - element.getTextRange().getStartOffset(), 0),
-                                  Math.min(intersection.getEndOffset() - element.getTextRange().getStartOffset(), element.getTextRange().getLength()));
+    intersection = TextRange.create(Math.max(intersection.getStartOffset() - textRange.getStartOffset(), 0),
+                                    Math.min(intersection.getEndOffset() - textRange.getStartOffset(), textRange.getLength()));
     return isWhiteSpaceOrComment(element) ||
            intersection.substring(element.getText()).trim().length() == 0;
   }
 
-  private boolean isWhiteSpaceOrComment(PsiElement element) {
+  private static boolean isWhiteSpaceOrComment(PsiElement element) {
     return element instanceof PsiWhiteSpace ||
            PsiTreeUtil.getParentOfType(element, PsiComment.class, false) != null;
   }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionHandler.java
index 02ae9a8..3c0f95f 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupActionHandler.java
@@ -85,7 +85,7 @@
 
     static void executeDown(LookupImpl lookup) {
       if (!lookup.isFocused()) {
-        boolean semiFocused = CompletionPreview.hasPreview(lookup);
+        boolean semiFocused = lookup.isSemiFocused();
         lookup.setFocused(true);
         lookup.getList().setSelectedIndex(0);
         lookup.refreshUi(false, true);
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java
index 8124c1d..77f9fc2 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java
@@ -117,7 +117,7 @@
       boolean hasFocus) {
 
 
-    boolean nonFocusedSelection = isSelected && !myLookup.isFocused() && CompletionPreview.hasPreview(myLookup);
+    boolean nonFocusedSelection = isSelected && !myLookup.isFocused() && myLookup.isSemiFocused();
     if (!myLookup.isFocused()) {
       isSelected = false;
     }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
index 4fb5af0..9b1a0a6 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
@@ -267,12 +267,16 @@
   }
 
   public void setFocused(boolean focused) {
-    if (focused && !CompletionPreview.hasPreview(this)) {
+    if (focused && !isSemiFocused()) {
       CompletionPreview.installPreview(this);
     }
     myFocused = focused;
   }
 
+  public boolean isSemiFocused() {
+    return CompletionPreview.hasPreview(this);
+  }
+
   public boolean isCalculating() {
     return myCalculating;
   }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/actions/ChooseItemAction.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/actions/ChooseItemAction.java
index 058ed26..dd5d249 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/actions/ChooseItemAction.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/actions/ChooseItemAction.java
@@ -21,7 +21,6 @@
 import com.intellij.codeInsight.completion.CompletionService;
 import com.intellij.codeInsight.lookup.Lookup;
 import com.intellij.codeInsight.lookup.LookupManager;
-import com.intellij.codeInsight.lookup.impl.CompletionPreview;
 import com.intellij.codeInsight.lookup.impl.LookupImpl;
 import com.intellij.codeInsight.template.impl.ListTemplatesHandler;
 import com.intellij.codeInsight.template.impl.SurroundWithTemplateHandler;
@@ -79,7 +78,7 @@
       LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);
       if (lookup == null) return false;
       if (!lookup.isAvailableToUser()) return false;
-      if (focusedOnly && !CompletionPreview.hasPreview(lookup) && !lookup.isFocused()) return false;
+      if (focusedOnly && !lookup.isSemiFocused() && !lookup.isFocused()) return false;
       if (finishingChar == Lookup.NORMAL_SELECT_CHAR && hasTemplatePrefix(lookup, TemplateSettings.ENTER_CHAR) ||
           finishingChar == Lookup.REPLACE_SELECT_CHAR && hasTemplatePrefix(lookup, TemplateSettings.TAB_CHAR)) {
         return false;
diff --git a/platform/lang-impl/src/com/intellij/extapi/psi/StubPath.java b/platform/lang-impl/src/com/intellij/extapi/psi/StubPath.java
deleted file mode 100644
index 0ebd258..0000000
--- a/platform/lang-impl/src/com/intellij/extapi/psi/StubPath.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * 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.
- */
-
-/*
- * @author max
- */
-package com.intellij.extapi.psi;
-
-import com.intellij.psi.tree.IElementType;
-
-public class StubPath {
-  private final StubPath myParentPath;
-  private final String myId;
-  private final IElementType myType;
-
-
-  public StubPath(final StubPath parentPath, final String id, final IElementType type) {
-    myParentPath = parentPath;
-    myId = id;
-    myType = type;
-  }
-
-  public StubPath getParentPath() {
-    return myParentPath;
-  }
-
-
-  public String getId() {
-    return myId;
-  }
-
-  public IElementType getType() {
-    return myType;
-  }
-
-  public boolean equals(final Object o) {
-    if (this == o) return true;
-    if (!(o instanceof StubPath)) return false;
-
-    final StubPath stubPath = (StubPath)o;
-
-    if (!myId.equals(stubPath.myId)) return false;
-    if (myParentPath != null ? !myParentPath.equals(stubPath.myParentPath) : stubPath.myParentPath != null) return false;
-    if (!myType.equals(stubPath.myType)) return false;
-
-    return true;
-  }
-
-  public int hashCode() {
-    int result = (myParentPath != null ? myParentPath.hashCode() : 0);
-    result = 31 * result + myId.hashCode();
-    result = 31 * result + myType.hashCode();
-    return result;
-  }
-
-  public String toString() {
-    return (myParentPath != null ? myParentPath.toString() : "") + "::(" + myType.toString() + ":" + myId + ")";
-  }
-}
diff --git a/platform/lang-impl/src/com/intellij/extapi/psi/StubPathBuilder.java b/platform/lang-impl/src/com/intellij/extapi/psi/StubPathBuilder.java
deleted file mode 100644
index e2a7429..0000000
--- a/platform/lang-impl/src/com/intellij/extapi/psi/StubPathBuilder.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * 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.
- */
-
-/*
- * @author max
- */
-package com.intellij.extapi.psi;
-
-import com.intellij.lang.ASTNode;
-import com.intellij.openapi.util.Pair;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiFile;
-import com.intellij.psi.StubBasedPsiElement;
-import com.intellij.psi.impl.source.PsiFileImpl;
-import com.intellij.psi.stubs.*;
-import org.jetbrains.annotations.Nullable;
-
-import java.util.List;
-
-public class StubPathBuilder {
-  private StubPathBuilder() {
-  }
-
-  public static StubPath build(StubBasedPsiElement psi) {
-    if (psi instanceof PsiFile) {
-      return null;
-    }
-
-    final StubElement liveStub = psi.getStub();
-    if (liveStub != null) {
-      return build(liveStub);
-    }
-
-    return buildForPsi(psi, ((PsiFileImpl)psi.getContainingFile()).calcStubTree()).getFirst();
-  }
-
-
-  public static StubPath build(StubElement stub) {
-    if (stub instanceof PsiFileStub || stub == null) {
-      return null;
-    }
-
-    final IStubElementType type = stub.getStubType();
-    return new StubPath(build(stub.getParentStub()), type.getId(stub), type);
-  }
-
-  private static Pair<StubPath, StubElement> buildForPsi(PsiElement psi, StubTree tree) {
-    if (psi instanceof PsiFile) {
-      return new Pair<StubPath, StubElement>(null, tree.getRoot());
-    }
-
-    if (psi instanceof StubBasedPsiElement) {
-      final IStubElementType type = ((StubBasedPsiElement)psi).getElementType();
-      if (type.shouldCreateStub(psi.getNode())) {
-        final Pair<StubPath, StubElement> parentPair = buildForPsi(psi.getParent(), tree);
-
-        final StubElement parentStub = parentPair.getSecond();
-        final List<StubElement> childrenStubs = parentStub.getChildrenStubs();
-        for (StubElement childStub : childrenStubs) {
-          if (childStub.getPsi() == psi) {
-            final IStubElementType type1 = childStub.getStubType();
-            return new Pair<StubPath, StubElement>(new StubPath(parentPair.getFirst(), type1.getId(childStub), type1), childStub);
-          }
-        }
-
-        return new Pair<StubPath, StubElement>(null, null);
-      }
-    }
-
-    return buildForPsi(psi.getParent(), tree);
-  }
-
-  @Nullable
-  public static PsiElement resolve(PsiFile file, StubPath path) {
-    PsiFileImpl fileImpl = (PsiFileImpl)file;
-    StubTree tree = fileImpl.getStubTree();
-
-    boolean foreign = (tree == null);
-    if (foreign) {
-      tree = fileImpl.calcStubTree();
-    }
-
-    StubElement stub = resolveStub(tree, path);
-
-    if (foreign) {
-      final PsiElement cachedPsi = ((StubBase)stub).getCachedPsi();
-      if (cachedPsi != null) return cachedPsi;
-
-      final ASTNode ast = fileImpl.findTreeForStub(tree, stub);
-      return ast != null ? ast.getPsi() : null;
-    }
-    else {
-      return stub != null ? stub.getPsi() : null;
-    }
-  }
-
-  @Nullable
-  public static StubElement resolveStub(StubTree tree, StubPath path) {
-    if (path == null) {
-      return tree.getRoot();
-    }
-
-    StubElement parentStub = resolveStub(tree, path.getParentPath());
-    if (parentStub == null) {
-      return null;
-    }
-
-    final String id = path.getId();
-    final IStubElementType type = (IStubElementType)path.getType();
-    final List<StubElement> children = parentStub.getChildrenStubs();
-
-    if (id.startsWith("#")) {
-      int count = Integer.parseInt(id.substring(1));
-
-      for (StubElement child : children) {
-        if (child.getStubType() == type) {
-          count--;
-          if (count == 0) {
-            return child;
-          }
-        }
-      }
-      return null;
-    }
-
-    for (StubElement child : children) {
-      if (child.getStubType() == type && id.equals(type.getId(child))) {
-        return child;
-      }
-    }
-
-    return null;
-  }
-}
\ No newline at end of file
diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java
index 936a750..a51d5aa 100644
--- a/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java
+++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java
@@ -191,12 +191,12 @@
       memStorage.addBufferingStateListsner(new MemoryIndexStorage.BufferingStateListener() {
         @Override
         public void bufferingStateChanged(final boolean newState) {
-          ((StubIndexImpl)StubIndexImpl.getInstance()).setDataBufferingEnabled(newState);
+          ((StubIndexImpl)StubIndex.getInstance()).setDataBufferingEnabled(newState);
         }
 
         @Override
         public void memoryStorageCleared() {
-          ((StubIndexImpl)StubIndexImpl.getInstance()).cleanupMemoryStorage();
+          ((StubIndexImpl)StubIndex.getInstance()).cleanupMemoryStorage();
         }
       });
     }
diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java b/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java
index e9331cc..ffdc0ab 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java
@@ -262,7 +262,14 @@
         return;
       }
 
-      ChangeTrackingValueContainer<Value> cached = myCache.getIfCached(key);
+      ChangeTrackingValueContainer<Value> cached;
+      try {
+        l.lock();
+        cached = myCache.getIfCached(key);
+      } finally {
+        l.unlock();
+      }
+
       if (cached != null) {
         cached.addValue(inputId, value);
         return;
diff --git a/platform/platform-api/src/com/intellij/notification/Notification.java b/platform/platform-api/src/com/intellij/notification/Notification.java
index 7baeac1..5a538dc 100644
--- a/platform/platform-api/src/com/intellij/notification/Notification.java
+++ b/platform/platform-api/src/com/intellij/notification/Notification.java
@@ -38,6 +38,7 @@
   private final NotificationListener myListener;
   private final String myTitle;
   private boolean myExpired;
+  private Runnable myWhenExpired;
   private Boolean myImportant;
   private WeakReference<Balloon> myBalloonRef;
 
@@ -102,6 +103,14 @@
     NotificationsManager.getNotificationsManager().expire(this);
     hideBalloon();
     myExpired = true;
+
+    Runnable whenExpired = myWhenExpired;
+    if (whenExpired != null) whenExpired.run();
+  }
+
+  public Notification whenExpired(@Nullable Runnable whenExpired) {
+    myWhenExpired = whenExpired;
+    return this;
   }
 
   public void hideBalloon() {
diff --git a/platform/platform-impl/src/com/intellij/ide/actions/CreateLauncherScriptAction.java b/platform/platform-impl/src/com/intellij/ide/actions/CreateLauncherScriptAction.java
index a1bc98b..8644cd5 100644
--- a/platform/platform-impl/src/com/intellij/ide/actions/CreateLauncherScriptAction.java
+++ b/platform/platform-impl/src/com/intellij/ide/actions/CreateLauncherScriptAction.java
@@ -138,9 +138,11 @@
       final String productName = ApplicationNamesInfo.getInstance().getProductName().toLowerCase();
       runPath += "/bin/" + productName + ".sh";
     }
-    final String launcherContents = ExecUtil.loadTemplate(CreateLauncherScriptAction.class.getClassLoader(), "launcher.py",
+    String launcherContents = ExecUtil.loadTemplate(CreateLauncherScriptAction.class.getClassLoader(), "launcher.py",
                                                           newHashMap(asList("$CONFIG_PATH$", "$RUN_PATH$"),
                                                                      asList(PathManager.getConfigPath(), runPath)));
+
+    launcherContents = StringUtil.convertLineSeparators(launcherContents);
     return ExecUtil.createTempExecutableScript("launcher", "", launcherContents);
   }
 
diff --git a/platform/platform-impl/src/com/intellij/ide/actions/SaveDocumentAction.java b/platform/platform-impl/src/com/intellij/ide/actions/SaveDocumentAction.java
new file mode 100644
index 0000000..1ab3a7d
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/ide/actions/SaveDocumentAction.java
@@ -0,0 +1,31 @@
+package com.intellij.ide.actions;
+
+import com.intellij.openapi.actionSystem.AnAction;
+import com.intellij.openapi.actionSystem.AnActionEvent;
+import com.intellij.openapi.actionSystem.PlatformDataKeys;
+import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.fileEditor.FileDocumentManager;
+
+/**
+ * @author yole
+ */
+public class SaveDocumentAction extends AnAction {
+  @Override
+  public void actionPerformed(AnActionEvent e) {
+    Document doc = getDocument(e);
+    if (doc != null) {
+      FileDocumentManager.getInstance().saveDocument(doc);
+    }
+  }
+
+  @Override
+  public void update(AnActionEvent e) {
+    e.getPresentation().setEnabled(getDocument(e) != null);
+  }
+
+  private static Document getDocument(AnActionEvent e) {
+    Editor editor = e.getData(PlatformDataKeys.EDITOR);
+    return editor != null ? editor.getDocument() : null;
+  }
+}
diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java
index 05f0fd3..cf89596 100644
--- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java
+++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java
@@ -251,11 +251,11 @@
         UIUtil.invokeLaterIfNeeded(new Runnable() {
           public void run() {
             setDownloadStatus(false);
-            if (list != null && errorMessages.isEmpty()) {
+            if (list != null) {
               modifyPluginsList(list);
               propagateUpdates(list);
             }
-            else if (!errorMessages.isEmpty()) {
+            if (!errorMessages.isEmpty()) {
               if (0 == Messages.showOkCancelDialog(
                 IdeBundle.message("error.list.of.plugins.was.not.loaded", StringUtil.join(errorMessages, ", ")),
                 IdeBundle.message("title.plugins"),
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaComboBoxUI.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaComboBoxUI.java
index 745a1a4..577f8f8 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaComboBoxUI.java
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaComboBoxUI.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -23,6 +23,7 @@
 import javax.swing.*;
 import javax.swing.border.Border;
 import javax.swing.plaf.ComponentUI;
+import javax.swing.plaf.DimensionUIResource;
 import javax.swing.plaf.InsetsUIResource;
 import javax.swing.plaf.basic.BasicArrowButton;
 import javax.swing.plaf.basic.BasicComboBoxRenderer;
@@ -36,6 +37,12 @@
 @SuppressWarnings("GtkPreferredJComboBoxRenderer")
 public class DarculaComboBoxUI extends BasicComboBoxUI implements Border {
   private final JComboBox myComboBox;
+  // Flag for calculating the display size
+  private boolean myDisplaySizeDirty = true;
+
+  // Cached the size that the display needs to render the largest item
+  private Dimension myDisplaySizeCache = new Dimension(0, 0);
+  private Insets myPadding;
 
   public DarculaComboBoxUI(JComboBox comboBox) {
     super();
@@ -49,6 +56,12 @@
   }
 
   @Override
+  protected void installDefaults() {
+    super.installDefaults();
+    myPadding = UIManager.getInsets("ComboBox.padding");
+  }
+
+  @Override
   protected ListCellRenderer createRenderer() {
     return new BasicComboBoxRenderer.UIResource() {
       @Override
@@ -89,18 +102,25 @@
         final int xU = w / 4;
         final int yU = h / 4;
         final Path2D.Double path = new Path2D.Double();
-        g.translate(1, 1);
+        g.translate(2, 0);
         path.moveTo(xU + 1, yU + 2);
         path.lineTo(3 * xU + 1, yU + 2);
         path.lineTo(2 * xU + 1, 3 * yU);
         path.lineTo(xU + 1, yU + 2);
         path.closePath();
         g.fill(path);
-        g.translate(-1, -1);
+        g.translate(-2, 0);
         g.setColor(getBorderColor());
         g.drawLine(0, -1, 0, h);
         config.restore();
       }
+
+      @Override
+      public Dimension getPreferredSize() {
+        int size = getFont().getSize() + 4;
+        if (size%2==1) size++;
+        return new DimensionUIResource(size, size);
+      }
     };
     button.setBorder(BorderFactory.createEmptyBorder());
     button.setOpaque(false);
@@ -112,6 +132,78 @@
     return new InsetsUIResource(4, 7, 4, 5);
   }
 
+  protected Dimension getDisplaySize() {
+    if (!myDisplaySizeDirty) {
+      return new Dimension(myDisplaySizeCache);
+    }
+
+    Dimension display = new Dimension();
+
+    ListCellRenderer renderer = comboBox.getRenderer();
+    if (renderer == null) {
+      renderer = new DefaultListCellRenderer();
+    }
+
+    boolean sameBaseline = true;
+
+    Object prototypeValue = comboBox.getPrototypeDisplayValue();
+    if (prototypeValue != null) {
+      display = getSizeForComponent(renderer.getListCellRendererComponent(listBox, prototypeValue, -1, false, false));
+    } else {
+      final ComboBoxModel model = comboBox.getModel();
+
+      int baseline = -1;
+      Dimension d;
+
+      if (model.getSize() > 0) {
+        for (int i = 0; i < model.getSize(); i++) {
+          Object value = model.getElementAt(i);
+          Component rendererComponent = renderer.getListCellRendererComponent(listBox, value, -1, false, false);
+          d = getSizeForComponent(rendererComponent);
+          if (sameBaseline && value != null && (!(value instanceof String) || !"".equals(value))) {
+            int newBaseline = rendererComponent.getBaseline(d.width, d.height);
+            if (newBaseline == -1) {
+              sameBaseline = false;
+            }
+            else if (baseline == -1) {
+              baseline = newBaseline;
+            }
+            else if (baseline != newBaseline) {
+              sameBaseline = false;
+            }
+          }
+          display.width = Math.max(display.width, d.width);
+          display.height = Math.max(display.height, d.height);
+        }
+      }
+      else {
+        display = getDefaultSize();
+        if (comboBox.isEditable()) {
+          display.width = 100;
+        }
+      }
+    }
+
+    if (myPadding != null) {
+      display.width += myPadding.left + myPadding.right;
+      display.height += myPadding.top + myPadding.bottom;
+    }
+
+    myDisplaySizeCache.setSize(display.width, display.height);
+    myDisplaySizeDirty = false;
+
+    return display;
+  }
+
+  protected Dimension getSizeForComponent(Component comp) {
+    currentValuePane.add(comp);
+    comp.setFont(comboBox.getFont());
+    Dimension d = comp.getPreferredSize();
+    currentValuePane.remove(comp);
+    return d;
+  }
+
+
   @Override
   public void paint(Graphics g, JComponent c) {
     final Container parent = c.getParent();
@@ -164,8 +256,8 @@
     g.drawLine(xxx + 5, y + 1 + off, xxx + 5, height - 3);
 
     Rectangle r = rectangleForCurrentValue();
-    paintCurrentValueBackground(g,r,hasFocus);
-    paintCurrentValue(g,r,hasFocus);
+    paintCurrentValueBackground(g, r, hasFocus);
+    paintCurrentValue(g, r, hasFocus);
 
     if (hasFocus) {
       DarculaUIUtil.paintFocusRing(g, 2, 2, width - 4, height - 4);
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java
index 0752f88..b540092 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextBorder.java
@@ -31,8 +31,11 @@
 public class DarculaTextBorder implements Border, UIResource {
   @Override
   public Insets getBorderInsets(Component c) {
-    int off = DarculaTextFieldUI.isSearchField(c) ? 16 : 0;
-    return new InsetsUIResource(5, 7 + off + (off == 0 ? 0 : 3), 5, 7 + off);
+    if (DarculaTextFieldUI.isSearchField(c)) {
+      return new InsetsUIResource(5, 7 + 16 + 3, 5, 7 + 16);
+    } else {
+      return new InsetsUIResource(5, 7, 5, 7);
+    }
   }
 
   @Override
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextFieldUI.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextFieldUI.java
index 1885b23..f7c24ed 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextFieldUI.java
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTextFieldUI.java
@@ -24,7 +24,6 @@
 import javax.swing.*;
 import javax.swing.border.Border;
 import javax.swing.plaf.ComponentUI;
-import javax.swing.plaf.DimensionUIResource;
 import javax.swing.plaf.basic.BasicTextFieldUI;
 import javax.swing.text.JTextComponent;
 import java.awt.*;
@@ -115,11 +114,6 @@
     return cPoint.distance(ePoint) <= 8 ? SearchAction.CLEAR : sPoint.distance(ePoint) <= 8 ? SearchAction.POPUP : null;
   }
 
-  @Override
-  protected void paintSafely(Graphics g) {
-    super.paintSafely(g);
-  }
-
   protected Rectangle getDrawingRect() {
     final JTextComponent c = getComponent();
     final JBInsets i = JBInsets.create(c.getInsets());
@@ -191,24 +185,6 @@
     config.restore();
   }
 
-  @Override
-  public Dimension getMinimumSize(JComponent c) {
-    final Dimension size = super.getMinimumSize(c);
-    return new DimensionUIResource(size.width, 24);
-  }
-
-  @Override
-  public Dimension getPreferredSize(JComponent c) {
-    final Dimension size = super.getPreferredSize(c);
-    return new DimensionUIResource(size.width, 24);
-  }
-
-  @Override
-  public Dimension getMaximumSize(JComponent c) {
-    final Dimension size = super.getMaximumSize(c);
-    return new DimensionUIResource(size.width, 24);
-  }
-
   public static boolean isSearchField(Component c) {
     return c instanceof JTextField && "search".equals(((JTextField)c).getClientProperty("JTextField.variant"));
   }
diff --git a/platform/platform-impl/src/com/intellij/idea/StartupUtil.java b/platform/platform-impl/src/com/intellij/idea/StartupUtil.java
index ed2e1fe..8575ab1 100644
--- a/platform/platform-impl/src/com/intellij/idea/StartupUtil.java
+++ b/platform/platform-impl/src/com/intellij/idea/StartupUtil.java
@@ -30,8 +30,6 @@
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.util.Consumer;
 import com.intellij.util.SystemProperties;
-import com.intellij.util.containers.ContainerUtil;
-import com.intellij.util.containers.ContainerUtilRt;
 import com.intellij.util.text.DateFormatUtilRt;
 import com.sun.jna.Native;
 import org.jetbrains.annotations.NonNls;
diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java
index b9b0903..3cc6a8b 100644
--- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java
+++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -44,17 +44,9 @@
   private final ActionRef<ActionGroup> myGroup;
   private final PresentationFactory myPresentationFactory;
   private final Presentation myPresentation;
-  /**
-   * Defines whether menu shows its mnemonic or not.
-   */
   private boolean myMnemonicEnabled;
   private MenuItemSynchronizer myMenuItemSynchronizer;
-  /**
-   * This is PATCH!!!
-   * Do not remove this STUPID code. Otherwise you will lose all keyboard navigation
-   * at JMenuBar.
-   */
-  private StubItem myStubItem;
+  private StubItem myStubItem;  // A PATCH!!! Do not remove this code, otherwise you will lose all keyboard navigation in JMenuBar.
   private final boolean myTopLevel;
 
   public ActionMenu(final DataContext context,
@@ -121,10 +113,6 @@
 
     if (UIUtil.isStandardMenuLAF()) {
       super.updateUI();
-
-      if (myTopLevel && isAmbiance) {
-        setForeground(UIUtil.GTK_AMBIANCE_TEXT_COLOR);
-      }
     }
     else {
       setUI(IdeaMenuUI.createUI(this));
@@ -135,6 +123,24 @@
         popupMenu.updateUI();
       }
     }
+
+    if (myTopLevel && isAmbiance) {
+      setForeground(UIUtil.GTK_AMBIANCE_TEXT_COLOR);
+    }
+
+    if (myTopLevel && UIUtil.isUnderGTKLookAndFeel()) {
+      Insets insets = getInsets();
+      Insets newInsets = new Insets(insets.top, insets.left, insets.bottom, insets.right);
+      if (insets.top + insets.bottom < 6) {
+        newInsets.top = newInsets.bottom = 3;
+      }
+      if (insets.left + insets.right < 12) {
+        newInsets.left = newInsets.right = 6;
+      }
+      if (!newInsets.equals(insets)) {
+        setBorder(BorderFactory.createEmptyBorder(newInsets.top, newInsets.left, newInsets.bottom, newInsets.right));
+      }
+    }
   }
 
   @Override
@@ -248,21 +254,23 @@
   }
 
   private void fillMenu() {
-    boolean mayContextBeInvalid;
     DataContext context;
+    boolean mayContextBeInvalid;
 
     if (myContext != null) {
       context = myContext;
       mayContextBeInvalid = false;
     }
     else {
-      context = DataManager.getInstance().getDataContext();
+      @SuppressWarnings("deprecation") DataContext contextFromFocus = DataManager.getInstance().getDataContext();
+      context = contextFromFocus;
       if (PlatformDataKeys.CONTEXT_COMPONENT.getData(context) == null) {
-        context = DataManager.getInstance()
-          .getDataContext(IdeFocusManager.getGlobalInstance().getLastFocusedFor(UIUtil.getParentOfType(IdeFrame.class, this)));
+        IdeFrame frame = UIUtil.getParentOfType(IdeFrame.class, this);
+        context = DataManager.getInstance().getDataContext(IdeFocusManager.getGlobalInstance().getLastFocusedFor(frame));
       }
       mayContextBeInvalid = true;
     }
+
     Utils.fillMenu(myGroup.getAction(), this, myMnemonicEnabled, myPresentationFactory, context, myPlace, true, mayContextBeInvalid);
   }
 
diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenuItem.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenuItem.java
index 004fa10..e9e33b6 100644
--- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenuItem.java
+++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenuItem.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -225,8 +225,8 @@
 
     public void actionPerformed(final ActionEvent e) {
       final IdeFocusManager fm = IdeFocusManager.findInstanceByContext(myContext);
-      final ActionCallback typeahead = new ActionCallback();
-      fm.typeAheadUntil(typeahead);
+      final ActionCallback typeAhead = new ActionCallback();
+      fm.typeAheadUntil(typeAhead);
       fm.runOnOwnContext(myContext, new Runnable() {
         @Override
         public void run() {
@@ -240,17 +240,18 @@
             actionManager.fireBeforeActionPerformed(action, myContext, event);
             Component component = PlatformDataKeys.CONTEXT_COMPONENT.getData(event.getDataContext());
             if (component != null && !isInTree(component)) {
-              typeahead.setDone();
+              typeAhead.setDone();
               return;
             }
 
             SimpleTimer.getInstance().setUp(new Runnable() {
               @Override
               public void run() {
+                //noinspection SSBasedInspection
                 SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
-                    fm.doWhenFocusSettlesDown(typeahead.createSetDoneRunnable());
+                    fm.doWhenFocusSettlesDown(typeAhead.createSetDoneRunnable());
                   }
                 });
               }
@@ -258,8 +259,9 @@
 
             ActionUtil.performActionDumbAware(action, event);
             actionManager.queueActionPerformedEvent(action, myContext, event);
-          } else {
-            typeahead.setDone();
+          }
+          else {
+            typeAhead.setDone();
           }
         }
       });
diff --git a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffMarkup.java b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffMarkup.java
index 25defaf..f2fcc6a 100644
--- a/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffMarkup.java
+++ b/platform/platform-impl/src/com/intellij/openapi/diff/impl/highlighting/DiffMarkup.java
@@ -93,7 +93,7 @@
         @Override
         public void paint(@NotNull Editor ed, @NotNull RangeHighlighter highlighter, @NotNull Graphics g) {
           g.setColor(attributes.getBackgroundColor());
-          Point point = ed.logicalPositionToXY(ed.offsetToLogicalPosition(offset));
+          Point point = ed.logicalPositionToXY(ed.offsetToLogicalPosition(highlighter.getStartOffset()));
           int endy = point.y + ed.getLineHeight() - 1;
           g.drawLine(point.x, point.y, point.x, endy);
           g.drawLine(point.x - 1, point.y, point.x - 1, endy);
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/IgnoredFileCache.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/IgnoredFileCache.java
index cff063d..e3f15e0 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/IgnoredFileCache.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/IgnoredFileCache.java
@@ -17,11 +17,10 @@
 
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.vfs.*;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.openapi.vfs.VirtualFileManager;
 import com.intellij.openapi.vfs.newvfs.BulkFileListener;
 import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
-import com.intellij.openapi.vfs.newvfs.events.VFileCreateEvent;
-import com.intellij.openapi.vfs.newvfs.events.VFileDeleteEvent;
 import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
 import com.intellij.openapi.vfs.newvfs.events.VFilePropertyChangeEvent;
 import com.intellij.util.containers.IntArrayList;
@@ -50,17 +49,17 @@
       public void before(@NotNull List<? extends VFileEvent> events) {
         // during VFS event processing the system may be in inconsistent state, don't cache it
         myEnableCache = false;
-        clearCacheForChangedFiles(events, true);
+        clearCacheForChangedFiles(events);
       }
 
       @Override
       public void after(@NotNull List<? extends VFileEvent> events) {
-        clearCacheForChangedFiles(events, false);
+        clearCacheForChangedFiles(events);
         myEnableCache = true;
       }
 
-      private void clearCacheForChangedFiles(List<? extends VFileEvent> events, boolean before) {
-        final IntArrayList ids = collectChangedIds(events, before);
+      private void clearCacheForChangedFiles(List<? extends VFileEvent> events) {
+        final IntArrayList ids = collectChangedIds(events);
         synchronized (myCheckedIds) {
           for (int i : ids.toArray()) {
             myCheckedIds.clear(i);
@@ -68,7 +67,7 @@
         }
       }
 
-      private IntArrayList collectChangedIds(List<? extends VFileEvent> events, boolean before) {
+      private IntArrayList collectChangedIds(List<? extends VFileEvent> events) {
         final IntArrayList ids = new IntArrayList();
         for (final VFileEvent event : events) {
           VirtualFile file = event.getFile();
@@ -77,31 +76,14 @@
           }
 
           if (event instanceof VFilePropertyChangeEvent) {
-            addId(ids, event, file);
-          } else if (event instanceof VFileDeleteEvent && before || event instanceof VFileCreateEvent && !before) {
-            VfsUtilCore.visitChildrenRecursively(file, new VirtualFileVisitor() {
-              @Override
-              public boolean visitFile(@NotNull VirtualFile file) {
-                addId(ids, event, file);
-                return true;
-              }
-
-              @Override
-              public Iterable<VirtualFile> getChildrenIterable(@NotNull VirtualFile file) {
-                return file instanceof NewVirtualFile ? ((NewVirtualFile)file).iterInDbChildren() : null;
-              }
-            });
+            int id = ((NewVirtualFile)file).getId();
+            if (id >= 0) {
+              ids.add(id);
+            }
           }
         }
         return ids;
       }
-
-      private void addId(IntArrayList ids, VFileEvent event, VirtualFile file) {
-        int id = ((NewVirtualFile)file).getId();
-        if (id >= 0) {
-          ids.add(id);
-        }
-      }
     });
   }
 
diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultBundledKeymaps.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultBundledKeymaps.java
index a610ae3..a56295f 100644
--- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultBundledKeymaps.java
+++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/DefaultBundledKeymaps.java
@@ -34,6 +34,7 @@
       "Keymap_GNOME.xml",
       "Keymap_KDE.xml",
       "Keymap_Eclipse.xml",
+      "Keymap_EclipseMac.xml",
       "Keymap_Netbeans.xml"
     );
   }
diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/LabelTextReplacingUtil.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/LabelTextReplacingUtil.java
index 991aafe..eeaed02 100644
--- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/LabelTextReplacingUtil.java
+++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/LabelTextReplacingUtil.java
@@ -41,12 +41,23 @@
       if (child instanceof JLabel) {
         final JLabel label = (JLabel)child;
         String oldText = label.getText();
-        if (oldText == null) continue;
-        String newText = StringUtil.replace(oldText, "$PRODUCT$", ApplicationNamesInfo.getInstance().getProductName());
-        newText = StringUtil.replace(newText, "$FULLNAME$", ApplicationNamesInfo.getInstance().getFullProductName());
-        label.setText(newText);
+        if (oldText != null) {
+          label.setText(doReplace(oldText));
+        }
+      }
+      else if (child instanceof AbstractButton) {
+        AbstractButton button = (AbstractButton)child;
+        String oldText = button.getText();
+        if (oldText != null) {
+          button.setText(doReplace(oldText));
+        }
       }
     }
   }
 
+  private static String doReplace(String oldText) {
+    String newText = StringUtil.replace(oldText, "$PRODUCT$", ApplicationNamesInfo.getInstance().getProductName());
+    newText = StringUtil.replace(newText, "$FULLNAME$", ApplicationNamesInfo.getInstance().getFullProductName());
+    return newText;
+  }
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java
index 59b4a4b..8fee9d5 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java
@@ -29,6 +29,7 @@
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.project.DumbAwareRunnable;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.roots.impl.DirectoryIndex;
 import com.intellij.openapi.startup.StartupManager;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.NotNullLazyValue;
@@ -89,9 +90,28 @@
     }
   }
 
-  public FileStatusManagerImpl(Project project, StartupManager startupManager) {
+  public FileStatusManagerImpl(Project project, StartupManager startupManager,
+                               @SuppressWarnings("UnusedParameters") DirectoryIndex makeSureIndexIsInitializedFirst) {
     myProject = project;
 
+    startupManager.registerPreStartupActivity(new Runnable() {
+      @Override
+      public void run() {
+        DocumentAdapter documentListener = new DocumentAdapter() {
+          public void documentChanged(DocumentEvent event) {
+            VirtualFile file = FileDocumentManager.getInstance().getFile(event.getDocument());
+            if (file != null) {
+              refreshFileStatusFromDocument(file, event.getDocument());
+            }
+          }
+        };
+
+        final EditorFactory factory = EditorFactory.getInstance();
+        if (factory != null) {
+          factory.getEventMulticaster().addDocumentListener(documentListener, myProject);
+        }
+      }
+    });
     startupManager.registerPostStartupActivity(new DumbAwareRunnable() {
       public void run() {
         fileStatusesChanged();
@@ -126,19 +146,6 @@
   }
 
   public void projectOpened() {
-    DocumentAdapter documentListener = new DocumentAdapter() {
-      public void documentChanged(DocumentEvent event) {
-        VirtualFile file = FileDocumentManager.getInstance().getFile(event.getDocument());
-        if (file != null) {
-          refreshFileStatusFromDocument(file, event.getDocument());
-        }
-      }
-    };
-
-    final EditorFactory factory = EditorFactory.getInstance();
-    if (factory != null) {
-      factory.getEventMulticaster().addDocumentListener(documentListener, myProject);
-    }
   }
 
   public void disposeComponent() {
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandler.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandler.java
index c992ca4..2d9b885 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandler.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarHandler.java
@@ -19,13 +19,13 @@
  */
 package com.intellij.openapi.vfs.impl.jar;
 
-import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.application.ModalityState;
+import com.intellij.notification.NotificationGroup;
+import com.intellij.notification.NotificationType;
 import com.intellij.openapi.application.PathManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProgressIndicator;
 import com.intellij.openapi.progress.ProgressManager;
-import com.intellij.openapi.ui.Messages;
+import com.intellij.openapi.util.NotNullLazyValue;
 import com.intellij.openapi.util.io.FileAttributes;
 import com.intellij.openapi.util.io.FileSystemUtil;
 import com.intellij.openapi.util.io.FileUtil;
@@ -34,17 +34,25 @@
 import com.intellij.openapi.vfs.VfsBundle;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
+import com.intellij.openapi.vfs.newvfs.persistent.FSRecords;
+import com.intellij.util.io.DataExternalizer;
+import com.intellij.util.io.EnumeratorStringDescriptor;
+import com.intellij.util.io.IOUtil;
+import com.intellij.util.io.PersistentHashMap;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.io.File;
-import java.io.IOException;
+import java.io.*;
+import java.nio.charset.Charset;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
 
 public class JarHandler extends JarHandlerBase {
   private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.impl.jar.JarHandler");
 
   @NonNls private static final String JARS_FOLDER = "jars";
+  private static final int FS_TIME_RESOLUTION = 2000;
 
   private final JarFileSystemImpl myFileSystem;
 
@@ -83,19 +91,124 @@
       return originalFile;
     }
 
+    if (FSRecords.weHaveContentHashes) {
+      return getMirrorWithContentHash(originalFile, originalAttributes);
+    }
+
     final String mirrorName = originalFile.getName() + "." + Integer.toHexString(originalFile.getPath().hashCode());
     final File mirrorFile = new File(folderPath, mirrorName);
     final FileAttributes mirrorAttributes = FileSystemUtil.getAttributes(mirrorFile);
 
     if (mirrorAttributes == null ||
         originalAttributes.length != mirrorAttributes.length ||
-        Math.abs(originalAttributes.lastModified - mirrorAttributes.lastModified) > 2000) {
+        Math.abs(originalAttributes.lastModified - mirrorAttributes.lastModified) > FS_TIME_RESOLUTION) {
       return copyToMirror(originalFile, mirrorFile);
     }
 
     return mirrorFile;
   }
 
+  private File getMirrorWithContentHash(File originalFile,
+                                        FileAttributes originalAttributes) {
+    File mirrorFile = null;
+    try {
+      String path = originalFile.getPath();
+      CacheLibraryInfo info = CacheLibraryInfo.ourCachedLibraryInfo.get(path);
+      FileAttributes mirrorFileAttributes;
+
+      if (info != null) {
+        if (originalAttributes.length == info.myFileLength &&
+            Math.abs(originalAttributes.lastModified - info.myModificationTime) <= FS_TIME_RESOLUTION
+           ) {
+          mirrorFile = new File(new File(getJarsDir()), info.mySnapshotPath);
+          mirrorFileAttributes = FileSystemUtil.getAttributes(mirrorFile);
+          if (mirrorFileAttributes != null &&
+              mirrorFileAttributes.length == originalAttributes.length &&
+              // no abs, reuse if cached file is older, mirrors can be from different projects with different modification times
+              (mirrorFileAttributes.lastModified - originalAttributes.lastModified) <= FS_TIME_RESOLUTION
+            ) {
+            return mirrorFile;
+          }
+        }
+      }
+
+      DataOutputStream os = null;
+      FileInputStream is = null;
+
+      MessageDigest sha1 = null;
+      File tempJarFile = null;
+
+      try {
+        tempJarFile = FileUtil.createTempFile(new File(getJarsDir()), originalFile.getName(), "", true, false);
+        os = new DataOutputStream(new FileOutputStream(tempJarFile));
+        is = new FileInputStream(originalFile);
+        byte[] buffer = new byte[20 * 1024];
+
+        sha1 = MessageDigest.getInstance("SHA1");
+        sha1.update(String.valueOf(originalAttributes.length).getBytes(Charset.defaultCharset()));
+        sha1.update("\0".getBytes(Charset.defaultCharset()));
+
+        while(true) {
+          int read = is.read(buffer);
+          if (read == -1) break;
+          sha1.update(buffer, 0, read);
+          os.write(buffer, 0, read);
+        }
+      } catch (IOException ex) {
+        reportIOErrorWithJars(originalFile, mirrorFile, ex);
+        return originalFile;
+      } catch (NoSuchAlgorithmException ex) {
+        assert false;
+        return originalFile; // should never happen for sha1
+      }
+      finally {
+        if (os != null) try {os.close();} catch (IOException ignored) {}
+        if (is != null) try {is.close();} catch (IOException ignored) {}
+      }
+
+      byte[] digest = sha1.digest();
+      mirrorFile = new File(new File(getJarsDir()), getSnapshotName(originalFile.getName(), digest));
+      mirrorFileAttributes = FileSystemUtil.getAttributes(mirrorFile);
+
+      if (mirrorFileAttributes == null ||
+          originalAttributes.length != mirrorFileAttributes.length ||
+          mirrorFileAttributes.lastModified - originalAttributes.lastModified > FS_TIME_RESOLUTION // no abs, avoid leaving lately modified mirrors
+        ) {
+        try {
+          if (mirrorFileAttributes != null) {
+            FileUtil.delete(mirrorFile);
+          }
+          FileUtil.rename(tempJarFile, mirrorFile);
+          mirrorFile.setLastModified(originalAttributes.lastModified);
+        } catch (IOException ex) {
+          reportIOErrorWithJars(originalFile, mirrorFile, ex);
+          return originalFile;
+        }
+      } else {
+        FileUtil.delete(tempJarFile);
+      }
+
+      info = new CacheLibraryInfo(mirrorFile.getName(), originalAttributes.lastModified, originalAttributes.length);
+      CacheLibraryInfo.ourCachedLibraryInfo.put(path, info);
+      CacheLibraryInfo.ourCachedLibraryInfo.force();
+      return mirrorFile;
+    } catch (IOException ex) {
+      reportIOErrorWithJars(originalFile, mirrorFile != null ? mirrorFile: new File(getJarsDir(), originalFile.getName()), ex);
+      return originalFile;
+    }
+  }
+
+  private String getSnapshotName(String name, byte[] digest) {
+    StringBuilder builder = new StringBuilder(name.length() + 1 + 2 * digest.length);
+    builder.append(name).append('.');
+    for(byte b:digest) {
+      builder.append(Character.forDigit((b & 0xF0) >> 4, 16));
+      builder.append(Character.forDigit(b & 0xF, 16));
+    }
+
+    return builder.toString();
+  }
+
   @NotNull
   private static String getJarsDir() {
     String dir = System.getProperty("jars_dir");
@@ -115,17 +228,7 @@
       FileUtil.copy(original, mirror);
     }
     catch (final IOException e) {
-      LOG.warn(e);
-      final String path = original.getPath();
-      final String message = VfsBundle.message("jar.copy.error.message", path, mirror.getPath(), e.getMessage());
-      ApplicationManager.getApplication().invokeLater(new Runnable() {
-        @Override
-        public void run() {
-          Messages.showErrorDialog(message, VfsBundle.message("jar.copy.error.title"));
-        }
-      }, ModalityState.NON_MODAL);
-
-      myFileSystem.setNoCopyJarForPath(path);
+      reportIOErrorWithJars(original, mirror, e);
       return original;
     }
 
@@ -135,4 +238,89 @@
 
     return mirror;
   }
+
+  private static class CacheLibraryInfo {
+    private final String mySnapshotPath;
+    private final long myModificationTime;
+    private final long myFileLength;
+
+    private static final PersistentHashMap<String, CacheLibraryInfo> ourCachedLibraryInfo;
+
+    static {
+      File file = new File(new File(getJarsDir()), "snapshots_info");
+      PersistentHashMap<String, CacheLibraryInfo> info = null;
+      for (int i = 0; i < 2; ++i) {
+        try {
+          info = new PersistentHashMap<String, CacheLibraryInfo>(
+            file, new EnumeratorStringDescriptor(), new DataExternalizer<CacheLibraryInfo>() {
+            private final byte[] myBuffer = IOUtil.allocReadWriteUTFBuffer();
+
+            @Override
+            public void save(DataOutput out, CacheLibraryInfo value) throws IOException {
+              IOUtil.writeUTFFast(myBuffer, out, value.mySnapshotPath);
+              out.writeLong(value.myModificationTime);
+              out.writeLong(value.myFileLength);
+            }
+
+            @Override
+            public CacheLibraryInfo read(DataInput in) throws IOException {
+              return new CacheLibraryInfo(IOUtil.readUTFFast(myBuffer, in), in.readLong(), in.readLong());
+            }
+          }
+          );
+          break;
+        } catch (IOException ex) {
+          PersistentHashMap.deleteFilesStartingWith(file);
+        }
+      }
+      assert info != null;
+      ourCachedLibraryInfo = info;
+    }
+
+    private CacheLibraryInfo(@NotNull String path, long time, long length) {
+      mySnapshotPath = path;
+      myModificationTime = time;
+      myFileLength = length;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+      if (this == o) return true;
+      if (o == null || getClass() != o.getClass()) return false;
+
+      CacheLibraryInfo info = (CacheLibraryInfo)o;
+
+      if (myFileLength != info.myFileLength) return false;
+      if (myModificationTime != info.myModificationTime) return false;
+      if (!mySnapshotPath.equals(info.mySnapshotPath)) return false;
+
+      return true;
+    }
+
+    @Override
+    public int hashCode() {
+      int result = mySnapshotPath.hashCode();
+      result = 31 * result + (int)(myModificationTime ^ (myModificationTime >>> 32));
+      result = 31 * result + (int)(myFileLength ^ (myFileLength >>> 32));
+      return result;
+    }
+  }
+
+  private static final NotNullLazyValue<NotificationGroup> ERROR_COPY_NOTIFICATION = new NotNullLazyValue<NotificationGroup>() {
+    @NotNull
+    @Override
+    protected NotificationGroup compute() {
+      return NotificationGroup.balloonGroup(VfsBundle.message("jar.copy.error.title"));
+    }
+  };
+
+  private void reportIOErrorWithJars(File original, File mirror, IOException e) {
+    LOG.warn(e);
+    final String path = original.getPath();
+    final String message = VfsBundle.message("jar.copy.error.message", path, mirror.getPath(), e.getMessage());
+
+    ERROR_COPY_NOTIFICATION.getValue().createNotification(message, NotificationType.ERROR).notify(null);
+
+    myFileSystem.setNoCopyJarForPath(path);
+  }
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java
index 69700ac..0bf2b4c 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/FSRecords.java
@@ -29,6 +29,7 @@
 import com.intellij.openapi.util.io.ByteSequence;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.util.ArrayUtil;
+import com.intellij.util.SystemProperties;
 import com.intellij.util.containers.ConcurrentHashMap;
 import com.intellij.util.containers.IntArrayList;
 import com.intellij.util.io.*;
@@ -41,6 +42,10 @@
 import javax.swing.*;
 import java.awt.*;
 import java.io.*;
+import java.nio.charset.Charset;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.Arrays;
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
 
@@ -50,7 +55,8 @@
 public class FSRecords implements Forceable {
   private static final Logger LOG = Logger.getInstance("#com.intellij.vfs.persistent.FSRecords");
 
-  private static final int VERSION = 19;
+  public static final boolean weHaveContentHashes = SystemProperties.getBooleanProperty("idea.share.contents", false);
+  private static final int VERSION = 19 + (weHaveContentHashes ? 2:0);
 
   private static final int PARENT_OFFSET = 0;
   private static final int PARENT_SIZE = 4;
@@ -105,6 +111,7 @@
   }
 
   static class DbConnection {
+    private static final int SIGNATURE_LENGTH = 20;
     private static boolean ourInitialized;
     private static final ConcurrentHashMap<String, Integer> myAttributeIds = new ConcurrentHashMap<String, Integer>();
 
@@ -112,6 +119,7 @@
     private static Storage myAttributes;
     private static RefCountingStorage myContents;
     private static ResizeableMappedFile myRecords;
+    private static PersistentBTreeEnumerator<byte[]> myContentHashesEnumerator;
     private static final TIntArrayList myFreeRecords = new TIntArrayList();
 
     private static boolean myDirty = false;
@@ -194,6 +202,7 @@
       final File namesFile = new File(basePath, "names.dat");
       final File attributesFile = new File(basePath, "attrib.dat");
       final File contentsFile = new File(basePath, "content.dat");
+      final File contentsHashesFile = new File(basePath, "contentHashes.dat");
       final File recordsFile = new File(basePath, "records.dat");
 
       if (!namesFile.exists()) {
@@ -210,6 +219,66 @@
         myNames = new PersistentStringEnumerator(namesFile, storageLockContext);
         myAttributes = new Storage(attributesFile.getCanonicalPath(), REASONABLY_SMALL);
         myContents = new RefCountingStorage(contentsFile.getCanonicalPath(), CapacityAllocationPolicy.FIVE_PERCENT_FOR_GROWTH); // sources usually zipped with 4x ratio
+        myContentHashesEnumerator = weHaveContentHashes ? new PersistentBTreeEnumerator<byte[]>(contentsHashesFile, new KeyDescriptor<byte[]>() {
+          @Override
+          public void save(DataOutput out, byte[] value) throws IOException {
+            out.write(value);
+          }
+
+          @Override
+          public byte[] read(DataInput in) throws IOException {
+            byte[] b = new byte[SIGNATURE_LENGTH];
+            in.readFully(b);
+            return b;
+          }
+
+          @Override
+          public int getHashCode(byte[] value) {
+            int hash = 0; // take first 4 bytes, this should be good enough hash given we reference git revisions with 7-8 hex digits
+            for(int i = 0; i < 4; ++i) {
+              hash = (hash << 8) + (value[i] & 0xFF);
+            }
+            return hash;
+          }
+
+          @Override
+          public boolean isEqual(byte[] val1, byte[] val2) {
+            return Arrays.equals(val1, val2);
+          }
+        }, 4096, storageLockContext) {
+          @Override
+          protected int doWriteData(byte[] value) throws IOException {
+            int record = getContentStorage().createNewRecord();
+            int idx = (super.doWriteData(value)) / SIGNATURE_LENGTH;
+            if (idx + 1 != record) {
+              assert false:"Unexpected content storage modification";
+            }
+            return idx;
+          }
+
+          @Override
+          public int getLargestId() {
+            return super.getLargestId() / SIGNATURE_LENGTH;
+          }
+
+          private boolean myProcessingKeyAtIndex;   // currently protected by w.lock of FSRecords
+
+          @Override
+          protected boolean isKeyAtIndex(byte[] value, int idx) throws IOException {
+            myProcessingKeyAtIndex = true;
+            try {
+              return super.isKeyAtIndex(value, addrToIndex(indexToAddr(idx)* SIGNATURE_LENGTH));
+            } finally {
+              myProcessingKeyAtIndex = false;
+            }
+          }
+
+          @Override
+          public byte[] valueOf(int idx) throws IOException {
+            if (myProcessingKeyAtIndex) return super.valueOf(idx);
+            return super.valueOf(addrToIndex(indexToAddr(idx)* SIGNATURE_LENGTH));
+          }
+        }: null;
         boolean aligned = PagedFileStorage.BUFFER_SIZE % RECORD_SIZE == 0;
         assert aligned; // for performance
         myRecords = new ResizeableMappedFile(recordsFile, 20 * 1024, storageLockContext,
@@ -240,6 +309,7 @@
           deleted &= deleteAllFilesStartingWith(namesFile);
           deleted &= AbstractStorage.deleteFiles(attributesFile.getCanonicalPath());
           deleted &= AbstractStorage.deleteFiles(contentsFile.getCanonicalPath());
+          deleted &= deleteAllFilesStartingWith(contentsHashesFile);
           deleted &= deleteAllFilesStartingWith(recordsFile);
 
           if (!deleted) {
@@ -337,6 +407,7 @@
           myNames.force();
           myAttributes.force();
           myContents.force();
+          if (myContentHashesEnumerator != null) myContentHashesEnumerator.force();
           myRecords.force();
         }
       }
@@ -357,6 +428,7 @@
 
         final boolean attribsFlushed = myAttributes.flushSome();
         final boolean contentsFlushed = myContents.flushSome();
+        if (myContentHashesEnumerator != null) myContentHashesEnumerator.force();
         if (attribsFlushed && contentsFlushed) {
           markClean();
           myRecords.force();
@@ -368,7 +440,8 @@
     }
 
     public static boolean isDirty() {
-      return myDirty || myNames.isDirty() || myAttributes.isDirty() || myContents.isDirty() || myRecords.isDirty();
+      return myDirty || myNames.isDirty() || myAttributes.isDirty() || myContents.isDirty() || myRecords.isDirty() ||
+             (myContentHashesEnumerator != null ? myContentHashesEnumerator.isDirty() : false);
     }
 
 
@@ -424,6 +497,11 @@
         myContents = null;
       }
 
+      if (myContentHashesEnumerator != null) {
+        myContentHashesEnumerator.close();
+        myContentHashesEnumerator = null;
+      }
+
       if (myRecords != null) {
         markClean();
         myRecords.close();
@@ -491,6 +569,10 @@
     return DbConnection.getRecords();
   }
 
+  private static PersistentBTreeEnumerator<byte[]> getContentHashesEnumerator() {
+    return DbConnection.myContentHashesEnumerator;
+  }
+
   private static RefCountingStorage getContentStorage() {
     return DbConnection.myContents;
   }
@@ -572,7 +654,11 @@
   private static void deleteContentAndAttributes(int id) throws IOException {
     int content_page = getContentRecordId(id);
     if (content_page != 0) {
-      getContentStorage().releaseRecord(content_page);
+      if (weHaveContentHashes) {
+        getContentStorage().releaseRecord(content_page, false);
+      } else {
+        getContentStorage().releaseRecord(content_page);
+      }
     }
 
     int att_page = getAttributeRecordId(id);
@@ -1239,10 +1325,18 @@
 
   public static void releaseContent(int contentId) {
     try {
-      getContentStorage().releaseRecord(contentId);
+      w.lock();
+      RefCountingStorage contentStorage = getContentStorage();
+      if (weHaveContentHashes) {
+        contentStorage.releaseRecord(contentId, false);
+      } else {
+        contentStorage.releaseRecord(contentId);
+      }
     }
     catch (Throwable e) {
       throw DbConnection.handleError(e);
+    } finally {
+      w.unlock();
     }
   }
 
@@ -1266,13 +1360,35 @@
     return new ContentOutputStream(fileId, readOnly);
   }
 
+  private static final MessageDigest myDigest;
+
+  static {
+    MessageDigest digest;
+    try {
+      digest = weHaveContentHashes ? MessageDigest.getInstance("SHA1") : null;
+    } catch (NoSuchAlgorithmException ex) {
+      assert false:"Every Java implementation should have SHA-1 support"; // http://docs.oracle.com/javase/7/docs/api/java/security/MessageDigest.html
+      digest = null;
+    }
+    myDigest = digest;
+  }
+
   public static void writeContent(int fileId, ByteSequence bytes, boolean readOnly) throws IOException {
     new ContentOutputStream(fileId, readOnly).writeBytes(bytes);
   }
 
   public static int storeUnlinkedContent(byte[] bytes) {
     try {
-      int recordId = getContentStorage().acquireNewRecord();
+      w.lock();
+      int recordId;
+
+      if (weHaveContentHashes) {
+        recordId = findOrCreateContentRecord(bytes, 0, bytes.length);
+        if (recordId > 0) return recordId;
+        recordId = -recordId;
+      } else {
+        recordId = getContentStorage().acquireNewRecord();
+      }
       AbstractStorage.StorageDataOutput output = getContentStorage().writeStream(recordId, true);
       output.write(bytes);
       output.close();
@@ -1280,6 +1396,8 @@
     }
     catch (IOException e) {
       throw DbConnection.handleError(e);
+    } finally {
+      w.unlock();
     }
   }
 
@@ -1314,26 +1432,106 @@
     public void writeBytes(ByteSequence bytes) throws IOException {
       int page;
       RefCountingStorage contentStorage = getContentStorage();
+      final boolean fixedSize;
       try {
         w.lock();
         incModCount(myFileId);
 
         checkFileIsValid(myFileId);
 
-        page = getContentRecordId(myFileId);
-        if (page == 0 || contentStorage.getRefCount(page) > 1) {
-          page = contentStorage.acquireNewRecord();
-          setContentRecordId(myFileId, page);
+        if (weHaveContentHashes) {
+          page = findOrCreateContentRecord(bytes.getBytes(), bytes.getOffset(), bytes.getLength());
+
+          incModCount(myFileId);
+          checkFileIsValid(myFileId);
+
+          setContentRecordId(myFileId, page > 0 ? page : -page);
+
+          if (page > 0) return;
+          page = -page;
+          fixedSize = true;
+        } else {
+          page = getContentRecordId(myFileId);
+          if (page == 0 || contentStorage.getRefCount(page) > 1) {
+            page = contentStorage.acquireNewRecord();
+            setContentRecordId(myFileId, page);
+          }
+          fixedSize = myFixedSize;
         }
       }
       finally {
         w.unlock();
       }
 
-      contentStorage.writeBytes(page, bytes, myFixedSize);
+      contentStorage.writeBytes(page, bytes, fixedSize);
     }
   }
 
+  private static final boolean DO_HARD_CONSISTENCY_CHECK = false;
+  private static final boolean DUMP_STATISTICS = weHaveContentHashes;  // TODO: remove once not needed
+  private static long totalContents, totalReuses, time;
+  private static int contents, reuses;
+
+  private static int findOrCreateContentRecord(byte[] bytes, int offset, int length) throws IOException {
+    assert weHaveContentHashes;
+    byte[] digest;
+
+    long started = DUMP_STATISTICS ? System.nanoTime():0;
+    myDigest.reset();
+    myDigest.update(String.valueOf(length - offset).getBytes(Charset.defaultCharset()));
+    myDigest.update("\0".getBytes(Charset.defaultCharset()));
+    myDigest.update(bytes, offset, length);
+    digest = myDigest.digest();
+    long done = DUMP_STATISTICS ? System.nanoTime() - started : 0;
+    time += done;
+
+    ++contents;
+    totalContents += length;
+
+    if (DUMP_STATISTICS && (contents & 0x3FFF) == 0) {
+      LOG.info("Contents:"+contents + " of " + totalContents + ", reuses:"+reuses + " of " + totalReuses + " for " + (time / 1000000));
+    }
+    PersistentBTreeEnumerator<byte[]> hashesEnumerator = getContentHashesEnumerator();
+    final int largestId = hashesEnumerator.getLargestId();
+    int page = hashesEnumerator.enumerate(digest);
+    getContentStorage().acquireRecord(page);
+
+    if (page < largestId) {
+      ++reuses;
+      totalReuses += length;
+
+      if (DO_HARD_CONSISTENCY_CHECK) {
+        DataInputStream stream = getContentStorage().readStream(page);
+        int i = offset;
+        for(int c = 0; c < length; ++c) {
+          if (stream.available() == 0) {
+            assert false;
+          }
+          if (bytes[i++] != stream.readByte()) {
+            assert false;
+          }
+        }
+        if (stream.available() > 0) {
+          assert false;
+        }
+      }
+      return page;
+    }
+
+    if (DO_HARD_CONSISTENCY_CHECK) {
+      if (hashesEnumerator.enumerate(digest) != page) {
+        assert false;
+      }
+
+      byte[] bytes1 = hashesEnumerator.valueOf(page);
+      if (!Arrays.equals(digest, bytes1)) {
+        assert false;
+      }
+    }
+
+    return -page;
+  }
+
   private static class AttributeOutputStream extends DataOutputStream {
     private final String myAttributeId;
     private final int myFileId;
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java
index 64234f9..97c2440 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java
@@ -19,6 +19,7 @@
 import com.intellij.openapi.application.ex.ApplicationEx;
 import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.util.LowMemoryWatcher;
 import com.intellij.openapi.util.ShutDownTracker;
 import com.intellij.openapi.util.SystemInfo;
 import com.intellij.openapi.util.io.*;
@@ -68,6 +69,13 @@
   // the root of all roots. All roots in myRoots and myRootsById maps are children of this super root. guarded by myRootsLock
   @Nullable private volatile VirtualFileSystemEntry mySuperRoot;
   private boolean myShutDown = false;
+  @SuppressWarnings("UnusedDeclaration")
+  private final LowMemoryWatcher myLowMemoryWatcher = LowMemoryWatcher.register(new Runnable() {
+    @Override
+    public void run() {
+      clearIdCache();
+    }
+  });
 
   public PersistentFSImpl(@NotNull final MessageBus bus) {
     myEventsBus = bus;
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java
index b0e6949..faf6aca 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java
@@ -31,13 +31,17 @@
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.wm.ex.IdeFrameEx;
 import com.intellij.openapi.wm.impl.status.ClockPanel;
+import com.intellij.ui.Gray;
 import com.intellij.ui.ScreenUtil;
+import com.intellij.ui.border.CustomLineBorder;
 import com.intellij.util.ui.Animator;
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
+import javax.swing.border.Border;
+import javax.swing.border.EmptyBorder;
 import java.awt.*;
 import java.awt.event.*;
 import java.awt.geom.AffineTransform;
@@ -106,6 +110,35 @@
   }
 
   @Override
+  public Border getBorder() {
+    //avoid moving lines
+    if (myState == State.EXPANDING || myState == State.COLLAPSING) {
+      return new EmptyBorder(0,0,0,0);
+    }
+
+    //fix for Darcula double border
+    if (myState == State.TEMPORARY_EXPANDED && UIUtil.isUnderDarcula()) {
+      return new CustomLineBorder(Gray._75, 0, 0, 1, 0);
+    }
+
+    //save 1px for mouse handler
+    if (myState == State.COLLAPSED) {
+      return new EmptyBorder(0, 0, 1, 0);
+    }
+
+    return super.getBorder();
+  }
+
+  @Override
+  public void paint(Graphics g) {
+    //otherwise, there will be 1px line on top
+    if (myState == State.COLLAPSED) {
+      return;
+    }
+    super.paint(g);
+  }
+
+  @Override
   public void doLayout() {
     super.doLayout();
     if (myClockPanel != null) {
@@ -433,7 +466,12 @@
         default:
       }
       revalidate();
-      repaint();
+      if (myState == State.COLLAPSED) {
+        //we should repaint parent, to clear 1px on top when menu is collapsed
+        getParent().repaint();
+      } else {
+        repaint();
+      }
     }
   }
 
diff --git a/platform/platform-impl/src/com/intellij/ui/plaf/gtk/GtkMenuItemUI.java b/platform/platform-impl/src/com/intellij/ui/plaf/gtk/GtkMenuItemUI.java
index 72bc59f..fd74d0e 100644
--- a/platform/platform-impl/src/com/intellij/ui/plaf/gtk/GtkMenuItemUI.java
+++ b/platform/platform-impl/src/com/intellij/ui/plaf/gtk/GtkMenuItemUI.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -93,7 +93,6 @@
     super.update(g, c);
   }
 
-
   @Override
   protected void paintText(final Graphics g, final JMenuItem menuItem, final Rectangle textRect, final String text) {
     if (!menuItem.isEnabled() && UIUtil.isMurrineBasedTheme()) {
diff --git a/platform/platform-impl/src/org/jetbrains/io/FileResponses.java b/platform/platform-impl/src/org/jetbrains/io/FileResponses.java
index 2f70a42..7bc2b21 100644
--- a/platform/platform-impl/src/org/jetbrains/io/FileResponses.java
+++ b/platform/platform-impl/src/org/jetbrains/io/FileResponses.java
@@ -52,8 +52,7 @@
       try {
         if (Responses.DATE_FORMAT.get().parse(ifModifiedSince).getTime() >= lastModified) {
           HttpResponse response = new DefaultHttpResponse(HTTP_1_1, NOT_MODIFIED);
-          response.setHeader("Access-Control-Allow-Origin", "*");
-          response.setHeader("Access-Control-Allow-Credentials", true);
+          addAllowAnyOrigin(response);
           addDate(response);
           addServer(response);
           send(response, request, context);
@@ -68,6 +67,11 @@
     return false;
   }
 
+  private static void addAllowAnyOrigin(HttpResponse response) {
+    response.setHeader("Access-Control-Allow-Origin", "*");
+    response.setHeader("Access-Control-Allow-Credentials", true);
+  }
+
   public static void sendFile(HttpRequest request, ChannelHandlerContext context, File file) throws IOException {
     if (checkCache(request, context, file.lastModified())) {
       return;
@@ -80,6 +84,7 @@
       HttpResponse response = createResponse(file.getPath());
       setContentLength(response, fileLength);
       addDate(response);
+      addAllowAnyOrigin(response);
       response.setHeader(LAST_MODIFIED, Responses.DATE_FORMAT.get().format(new Date(file.lastModified())));
       if (isKeepAlive(request)) {
         response.setHeader(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
diff --git a/platform/platform-resources-en/src/messages/ActionsBundle.properties b/platform/platform-resources-en/src/messages/ActionsBundle.properties
index fe3c4fc..5b46bd9 100644
--- a/platform/platform-resources-en/src/messages/ActionsBundle.properties
+++ b/platform/platform-resources-en/src/messages/ActionsBundle.properties
@@ -1367,3 +1367,6 @@
 
 action.FillParagraph.text=Fill Paragraph
 action.FillParagraph.description=Reformat string literal or comment to fit maximum width (usually 80)
+
+action.SaveDocument.text=Save Document
+action.SaveDocument.description=Saves only the file opened in the current editor
diff --git a/platform/platform-resources-en/src/messages/DiagnosticBundle.properties b/platform/platform-resources-en/src/messages/DiagnosticBundle.properties
index dfac673..0d8fd8f 100644
--- a/platform/platform-resources-en/src/messages/DiagnosticBundle.properties
+++ b/platform/platform-resources-en/src/messages/DiagnosticBundle.properties
@@ -49,7 +49,7 @@
 error.list.restart.action=R_estart
 error.list.disable.plugin=&Disable plugin...
 error.list.disable.plugin.0=Disable plugin {0}
-error.notification.tooltip=<html><body>IDE internal error occurred.<br>Click to see details and post bug report to JetBrains.</body></html>
+error.notification.tooltip=<html><body>IDE internal error occurred.<br>Click to see details and submit a bug report.</body></html>
 error.notification.empty.text=No IDE fatal errors
 error.monitor.too.many.errors=Too many IDE fatal errors. Monitoring stopped.
 error.report.title=Error Report
diff --git a/platform/platform-resources-en/src/messages/IdeBundle.properties b/platform/platform-resources-en/src/messages/IdeBundle.properties
index 7792ebe4..2a4890b 100644
--- a/platform/platform-resources-en/src/messages/IdeBundle.properties
+++ b/platform/platform-resources-en/src/messages/IdeBundle.properties
@@ -887,11 +887,11 @@
 updates.check.manually.label=<html><br>To check for new updates manually, use the <b>Help | Check for Updates</b> command.</html>
 updates.settings.title=Updates
 updates.last.check.never=Never
-updates.settings.caption.1=<html>$PRODUCT$ can automatically check for new and updated versions of itself, using your internet connection (when active).<html>
+updates.settings.caption.1=<html>$FULLNAME$ can automatically check for new and updated versions of itself, using your internet connection (when active).<html>
 updates.settings.check.now.button=&Check Now
 updates.settings.checkbox=Check for updates in channel
 updates.settings.build.number=     Build number:
-updates.settings.current.version=Current $PRODUCT$ version:
+updates.settings.current.version=Current $FULLNAME$ version\:
 updates.settings.last.check=Last checked for updates:
 
 hierarchy.method.next.occurence.name=Go to next method
diff --git a/platform/platform-resources-en/src/messages/RefactoringBundle.properties b/platform/platform-resources-en/src/messages/RefactoringBundle.properties
index d1d6ad6..915eebf 100644
--- a/platform/platform-resources-en/src/messages/RefactoringBundle.properties
+++ b/platform/platform-resources-en/src/messages/RefactoringBundle.properties
@@ -243,7 +243,7 @@
 move.directories= Move &all
 warning.title=Warning
 replace.constructor.with.factory.method.title=Replace Constructor With Factory Method
-class.does.not.have.implicit.default.consructor=Class {0} does not have implicit default consructor.
+class.does.not.have.implicit.default.constructor=Class {0} does not have implicit default constructor.
 would.you.like.to.replace.default.constructor.of.0.with.factory.method=Would you like to replace default constructor of {0} with factory method?
 refactoring.is.not.supported.for.local.and.jsp.classes=Refactoring is not supported for local and JSP classes.
 refactoring.is.not.supported.for.jsp.classes=Refactoring is not supported for JSP classes.
diff --git a/platform/platform-resources/src/idea/Keymap_Eclipse.xml b/platform/platform-resources/src/idea/Keymap_Eclipse.xml
index f78c739..788449e 100644
--- a/platform/platform-resources/src/idea/Keymap_Eclipse.xml
+++ b/platform/platform-resources/src/idea/Keymap_Eclipse.xml
@@ -335,5 +335,6 @@
     </action>
     <action id="MoveLineDown" />
     <action id="MoveLineUp" />
+    <action id="context.clear"/>
   </keymap>
 </component>
diff --git a/platform/platform-resources/src/idea/Keymap_EclipseMac.xml b/platform/platform-resources/src/idea/Keymap_EclipseMac.xml
new file mode 100644
index 0000000..1f6d59d
--- /dev/null
+++ b/platform/platform-resources/src/idea/Keymap_EclipseMac.xml
@@ -0,0 +1,335 @@
+<component>
+  <keymap version="1" name="Eclipse (Mac OS X)" disable-mnemonics="false" parent="Mac OS X 10.5+">
+    <action id="FileChooser.TogglePathShowing">
+      <keyboard-shortcut first-keystroke="meta P"/>
+    </action>
+    <action id="$Redo">
+      <keyboard-shortcut first-keystroke="meta shift Z"/>
+    </action>
+    <action id="$Undo">
+      <keyboard-shortcut first-keystroke="meta Z" />
+    </action>
+    <action id="ActivateNavBar"/>
+    <action id="AutoIndentLines">
+      <keyboard-shortcut first-keystroke="meta I"/>
+    </action>
+    <action id="Back">
+      <keyboard-shortcut first-keystroke="meta OPEN_BRACKET" />
+      <mouse-shortcut keystroke="button4"/>
+    </action>
+    <action id="ChangeSignature">
+      <keyboard-shortcut first-keystroke="alt meta C" />
+    </action>
+    <action id="ChangeTypeSignature"/>
+    <action id="CheckinProject" />
+    <action id="CloseActiveTab">
+      <keyboard-shortcut first-keystroke="meta W" />
+    </action>
+    <action id="CloseAllEditors">
+      <keyboard-shortcut first-keystroke="meta shift W" />
+    </action>
+    <action id="CloseEditor" />
+    <action id="CodeInspection.OnEditor" />
+    <action id="CollapseAllRegions">
+      <keyboard-shortcut first-keystroke="shift meta DIVIDE" />
+    </action>
+    <action id="CommentByBlockComment">
+      <keyboard-shortcut first-keystroke="shift control SLASH" />  <!-- TODO -->
+    </action>
+    <action id="CompileDirty">
+      <keyboard-shortcut first-keystroke="meta B" />
+    </action>
+    <action id="CopyElement" />
+    <action id="Debug">
+      <keyboard-shortcut first-keystroke="meta F11" />
+    </action>
+    <action id="Debugger.Inspect">
+      <keyboard-shortcut first-keystroke="shift meta I" />
+    </action>
+    <action id="DelegateMethods"/>
+    <action id="EditSource">
+      <keyboard-shortcut first-keystroke="F3" />
+    </action>
+    <action id="EditorCodeBlockEnd">
+      <keyboard-shortcut first-keystroke="control CLOSE_BRACKET" />  <!-- TODO -->
+      <keyboard-shortcut first-keystroke="shift control P" />
+    </action>
+    <action id="EditorDeleteToLineEnd">
+      <keyboard-shortcut first-keystroke="shift meta DELETE" />
+    </action>
+    <action id="EditorDeleteLine">
+      <keyboard-shortcut first-keystroke="meta D" />
+    </action>
+    <action id="EditorDuplicate"/>
+    <action id="EditorDuplicateLines">
+      <keyboard-shortcut first-keystroke="meta alt DOWN" />
+    </action>
+    <action id="EditorIndentSelection">
+      <keyboard-shortcut first-keystroke="TAB" />
+    </action>
+    <action id="EditorMoveToPageBottom" />
+    <action id="EditorMoveToPageTop" />
+    <action id="EditorNextWordWithSelection">
+      <keyboard-shortcut first-keystroke="shift alt RIGHT" />
+    </action>
+    <action id="EditorPreviousWordWithSelection">
+      <keyboard-shortcut first-keystroke="shift alt LEFT" />
+    </action>
+    <action id="EditorSelectWord">
+      <keyboard-shortcut first-keystroke="shift control UP" />
+    </action>
+    <action id="EditorToggleCase">
+      <keyboard-shortcut first-keystroke="shift meta X" />
+      <keyboard-shortcut first-keystroke="shift meta Y" />
+    </action>
+    <action id="EditorUnSelectWord">
+      <keyboard-shortcut first-keystroke="shift control DOWN" />
+    </action>
+    <action id="EvaluateExpression">
+      <keyboard-shortcut first-keystroke="meta U" />
+    </action>
+    <action id="ExpandAllRegions">
+      <keyboard-shortcut first-keystroke="meta MULTIPLY" />
+    </action>
+    <action id="ExternalJavaDoc">
+      <keyboard-shortcut first-keystroke="shift F2" />
+    </action>
+    <action id="ExtractMethod">
+      <keyboard-shortcut first-keystroke="meta alt M" />
+    </action>
+    <action id="Faces.Create.Model.Element">
+      <keyboard-shortcut first-keystroke="meta N" />
+    </action>
+    <action id="FileStructurePopup">
+      <keyboard-shortcut first-keystroke="meta O" />
+    </action>
+    <action id="Find"/>
+    <action id="FindInPath">
+      <keyboard-shortcut first-keystroke="control H" />
+    </action>
+    <action id="FindNext">
+      <keyboard-shortcut first-keystroke="meta K" />
+    </action>
+    <action id="FindPrevious">
+      <keyboard-shortcut first-keystroke="shift meta K" />
+    </action>
+    <action id="FindUsages">
+      <keyboard-shortcut first-keystroke="meta shift G" />
+    </action>
+    <action id="FindUsagesInFile">
+      <keyboard-shortcut first-keystroke="meta shift U" />
+    </action>
+    <action id="FindWordAtCaret"/>
+    <action id="Forward">
+      <keyboard-shortcut first-keystroke="meta CLOSE_BRACKET" />
+      <mouse-shortcut keystroke="button5"/>
+    </action>
+    <action id="GotoTest"/>
+    <action id="GotoClass">
+      <keyboard-shortcut first-keystroke="shift meta T" />
+    </action>
+    <action id="GotoDeclaration">
+      <keyboard-shortcut first-keystroke="F3" />
+      <mouse-shortcut keystroke="ctrl button1"/>
+    </action>
+    <action id="GotoFile">
+      <keyboard-shortcut first-keystroke="shift meta R" />
+    </action>
+    <action id="GotoImplementation"/>
+    <action id="GotoLine">
+      <keyboard-shortcut first-keystroke="meta L" />
+    </action>
+    <action id="GotoNextError">
+      <keyboard-shortcut first-keystroke="meta PERIOD"/>
+    </action>
+    <action id="GotoPreviousError">
+      <keyboard-shortcut first-keystroke="meta shift PERIOD" />
+    </action>
+    <action id="GotoSuperMethod"/>
+    <action id="GotoTypeDeclaration"/>
+    <action id="Graph.Faces.OpenSelectedPages">
+      <keyboard-shortcut first-keystroke="F12" />
+      <keyboard-shortcut first-keystroke="shift control E" />
+    </action>
+    <action id="GuiDesigner.CreateComponent">
+      <keyboard-shortcut first-keystroke="meta N" />
+    </action>
+    <action id="GuiDesigner.CreateListener" />
+    <action id="GuiDesigner.Duplicate">
+      <keyboard-shortcut first-keystroke="meta alt UP" />
+      <keyboard-shortcut first-keystroke="meta alt DOWN" />
+    </action>
+    <action id="GuiDesigner.EditComponent" />
+    <action id="GuiDesigner.EditGroup" />
+    <action id="GuiDesigner.GoToListener">
+      <keyboard-shortcut first-keystroke="meta T" />
+    </action>
+    <action id="HighlightUsagesInFile"/>    <!-- TODO -->
+    <action id="IDEtalk.Rename" />
+    <action id="Images.ShowThumbnails" />
+    <action id="Images.Thumbnails.ToggleRecursive" />
+    <action id="ImplementMethods"/>
+    <action id="IncrementalSearch">
+      <keyboard-shortcut first-keystroke="meta J" />
+    </action>
+    <action id="Inline">
+      <keyboard-shortcut first-keystroke="meta alt I" />
+    </action>
+    <action id="InsertLiveTemplate"/>
+    <action id="IntroduceConstant"/>
+    <action id="IntroduceVariable">
+      <keyboard-shortcut first-keystroke="meta alt L" />
+    </action>
+    <action id="JumpToLastChange">
+      <keyboard-shortcut first-keystroke="control Q" />
+    </action>
+    <action id="JumpToLastWindow" />
+    <action id="MethodDown">
+      <keyboard-shortcut first-keystroke="control alt DOWN"/>
+    </action>
+    <action id="MethodUp">
+      <keyboard-shortcut first-keystroke="control alt UP"/>
+    </action>
+    <action id="Move">
+      <keyboard-shortcut first-keystroke="meta alt V" />
+    </action>
+    <action id="MoveStatementDown">
+      <keyboard-shortcut first-keystroke="alt DOWN" />
+    </action>
+    <action id="MoveStatementUp">
+      <keyboard-shortcut first-keystroke="alt UP" />
+    </action>
+    <action id="NextDiff">
+      <keyboard-shortcut first-keystroke="control F7" />
+    </action>
+    <action id="NextOccurence" />
+    <action id="NextTab">
+      <keyboard-shortcut first-keystroke="meta F6" />
+      <keyboard-shortcut first-keystroke="meta alt RIGHT" />
+    </action>
+    <action id="NextEditorTab"/>
+    <action id="OptimizeImports">
+      <keyboard-shortcut first-keystroke="shift meta O" />
+    </action>
+    <action id="OverrideMethods" />
+    <action id="ParameterInfo">
+      <keyboard-shortcut first-keystroke="control shift SPACE"/>
+    </action>
+    <action id="PreviousOccurence" />
+    <action id="PreviousTab">
+      <keyboard-shortcut first-keystroke="shift meta F6" />
+      <keyboard-shortcut first-keystroke="meta alt LEFT" />
+    </action>
+    <action id="PreviousEditorTab"/>
+    <action id="Print">
+      <keyboard-shortcut first-keystroke="meta P" />
+    </action>
+    <action id="QuickJavaDoc">
+      <mouse-shortcut keystroke="alt button2" />
+      <keyboard-shortcut first-keystroke="F2" />
+    </action>
+    <action id="RecentChanges" />
+    <action id="ReformatCode">
+      <keyboard-shortcut first-keystroke="shift meta F" />
+    </action>
+    <action id="Refresh"/>
+    <action id="Unwrap"/>  <!-- TODO -->
+    <action id="Replace"/>
+    <action id="ReplaceInPath" />
+    <action id="Rerun"/>
+    <action id="Resume">
+      <keyboard-shortcut first-keystroke="F8" />
+    </action>
+    <action id="Run">
+      <keyboard-shortcut first-keystroke="meta shift F11" />
+    </action>
+    <action id="RunToCursor">
+      <keyboard-shortcut first-keystroke="meta R" />
+    </action>
+    <action id="ShowIntentionActions">
+      <keyboard-shortcut first-keystroke="meta 1" />
+    </action>
+    <action id="ShowNavBar">
+      <keyboard-shortcut first-keystroke="alt meta B" />
+    </action>
+    <action id="ShowPopupMenu"/>
+    <action id="SmartStepInto">
+      <keyboard-shortcut first-keystroke="alt F5" />
+    </action>
+    <action id="SmartTypeCompletion">
+      <keyboard-shortcut first-keystroke="shift alt SPACE" />
+    </action>
+    <action id="StepInto">
+      <keyboard-shortcut first-keystroke="F5"/>
+     </action>
+    <action id="ForceStepInto">
+      <keyboard-shortcut first-keystroke="meta control F5"/>
+    </action>
+    <action id="StepOut">
+      <keyboard-shortcut first-keystroke="F7" />
+    </action>
+    <action id="StepOver">
+      <keyboard-shortcut first-keystroke="F6" />
+    </action>
+    <action id="ForceStepOver">
+      <keyboard-shortcut first-keystroke="meta control F6" />
+    </action>
+    <action id="StructuralSearchPlugin.StructuralReplaceAction" />
+    <action id="SurroundWith">
+      <keyboard-shortcut first-keystroke="meta alt Z" />
+    </action>
+    <action id="Synchronize"/>
+    <action id="ToggleBookmark"/>
+    <action id="ToggleLineBreakpoint">
+      <keyboard-shortcut first-keystroke="shift meta B" />
+    </action>
+    <action id="TypeHierarchy">
+      <keyboard-shortcut first-keystroke="F4" />
+    </action>
+    <action id="Vcs.UpdateProject" />
+    <action id="MoveLineDown" />
+    <action id="MoveLineUp" />
+
+    <action id="HippieCompletion">
+      <keyboard-shortcut first-keystroke="control PERIOD"/>
+    </action>
+    <action id="HippieBackwardCompletion"/>
+    <action id="EditorDeleteToWordStart">
+      <keyboard-shortcut first-keystroke="meta BACK_SPACE"/>
+    </action>
+    <action id="EditorDeleteToWordEnd">
+      <keyboard-shortcut first-keystroke="meta DELETE"/>
+    </action>
+    <action id="EditorDeleteToWordStartInDifferentHumpsMode">
+      <keyboard-shortcut first-keystroke="alt BACK_SPACE"/>
+    </action>
+    <action id="EditorDeleteToWordEndInDifferentHumpsMode">
+      <keyboard-shortcut first-keystroke="alt DELETE"/>
+    </action>
+    <action id="SafeDelete"/>
+
+    <action id="SelectIn">
+      <keyboard-shortcut first-keystroke="alt meta W"/>
+    </action>
+    <action id="GotoAction">
+      <keyboard-shortcut first-keystroke="meta 3"/>
+    </action>
+
+    <action id="ActivateProjectToolWindow"/>
+    <action id="ActivateFavoritesToolWindow"/>
+    <action id="ActivateFindToolWindow">
+      <keyboard-shortcut first-keystroke="alt meta Q" second-keystroke="S"/>
+    </action>
+
+    <action id="CollapseSelection"/>
+    <action id="CollapseBlock"/>
+    <action id="ShowFilePath"/>
+
+    <action id="tasks.goto">
+      <keyboard-shortcut first-keystroke="alt meta F12"/>
+    </action>
+    <action id="tasks.switch">
+      <keyboard-shortcut first-keystroke="meta F9"/>
+    </action>
+  </keymap>
+</component>
diff --git a/platform/platform-resources/src/idea/Keymap_VisualStudio.xml b/platform/platform-resources/src/idea/Keymap_VisualStudio.xml
index 3a75f1e..a8d3aaa 100644
--- a/platform/platform-resources/src/idea/Keymap_VisualStudio.xml
+++ b/platform/platform-resources/src/idea/Keymap_VisualStudio.xml
@@ -204,5 +204,7 @@
     <action id="VcsShowPrevChangeMarker">
       <keyboard-shortcut first-keystroke="shift control alt UP"/>
     </action>
+    <action id="CopyElement"/>
+    <action id="CloneElement"/>
   </keymap>
 </component>
diff --git a/platform/platform-resources/src/idea/PlatformActions.xml b/platform/platform-resources/src/idea/PlatformActions.xml
index 6dcd2bf..da42cb5 100644
--- a/platform/platform-resources/src/idea/PlatformActions.xml
+++ b/platform/platform-resources/src/idea/PlatformActions.xml
@@ -616,5 +616,7 @@
     <action id="DecrementWindowHeight" class="com.intellij.ide.actions.WindowAction$DecrementHeight" use-shortcut-of="ResizeToolWindowUp"/>
 
     <action id="ExportTestResults" class="com.intellij.execution.testframework.export.ExportTestResultsAction" icon="AllIcons.Actions.Export"/>
+
+    <action id="SaveDocument" class="com.intellij.ide.actions.SaveDocumentAction"/>
   </actions>
 </component>
diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/FileTypeManagerTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/FileTypeManagerTest.java
index aa50b40..57828d0 100644
--- a/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/FileTypeManagerTest.java
+++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/FileTypeManagerTest.java
@@ -15,27 +15,34 @@
  */
 package com.intellij.openapi.fileTypes;
 
-import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VfsUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.PsiFile;
 import com.intellij.psi.PsiManager;
 import com.intellij.psi.impl.PsiManagerEx;
-import com.intellij.testFramework.PlatformTestCase;
+import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
 
 import java.io.IOException;
 
-public class FileTypeManagerTest extends PlatformTestCase {
+public class FileTypeManagerTest extends LightPlatformCodeInsightFixtureTestCase {
   public void testAutoDetectTextFileFromContents() throws IOException {
-    VirtualFile temp = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(createTempDirectory());
-    VirtualFile vFile = createChildData(temp, "test.xxxxxxx");
+    VirtualFile vFile = myFixture.getTempDirFixture().createFile("test.xxxxxxxx");
     VfsUtil.saveText(vFile, "text");
 
     FileType type = vFile.getFileType();
     assertEquals(UnknownFileType.INSTANCE, type);
 
-    PsiFile psiFile = ((PsiManagerEx)PsiManager.getInstance(myProject)).getFileManager().findFile(vFile); // autodetect text file if needed
+    PsiFile psiFile = ((PsiManagerEx)PsiManager.getInstance(myFixture.getProject())).getFileManager().findFile(vFile); // autodetect text file if needed
     assertNotNull(psiFile);
     assertEquals(PlainTextFileType.INSTANCE, vFile.getFileType());
   }
+
+  public void testIgnoredFiles() throws IOException {
+    VirtualFile vFile = myFixture.getTempDirFixture().createFile(".svn", "");
+    assertTrue(FileTypeManager.getInstance().isFileIgnored(vFile));
+    vFile.delete(this);
+
+    vFile = myFixture.getTempDirFixture().createFile("a.txt", "");
+    assertFalse(FileTypeManager.getInstance().isFileIgnored(vFile));
+  }
 }
diff --git a/platform/testFramework/src/com/intellij/testFramework/EditorTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/EditorTestUtil.java
index 48e4ef5..a3c1f00 100644
--- a/platform/testFramework/src/com/intellij/testFramework/EditorTestUtil.java
+++ b/platform/testFramework/src/com/intellij/testFramework/EditorTestUtil.java
@@ -37,6 +37,8 @@
  */
 public class EditorTestUtil {
   public static final String CARET_TAG = "<caret>";
+  public static final String CARET_TAG_PREFIX = CARET_TAG.substring(0, CARET_TAG.length() - 1);
+
   public static final String SELECTION_START_TAG = "<selection>";
   public static final String SELECTION_END_TAG = "</selection>";
 
@@ -94,14 +96,23 @@
   }
 
   public static int[] getCaretAndSelectionPosition(@NotNull final String content) {
-    int caretPosInSourceFile = content.indexOf(CARET_TAG);
+    int caretPosInSourceFile = content.indexOf(CARET_TAG_PREFIX);
+    int caretEndInSourceFile = content.indexOf(">", caretPosInSourceFile);
+    int caretLength = caretEndInSourceFile - caretPosInSourceFile;
+    int visualColumnOffset = 0;
+    if (caretPosInSourceFile >= 0) {
+      String visualOffsetString = content.substring(caretPosInSourceFile + CARET_TAG_PREFIX.length(), caretEndInSourceFile);
+      if (visualOffsetString.length() > 1) {
+        visualColumnOffset = Integer.parseInt(visualOffsetString.substring(1));
+      }
+    }
     int selectionStartInSourceFile = content.indexOf(SELECTION_START_TAG);
     int selectionEndInSourceFile = content.indexOf(SELECTION_END_TAG);
     if (selectionStartInSourceFile >= 0) {
       if (caretPosInSourceFile >= 0) {
         if (caretPosInSourceFile < selectionStartInSourceFile) {
-          selectionStartInSourceFile -= CARET_TAG.length();
-          selectionEndInSourceFile -= CARET_TAG.length();
+          selectionStartInSourceFile -= caretLength;
+          selectionEndInSourceFile -= caretLength;
         }
         else {
           if (caretPosInSourceFile < selectionEndInSourceFile) {
@@ -115,6 +126,6 @@
       selectionEndInSourceFile -= SELECTION_START_TAG.length();
     }
 
-    return new int[]{caretPosInSourceFile, selectionStartInSourceFile, selectionEndInSourceFile};
+    return new int[]{caretPosInSourceFile, visualColumnOffset, selectionStartInSourceFile, selectionEndInSourceFile};
   }
 }
diff --git a/platform/testFramework/src/com/intellij/testFramework/HighlightTestInfo.java b/platform/testFramework/src/com/intellij/testFramework/HighlightTestInfo.java
index 407ae19..3361188 100644
--- a/platform/testFramework/src/com/intellij/testFramework/HighlightTestInfo.java
+++ b/platform/testFramework/src/com/intellij/testFramework/HighlightTestInfo.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -43,7 +43,7 @@
   public HighlightTestInfo checkSymbolNames() { checkSymbolNames = true; return this; }
   public HighlightTestInfo projectRoot(@NonNls @NotNull String root) { projectRoot = root; return this; }
 
-  public HighlightTestInfo test() throws Exception {
+  public HighlightTestInfo test() {
     try {
       doTest();
       return this;
@@ -59,5 +59,5 @@
     assert tested : "You must call HighlightTestInfo.test() in " + myPlace;
   }
 
-  protected abstract HighlightTestInfo doTest() throws Exception;
+  protected abstract HighlightTestInfo doTest();
 }
diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java
index 62e290e3..009943d 100644
--- a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java
+++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -427,9 +427,9 @@
 
   @Override
   public HighlightTestInfo testFile(@NonNls @NotNull String... filePath) {
-    return new HighlightTestInfo(getTestRootDisposable(), filePath){
+    return new HighlightTestInfo(getTestRootDisposable(), filePath) {
       @Override
-      public HighlightTestInfo doTest() throws Exception {
+      public HighlightTestInfo doTest() {
         configureByFiles(filePaths);
         ExpectedHighlightingData data = new ExpectedHighlightingData(myEditor.getDocument(), checkWarnings, checkWeakWarnings, checkInfos, myFile);
         if (checkSymbolNames) data.checkSymbolNames();
diff --git a/platform/testRunner/src/com/intellij/execution/testframework/TestConsoleProperties.java b/platform/testRunner/src/com/intellij/execution/testframework/TestConsoleProperties.java
index 96952bb..5075e26 100644
--- a/platform/testRunner/src/com/intellij/execution/testframework/TestConsoleProperties.java
+++ b/platform/testRunner/src/com/intellij/execution/testframework/TestConsoleProperties.java
@@ -47,7 +47,7 @@
   public static final BooleanProperty HIDE_IGNORED_TEST = new BooleanProperty("hideIgnoredTests", false);
   public static final BooleanProperty HIDE_PASSED_TESTS = new BooleanProperty("hidePassedTests", true);
   public static final BooleanProperty SCROLL_TO_SOURCE = new BooleanProperty("scrollToSource", false);
-  public static final BooleanProperty OPEN_FAILURE_LINE = new BooleanProperty("openFailureLine", false);
+  public static final BooleanProperty OPEN_FAILURE_LINE = new BooleanProperty("openFailureLine", true);
   public static final BooleanProperty TRACK_CODE_COVERAGE = new BooleanProperty("trackCodeCoverage", false);
   public static final BooleanProperty SHOW_STATISTICS = new BooleanProperty("showStatistics", false);
 
diff --git a/platform/usageView/src/com/intellij/usages/ChunkExtractor.java b/platform/usageView/src/com/intellij/usages/ChunkExtractor.java
index 80bfdb2..cf7b95d 100644
--- a/platform/usageView/src/com/intellij/usages/ChunkExtractor.java
+++ b/platform/usageView/src/com/intellij/usages/ChunkExtractor.java
@@ -150,26 +150,40 @@
     final List<TextChunk> result = new ArrayList<TextChunk>();
     appendPrefix(result, visibleLineNumber, visibleColumnNumber);
 
-    int lineStartOffset = myDocument.getLineStartOffset(lineNumber);
-    int lineEndOffset = lineStartOffset < myDocument.getTextLength() ? myDocument.getLineEndOffset(lineNumber) : 0;
-    if (lineStartOffset > lineEndOffset) return TextChunk.EMPTY_ARRAY;
+    int fragmentToShowStart = myDocument.getLineStartOffset(lineNumber);
+    int fragmentToShowEnd = fragmentToShowStart < myDocument.getTextLength() ? myDocument.getLineEndOffset(lineNumber) : 0;
+    if (fragmentToShowStart > fragmentToShowEnd) return TextChunk.EMPTY_ARRAY;
 
     final CharSequence chars = myDocument.getCharsSequence();
-    if (lineEndOffset - lineStartOffset > MAX_LINE_LENGTH_TO_SHOW) {
+    if (fragmentToShowEnd - fragmentToShowStart > MAX_LINE_LENGTH_TO_SHOW) {
+      final int lineStartOffset = fragmentToShowStart;
+      fragmentToShowStart = Math.max(lineStartOffset, absoluteStartOffset - OFFSET_BEFORE_TO_SHOW_WHEN_LONG_LINE);
+
+      final int lineEndOffset = fragmentToShowEnd;
       Segment segment = usageInfo2UsageAdapter.getUsageInfo().getSegment();
       int usage_length = segment != null ? segment.getEndOffset() - segment.getStartOffset():0;
-      lineStartOffset = Math.max(lineStartOffset, absoluteStartOffset - OFFSET_BEFORE_TO_SHOW_WHEN_LONG_LINE);
-      lineEndOffset = Math.min(lineEndOffset, absoluteStartOffset + usage_length + OFFSET_AFTER_TO_SHOW_WHEN_LONG_LINE);
+      fragmentToShowEnd = Math.min(lineEndOffset, absoluteStartOffset + usage_length + OFFSET_AFTER_TO_SHOW_WHEN_LONG_LINE);
+
+      // if we search something like a word, then expand shown context from one symbol before / after at least for word boundary
+      // this should not cause restarts of the lexer as the tokens are usually words
+      if (usage_length > 0 &&
+          StringUtil.isJavaIdentifierStart(chars.charAt(absoluteStartOffset)) &&
+          StringUtil.isJavaIdentifierStart(chars.charAt(absoluteStartOffset + usage_length - 1))) {
+        while(fragmentToShowEnd < lineEndOffset && StringUtil.isJavaIdentifierStart(chars.charAt(fragmentToShowEnd - 1))) ++fragmentToShowEnd;
+        while(fragmentToShowStart > lineStartOffset && StringUtil.isJavaIdentifierStart(chars.charAt(fragmentToShowStart))) --fragmentToShowStart;
+        if (fragmentToShowStart != lineStartOffset) ++fragmentToShowStart;
+        if (fragmentToShowEnd != lineEndOffset) --fragmentToShowEnd;
+      }
     }
     if (myDocument instanceof DocumentWindow) {
       List<TextRange> editable = InjectedLanguageManager.getInstance(file.getProject())
-        .intersectWithAllEditableFragments(file, new TextRange(lineStartOffset, lineEndOffset));
+        .intersectWithAllEditableFragments(file, new TextRange(fragmentToShowStart, fragmentToShowEnd));
       for (TextRange range : editable) {
         createTextChunks(usageInfo2UsageAdapter, chars, range.getStartOffset(), range.getEndOffset(), true, result);
       }
       return result.toArray(new TextChunk[result.size()]);
     }
-    return createTextChunks(usageInfo2UsageAdapter, chars, lineStartOffset, lineEndOffset, true, result);
+    return createTextChunks(usageInfo2UsageAdapter, chars, fragmentToShowStart, fragmentToShowEnd, true, result);
   }
 
   @NotNull
diff --git a/platform/util/src/com/intellij/util/EnvironmentUtil.java b/platform/util/src/com/intellij/util/EnvironmentUtil.java
index 3d30872..1303c47 100644
--- a/platform/util/src/com/intellij/util/EnvironmentUtil.java
+++ b/platform/util/src/com/intellij/util/EnvironmentUtil.java
@@ -18,7 +18,6 @@
 import com.intellij.openapi.util.SystemInfo;
 import com.intellij.util.text.CaseInsensitiveStringHashingStrategy;
 import gnu.trove.THashMap;
-import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -26,23 +25,21 @@
 import java.util.Map;
 
 public class EnvironmentUtil {
-  private static final Map<String, String> ourEnvironmentProperties = Collections.unmodifiableMap(new ProcessBuilder().environment());
+  private static final Map<String, String> ourEnvironmentProperties;
   private static final Map<String, String> ourEnvironmentVariablesOsSpecific;
 
   static {
-    Map<String, String> envVars = ourEnvironmentProperties;
+    ourEnvironmentProperties = Collections.unmodifiableMap(new ProcessBuilder().environment());
     if (SystemInfo.isWindows) {
-      THashMap<String, String> map = new THashMap<String, String>(CaseInsensitiveStringHashingStrategy.INSTANCE);
-      map.putAll(envVars);
-      ourEnvironmentVariablesOsSpecific = map;
+      ourEnvironmentVariablesOsSpecific = Collections.unmodifiableMap(
+        new THashMap<String, String>(ourEnvironmentProperties, CaseInsensitiveStringHashingStrategy.INSTANCE));
     }
     else {
-      ourEnvironmentVariablesOsSpecific = envVars;
+      ourEnvironmentVariablesOsSpecific = ourEnvironmentProperties;
     }
   }
 
-  private EnvironmentUtil() {
-  }
+  private EnvironmentUtil() { }
 
   /** @deprecated use {@link #getEnvironmentProperties()} (to remove in IDEA 14) */
   @SuppressWarnings({"UnusedDeclaration", "SpellCheckingInspection"})
@@ -50,7 +47,7 @@
     return getEnvironmentProperties();
   }
 
-  @NonNls
+  @NotNull
   public static Map<String, String> getEnvironmentProperties() {
     return ourEnvironmentProperties;
   }
diff --git a/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java b/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java
index 7da7e87..ca654e2 100644
--- a/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java
+++ b/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java
@@ -226,6 +226,11 @@
     }
   }
 
+  protected int addrToIndex(int addr) {
+    assert myExternalKeysNoMapping;
+    return addr + KEY_SHIFT;
+  }
+
   @Override
   protected int indexToAddr(int idx) {
     if (myExternalKeysNoMapping) {
@@ -242,7 +247,7 @@
 
   @Override
   protected int setupValueId(int hashCode, int dataOff) {
-    if (myExternalKeysNoMapping) return dataOff + KEY_SHIFT;
+    if (myExternalKeysNoMapping) return addrToIndex(dataOff);
     final PersistentEnumeratorBase.RecordBufferHandler<PersistentEnumeratorBase> recordHandler = getRecordHandler();
     final byte[] buf = recordHandler.getRecordBuffer(this);
 
diff --git a/platform/util/src/com/intellij/util/io/PersistentEnumeratorBase.java b/platform/util/src/com/intellij/util/io/PersistentEnumeratorBase.java
index 27cbaaf..c9e990d 100644
--- a/platform/util/src/com/intellij/util/io/PersistentEnumeratorBase.java
+++ b/platform/util/src/com/intellij/util/io/PersistentEnumeratorBase.java
@@ -433,28 +433,7 @@
     try {
       markDirty(true);
 
-      final int dataOff = myKeyStorage != null ? myKeyStoreBufferPosition + myKeyStoreFileLength : ((InlineKeyDescriptor<Data>)myDataDescriptor).toInt(value);
-
-      if (myKeyStorage != null) {
-        final BufferExposingByteArrayOutputStream bos = new BufferExposingByteArrayOutputStream();
-        DataOutput out = new DataOutputStream(bos);
-        myDataDescriptor.save(out, value);
-        final int size = bos.size();
-        final byte[] buffer = bos.getInternalBuffer();
-
-        if (size > myKeyStoreFileBuffer.length) {
-          flushKeyStoreBuffer();
-          myKeyStorage.put(dataOff, buffer, 0, size);
-          myKeyStoreFileLength += size;
-        } else {
-          if (size > myKeyStoreFileBuffer.length - myKeyStoreBufferPosition) {
-            flushKeyStoreBuffer();
-          }
-          // myKeyStoreFileBuffer will contain complete records
-          System.arraycopy(buffer, 0, myKeyStoreFileBuffer, myKeyStoreBufferPosition, size);
-          myKeyStoreBufferPosition += size;
-        }
-      }
+      final int dataOff = doWriteData(value);
 
       return setupValueId(hashCode, dataOff);
     }
@@ -463,6 +442,39 @@
     }
   }
 
+  public int getLargestId() {
+    assert myKeyStorage != null;
+    return myKeyStoreBufferPosition + myKeyStoreFileLength;
+  }
+
+  protected int doWriteData(Data value) throws IOException {
+    final int dataOff = myKeyStorage != null ?
+                        myKeyStoreBufferPosition + myKeyStoreFileLength :
+                        ((InlineKeyDescriptor<Data>)myDataDescriptor).toInt(value);
+
+    if (myKeyStorage != null) {
+      final BufferExposingByteArrayOutputStream bos = new BufferExposingByteArrayOutputStream();
+      DataOutput out = new DataOutputStream(bos);
+      myDataDescriptor.save(out, value);
+      final int size = bos.size();
+      final byte[] buffer = bos.getInternalBuffer();
+
+      if (size > myKeyStoreFileBuffer.length) {
+        flushKeyStoreBuffer();
+        myKeyStorage.put(dataOff, buffer, 0, size);
+        myKeyStoreFileLength += size;
+      } else {
+        if (size > myKeyStoreFileBuffer.length - myKeyStoreBufferPosition) {
+          flushKeyStoreBuffer();
+        }
+        // myKeyStoreFileBuffer will contain complete records
+        System.arraycopy(buffer, 0, myKeyStoreFileBuffer, myKeyStoreBufferPosition, size);
+        myKeyStoreBufferPosition += size;
+      }
+    }
+    return dataOff;
+  }
+
   private void flushKeyStoreBuffer() throws IOException {
     if (myKeyStoreBufferPosition > 0) {
       myKeyStorage.put(myKeyStoreFileLength, myKeyStoreFileBuffer, 0, myKeyStoreBufferPosition);
diff --git a/platform/util/src/com/intellij/util/io/storage/RefCountingStorage.java b/platform/util/src/com/intellij/util/io/storage/RefCountingStorage.java
index 6b50f4c..634c2bc 100644
--- a/platform/util/src/com/intellij/util/io/storage/RefCountingStorage.java
+++ b/platform/util/src/com/intellij/util/io/storage/RefCountingStorage.java
@@ -187,6 +187,12 @@
     }
   }
 
+  public int createNewRecord() throws IOException {
+    synchronized (myLock) {
+      return myRecordsTable.createNewRecord();
+    }
+  }
+
   public void acquireRecord(int record) {
     waitForPendingWriteForRecord(record);
     synchronized (myLock) {
@@ -195,9 +201,13 @@
   }
 
   public void releaseRecord(int record) throws IOException {
+    releaseRecord(record, true);
+  }
+
+  public void releaseRecord(int record, boolean completely) throws IOException {
     waitForPendingWriteForRecord(record);
     synchronized (myLock) {
-      if (((RefCountingRecordsTable)myRecordsTable).decRefCount(record)) {
+      if (((RefCountingRecordsTable)myRecordsTable).decRefCount(record) && completely) {
         doDeleteRecord(record);
       }
     }
diff --git a/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java b/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java
index 265582c..d6fb6c3 100644
--- a/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java
+++ b/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java
@@ -170,9 +170,7 @@
   }
 
   private void addOrderedComponentAdapter(ComponentAdapter componentAdapter) {
-    if (!orderedComponentAdapters.contains(componentAdapter)) {
-      orderedComponentAdapters.add(componentAdapter);
-    }
+    orderedComponentAdapters.add(componentAdapter);
   }
 
   @Override
@@ -225,10 +223,8 @@
   }
 
   @Nullable
-  private Object getInstance(ComponentAdapter componentAdapter) {
-    final boolean isLocal = componentAdapters.contains(componentAdapter);
-
-    if (isLocal) {
+  private Object getInstance(@NotNull ComponentAdapter componentAdapter) {
+    if (componentAdapters.getImmutableSet().contains(componentAdapter)) {
       return getLocalInstance(componentAdapter);
     }
     if (parent != null) {
@@ -360,33 +356,35 @@
   public PicoContainer getParent() {
     return parent;
   }
-  
+
+  /**
+   * A linked hash set that's copied on write operations.
+   * @param <T>
+   */
   private static class LinkedHashSetWrapper<T> {
-    
+    private final Object lock = new Object();
     private volatile Set<T> immutableSet;
-    
-    private final LinkedHashSet<T> synchronizedSet = new LinkedHashSet<T>();
-    
-    private final ConcurrentHashMap<T, T> concurrentSet = new ConcurrentHashMap<T, T>();
-    
-    public boolean contains(@Nullable T element) {
-      return element != null && concurrentSet.containsKey(element);
-    }
-    
-    public void add(@NotNull T element) {
-      synchronized (synchronizedSet) {
-        immutableSet = null;
-        synchronizedSet.add(element);
-        concurrentSet.put(element, element);
+    private LinkedHashSet<T> synchronizedSet = new LinkedHashSet<T>();
+
+    public synchronized void add(@NotNull T element) {
+      synchronized (lock) {
+        if (!synchronizedSet.contains(element)) {
+          copySyncSetIfExposedAsImmutable().add(element);
+        }
       }
     }
-    
-    public void remove(@Nullable T element) {
-      if (element == null) return;
-      synchronized (synchronizedSet) {
+
+    private LinkedHashSet<T> copySyncSetIfExposedAsImmutable() {
+      if (immutableSet != null) {
         immutableSet = null;
-        synchronizedSet.remove(element);
-        concurrentSet.remove(element);
+        synchronizedSet = new LinkedHashSet<T>(synchronizedSet);
+      }
+      return synchronizedSet;
+    }
+
+    public void remove(@Nullable T element) {
+      synchronized (lock) {
+        copySyncSetIfExposedAsImmutable().remove(element);
       }
     }
 
@@ -394,11 +392,11 @@
     public Set<T> getImmutableSet() {
       Set<T> res = immutableSet;
       if (res == null) {
-        synchronized (synchronizedSet) {
+        synchronized (lock) {
           res = immutableSet;
           if (res == null) {
-            res = Collections.unmodifiableSet((Set<T>)synchronizedSet.clone());
-            immutableSet = res;
+            // Expose the same set as immutable. It should be never modified again. Next add/remove operations will copy synchronizedSet
+            immutableSet = res = Collections.unmodifiableSet(synchronizedSet);
           }
         }
       }
diff --git a/platform/util/testSrc/com/intellij/util/EnvironmentUtilTest.java b/platform/util/testSrc/com/intellij/util/EnvironmentUtilTest.java
index 8c6f4c45..9f9c817 100644
--- a/platform/util/testSrc/com/intellij/util/EnvironmentUtilTest.java
+++ b/platform/util/testSrc/com/intellij/util/EnvironmentUtilTest.java
@@ -1,25 +1,36 @@
 /*
- * Created by IntelliJ IDEA.
- * User: mike
- * Date: Sep 19, 2002
- * Time: 3:27:12 PM
- * To change template for new class use 
- * Code Style | Class Templates options (Tools | IDE Options).
+ * Copyright 2000-2013 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.util;
 
 import com.intellij.openapi.util.SystemInfo;
-import junit.framework.TestCase;
+import org.junit.Test;
 
-import java.util.Map;
+import static org.junit.Assert.assertNotNull;
 
-public class EnvironmentUtilTest extends TestCase {
-  public void test1() {
-    Map enviromentProperties = EnvironmentUtil.getEnvironmentProperties();
-    assertNotNull(enviromentProperties);
-    if(SystemInfo.isWindows)
-      assertNotNull(enviromentProperties.get("Path"));
-    else
-      assertNotNull(enviromentProperties.get("PATH"));
+/**
+ * @author mike
+ * @since Sep 19, 2002
+ */
+public class EnvironmentUtilTest {
+  @Test
+  public void basic() {
+    assertNotNull(EnvironmentUtil.getEnvironmentProperties());
+    assertNotNull(EnvironmentUtil.getValue("PATH"));
+    if (SystemInfo.isWindows) {
+      assertNotNull(EnvironmentUtil.getValue("Path"));
+    }
   }
 }
diff --git a/platform/vcs-api/src/com/intellij/openapi/vcs/VcsException.java b/platform/vcs-api/src/com/intellij/openapi/vcs/VcsException.java
index ee4d347..5a72bfe1 100644
--- a/platform/vcs-api/src/com/intellij/openapi/vcs/VcsException.java
+++ b/platform/vcs-api/src/com/intellij/openapi/vcs/VcsException.java
@@ -86,7 +86,6 @@
 
   @Override
   public String getMessage() {
-    final String message = super.getMessage();
-    return (message == null ? "" : (message + " ")) + StringUtil.join(myMessages, ", ");
+    return StringUtil.join(myMessages, ", ");
   }
 }
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.java
index 9473198..b297f05 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/LineStatusTrackerManager.java
@@ -42,6 +42,8 @@
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.fileEditor.FileEditorManager;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.roots.impl.DirectoryIndex;
+import com.intellij.openapi.startup.StartupManager;
 import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.text.StringUtil;
@@ -90,7 +92,8 @@
   private long myLoadCounter;
 
   public LineStatusTrackerManager(final Project project, final ProjectLevelVcsManager vcsManager, final VcsBaseContentProvider statusProvider,
-                                  final Application application, final FileEditorManager fileEditorManager) {
+                                  final Application application, final FileEditorManager fileEditorManager,
+                                  @SuppressWarnings("UnusedParameters") DirectoryIndex makeSureIndexIsInitializedFirst) {
     myLoadCounter = 0;
     myProject = project;
     myVcsManager = vcsManager;
@@ -137,32 +140,37 @@
   }
 
   public void projectOpened() {
-    final MyFileStatusListener fileStatusListener = new MyFileStatusListener();
-    final EditorFactoryListener editorFactoryListener = new MyEditorFactoryListener();
-    final MyVirtualFileListener virtualFileListener = new MyVirtualFileListener();
-    final EditorColorsListener editorColorsListener = new EditorColorsListener() {
-      public void globalSchemeChange(EditorColorsScheme scheme) {
-        resetTrackersForOpenFiles();
-      }
-    };
+    StartupManager.getInstance(myProject).registerPreStartupActivity(new Runnable() {
+      @Override
+      public void run() {
+        final MyFileStatusListener fileStatusListener = new MyFileStatusListener();
+        final EditorFactoryListener editorFactoryListener = new MyEditorFactoryListener();
+        final MyVirtualFileListener virtualFileListener = new MyVirtualFileListener();
+        final EditorColorsListener editorColorsListener = new EditorColorsListener() {
+          public void globalSchemeChange(EditorColorsScheme scheme) {
+            resetTrackersForOpenFiles();
+          }
+        };
 
-    final FileStatusManager fsManager = FileStatusManager.getInstance(myProject);
-    fsManager.addFileStatusListener(fileStatusListener, myProject);
+        final FileStatusManager fsManager = FileStatusManager.getInstance(myProject);
+        fsManager.addFileStatusListener(fileStatusListener, myProject);
 
-    final EditorFactory editorFactory = EditorFactory.getInstance();
-    editorFactory.addEditorFactoryListener(editorFactoryListener,myProject);
+        final EditorFactory editorFactory = EditorFactory.getInstance();
+        editorFactory.addEditorFactoryListener(editorFactoryListener,myProject);
 
-    final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
-    virtualFileManager.addVirtualFileListener(virtualFileListener,myProject);
+        final VirtualFileManager virtualFileManager = VirtualFileManager.getInstance();
+        virtualFileManager.addVirtualFileListener(virtualFileListener,myProject);
 
-    final EditorColorsManager editorColorsManager = EditorColorsManager.getInstance();
-    editorColorsManager.addEditorColorsListener(editorColorsListener);
+        final EditorColorsManager editorColorsManager = EditorColorsManager.getInstance();
+        editorColorsManager.addEditorColorsListener(editorColorsListener);
 
-    Disposer.register(myDisposable, new Disposable() {
-      public void dispose() {
-        fsManager.removeFileStatusListener(fileStatusListener);
-        virtualFileManager.removeVirtualFileListener(virtualFileListener);
-        editorColorsManager.removeEditorColorsListener(editorColorsListener);
+        Disposer.register(myDisposable, new Disposable() {
+          public void dispose() {
+            fsManager.removeFileStatusListener(fileStatusListener);
+            virtualFileManager.removeVirtualFileListener(virtualFileListener);
+            editorColorsManager.removeEditorColorsListener(editorColorsListener);
+          }
+        });
       }
     });
   }
diff --git a/platform/vcs-impl/vcs-impl.iml b/platform/vcs-impl/vcs-impl.iml
index dd03873..9e8c655 100644
--- a/platform/vcs-impl/vcs-impl.iml
+++ b/platform/vcs-impl/vcs-impl.iml
@@ -15,7 +15,6 @@
     <orderEntry type="module" module-name="lang-api" />
     <orderEntry type="module" module-name="jps-model-serialization" />
     <orderEntry type="library" name="Guava" level="project" />
-    <orderEntry type="library" name="sqlite" level="project" />
     <orderEntry type="module" module-name="lang-impl" />
     <orderEntry type="module" module-name="spellchecker" />
   </component>
diff --git a/plugins/eclipse/jps-plugin/src/org/jetbrains/jps/eclipse/model/JpsEclipseClasspathReader.java b/plugins/eclipse/jps-plugin/src/org/jetbrains/jps/eclipse/model/JpsEclipseClasspathReader.java
index 72a7065..113cf49 100644
--- a/plugins/eclipse/jps-plugin/src/org/jetbrains/jps/eclipse/model/JpsEclipseClasspathReader.java
+++ b/plugins/eclipse/jps-plugin/src/org/jetbrains/jps/eclipse/model/JpsEclipseClasspathReader.java
@@ -31,7 +31,6 @@
 import org.jetbrains.jps.model.module.*;
 import org.jetbrains.jps.model.serialization.JpsMacroExpander;
 import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer;
-import org.jetbrains.jps.model.serialization.library.JpsSdkTableSerializer;
 
 import java.io.File;
 import java.io.FilenameFilter;
@@ -97,14 +96,6 @@
                                 Collection<String> unknownJdks,
                                 EclipseModuleManager eclipseModuleManager,
                                 String jdkName) {
-    if (LOG.isDebugEnabled()) {
-      LOG.debug("loading " + rootModel.getName() + ": set module jdk " + jdkName);
-    }
-    final JpsDependenciesList dependenciesList = rootModel.getDependenciesList();
-    dependenciesList.addSdkDependency(JpsJavaSdkType.INSTANCE);
-    if (jdkName != null) {
-      JpsSdkTableSerializer.setSdkReference(rootModel.getSdkReferencesTable(), jdkName, JpsJavaSdkType.INSTANCE);
-    }
   }
 
   @Override
diff --git a/plugins/git4idea/src/git4idea/commands/GitLineHandler.java b/plugins/git4idea/src/git4idea/commands/GitLineHandler.java
index 5063756..1e105a2 100644
--- a/plugins/git4idea/src/git4idea/commands/GitLineHandler.java
+++ b/plugins/git4idea/src/git4idea/commands/GitLineHandler.java
@@ -158,6 +158,9 @@
         myVcs.showErrorMessages(trimmed);
         LOG.info(line.trim());
       }
+      else {
+        LOG.debug(line.trim());
+      }
     }
     myLineListeners.getMulticaster().onLineAvailable(trimmed, outputType);
   }
diff --git a/plugins/git4idea/src/git4idea/commands/GitSimpleHandler.java b/plugins/git4idea/src/git4idea/commands/GitSimpleHandler.java
index b150025..6cef328 100644
--- a/plugins/git4idea/src/git4idea/commands/GitSimpleHandler.java
+++ b/plugins/git4idea/src/git4idea/commands/GitSimpleHandler.java
@@ -92,6 +92,10 @@
       LOG.info(stderr.trim());
       myStderrLine.setLength(0);
     }
+    else {
+      LOG.debug(stderr.trim());
+      LOG.debug(stdout.trim());
+    }
   }
 
   /**
@@ -130,6 +134,7 @@
     }
     entire.append(text);
     if (suppressed || myVcs == null) {
+      LOG.debug(text);
       return;
     }
     int last = lineRest.length() > 0 ? lineRest.charAt(lineRest.length() - 1) : -1;
diff --git a/plugins/git4idea/src/git4idea/merge/GitMergeProvider.java b/plugins/git4idea/src/git4idea/merge/GitMergeProvider.java
index fc26227..82a0095 100644
--- a/plugins/git4idea/src/git4idea/merge/GitMergeProvider.java
+++ b/plugins/git4idea/src/git4idea/merge/GitMergeProvider.java
@@ -149,7 +149,7 @@
         return GitRevisionNumber.resolve(myProject, root, "MERGE_HEAD");
       }
       catch (VcsException e) {
-        LOG.info("Couldn't resolved the MERGE_HEAD in " + root, e); // this may be not a bug, just cherry-pick
+        LOG.info("Couldn't resolve the MERGE_HEAD in " + root, e); // this may be not a bug, just cherry-pick
         try {
           return GitRevisionNumber.resolve(myProject, root, "CHERRY_PICK_HEAD");
         }
diff --git a/plugins/gradle/gradle.iml b/plugins/gradle/gradle.iml
index a7b46ec..00f0b01 100644
--- a/plugins/gradle/gradle.iml
+++ b/plugins/gradle/gradle.iml
@@ -25,227 +25,226 @@
     <orderEntry type="module-library" exported="">
       <library name="Gradle">
         <CLASSES>
-          <root url="jar://$MODULE_DIR$/lib/gradle-base-services-1.6-20130404052254+0000.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-core-1.6-20130404052254+0000.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-messaging-1.6-20130404052254+0000.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-tooling-api-1.6-20130404052254+0000.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-wrapper-1.6-20130404052254+0000.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-base-services-1.6-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-core-1.6-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-messaging-1.6-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-tooling-api-1.6-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-wrapper-1.6-rc-1.jar!/" />
         </CLASSES>
         <JAVADOC />
         <SOURCES>
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/buildSrc/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/buildSrc/src/test/resources" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ui/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ui/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ui/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/cli/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/cpp/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/cpp/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ear/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ide/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ide/src/main/resources" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/idea/IdeaIntegrationTest/canCreateAndDeleteMetaData/api/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/eclipse/EclipseIntegrationTest/canCreateAndDeleteMetaData/api/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/eclipse/EclipseIntegrationTest/canCreateAndDeleteMetaData/api/src/integTest/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/eclipse/EclipseIntegrationTest/canCreateAndDeleteMetaData/webAppJava6/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/eclipse/EclipseIntegrationTest/canCreateAndDeleteMetaData/groovyproject/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/eclipse/EclipseIntegrationTest/canCreateAndDeleteMetaData/webAppWithVars/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/tasks" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/plugins" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/ivy/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/core/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/core/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/core/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/core/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/ear/earWithWar/war/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/ear/earCustomized/war/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/base/prod/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/base/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/onlyif/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/onlyif/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/apiAndImpl/src/api/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/apiAndImpl/src/impl/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/apiAndImpl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/quickstart/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/quickstart/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/multiproject/api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/multiproject/shared/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/multiproject/shared/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/multiproject/buildSrc/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/multiproject/buildSrc/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/multiproject/services/shared/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/multiproject/services/webservice/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/multiproject/services/webservice/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/testListener/src/test/java/org/gradle" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/customizedLayout/src/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/customizedLayout/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/withIntegrationTests/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/withIntegrationTests/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/java/withIntegrationTests/src/integration-test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/antlr/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/maven/quickstart/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/maven/pomGeneration/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/scala/mixedJavaAndScala/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/scala/mixedJavaAndScala/src/main/scala" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/sonar/quickstart/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/sonar/quickstart/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/groovy/multiproject/testproject/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/groovy/multiproject/testproject/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/groovy/multiproject/testproject/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/groovy/multiproject/testproject/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/groovy/multiproject/groovycDetector/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/groovy/mixedJavaAndGroovy/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/groovy/mixedJavaAndGroovy/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/signing/maven/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/signing/conditional/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/junit/categories/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/jacoco/quickstart/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/jacoco/quickstart/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/jacoco/application/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/testng/groups/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/testng/suitexmlbuilder/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/testng/suitexmlbuilder/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/testng/java-jdk14-passing/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/testng/java-jdk14-passing/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/testng/java-jdk15-passing/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/testng/java-jdk15-passing/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/testReport/core/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/testing/testReport/util/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/ant/useExternalAntTaskWithConfig/src" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/java/sourceSets/src/intTest/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/api/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/shared/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/shared/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/services/personService/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/services/personService/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/multiproject/dependencies/webDist/date/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/multiproject/dependencies/webDist/hello/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/multiproject/dependencies/javaWithCustomConf/api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/userguide/multiproject/dependencies/javaWithCustomConf/shared/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/ivypublish/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/ivypublish/subproject/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/toolingApi/idea/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/toolingApi/model/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/toolingApi/eclipse/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/toolingApi/runBuild/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/toolingApi/customModel/plugin/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/toolingApi/customModel/tooling/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/application/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/codeQuality/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/sonarRunner/quickstart/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/sonarRunner/quickstart/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/maven-publish/quickstart/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/maven-publish/javaProject/subproject/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/webApplication/customised/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/webApplication/customised/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/webApplication/quickstart/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/docs/src/samples/clientModuleDependencies/shared/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/osgi/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/osgi/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/antlr/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/jetty/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/maven/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/maven/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/scala/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/scala/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/scala/src/integTest/resources/org/gradle/scala/compile/jdk6/ZincScalaCompilerJdk6IntegrationTest/compilesJavaCodeIncrementally/src/main/scala" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/scala/src/integTest/resources/org/gradle/scala/compile/IncrementalScalaCompileIntegrationTest/recompilesSourceWhenPropertiesChange/src/main/scala" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/nested/nested2/nestedProject/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/nested/nested2/nestedProject/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/skippedProject/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/skippedProject/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/customizedProject/src" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/customizedProject/test" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/javaProjectWithJacoco/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/javaProjectWithJacoco/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/nested/nested2/nestedProject/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/nested/nested2/nestedProject/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/skippedProject/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/skippedProject/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/customizedProject/src" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/customizedProject/test" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/javaProjectWithJacoco/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/javaProjectWithJacoco/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/jacoco/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/native/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesDependentClasses/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesDependentClasses" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesSourceWhenPropertiesChange/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesDependentClassesAcrossProjectBoundaries/app/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesDependentClassesAcrossProjectBoundaries/lib/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesDependentClassesAcrossProjectBoundaries" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/groovy/compile/GroovyCompilerIntegrationSpec/canUseThirdPartyAstTransform/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/groovy/compile/GroovyCompilerIntegrationSpec/canUseAstTransformThatReferencesGroovyTestCase/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/groovy/compile/BasicGroovyCompilerIntegrationSpec/compileBadJavaCode/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/groovy/compile/IncrementalGroovyCompileIntegrationTest/recompilesSourceWhenPropertiesChange/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/compile/daemon/ParallelCompilerDaemonIntegrationTest/shared" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/javadoc/JavadocIntegrationTest/handlesTagsAndTaglets/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/javadoc/JavadocIntegrationTest/handlesTagsAndTaglets/src/taglet/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/javadoc/JavadocIntegrationTest/canCombineLocalOptionWithOtherOptions/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/javadoc/JavadocIntegrationTest/canCombineLocalOptionWithOtherOptions/src/taglet/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/testing/junit/JUnitIntegrationTest/ignoreTests/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources/org/gradle/testing/junit/JUnitIntegrationTest/junit3Tests/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/integTest/resources" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/plugins/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/publish/src/main/groovy/org/gradle/api/publish/plugins" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/publish/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/wrapper/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/wrapper/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/announce/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/launcher/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/launcher/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/open-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/open-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/core-impl/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/core-impl/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/messaging/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/messaging/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/reporting/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/integ-test/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/ExecIntegrationTest/shared/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/ProjectLayoutIntegrationTest/canUseANonStandardBuildDir/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/ProjectLayoutIntegrationTest/canUseANonStandardBuildDir/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/IncrementalTestIntegrationTest/shared/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/IncrementalTestIntegrationTest/doesNotRunStaleTests/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/IncrementalTestIntegrationTest/executesTestsWhenSourceChanges/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/IncrementalTestIntegrationTest/executesTestsWhenSourceChanges" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/IncrementalTestIntegrationTest/executesTestsWhenSelectedTestsChange/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/javascript/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/testjar/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/testjar/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/multiModule/webinar-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/singleModule/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/singleModule/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/enforcerplugin/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/diagnostics/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/diagnostics/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/diagnostics/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/performance/src/configPlugin" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/performance/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/tooling-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/tooling-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/code-quality/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/language-jvm/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/base-services/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/base-services/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/language-base/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-comparison/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/source/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/target/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/internal-testing/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/base-services-groovy/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/base-services-groovy/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-src.zip!/gradle-1.6-20130404052254+0000/subprojects/internal-integ-testing/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/buildSrc/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/buildSrc/src/test/resources" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ui/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ui/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ui/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/cli/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/cpp/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/cpp/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ear/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ide/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ide/src/main/resources" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/idea/IdeaIntegrationTest/canCreateAndDeleteMetaData/api/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/eclipse/EclipseIntegrationTest/canCreateAndDeleteMetaData/api/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/eclipse/EclipseIntegrationTest/canCreateAndDeleteMetaData/api/src/integTest/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/eclipse/EclipseIntegrationTest/canCreateAndDeleteMetaData/webAppJava6/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/eclipse/EclipseIntegrationTest/canCreateAndDeleteMetaData/groovyproject/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ide/src/integTest/resources/org/gradle/plugins/ide/eclipse/EclipseIntegrationTest/canCreateAndDeleteMetaData/webAppWithVars/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/tasks" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/plugins" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/ivy/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/core/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/core/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/core/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/core/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/ear/earWithWar/war/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/ear/earCustomized/war/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/base/prod/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/base/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/onlyif/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/onlyif/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/apiAndImpl/src/api/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/apiAndImpl/src/impl/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/apiAndImpl/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/quickstart/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/quickstart/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/multiproject/api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/multiproject/shared/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/multiproject/shared/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/multiproject/buildSrc/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/multiproject/buildSrc/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/multiproject/services/shared/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/multiproject/services/webservice/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/multiproject/services/webservice/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/testListener/src/test/java/org/gradle" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/customizedLayout/src/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/customizedLayout/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/withIntegrationTests/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/withIntegrationTests/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/java/withIntegrationTests/src/integration-test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/antlr/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/maven/quickstart/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/maven/pomGeneration/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/scala/mixedJavaAndScala/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/scala/mixedJavaAndScala/src/main/scala" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/sonar/quickstart/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/sonar/quickstart/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/groovy/multiproject/testproject/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/groovy/multiproject/testproject/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/groovy/multiproject/testproject/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/groovy/multiproject/testproject/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/groovy/multiproject/groovycDetector/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/groovy/mixedJavaAndGroovy/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/groovy/mixedJavaAndGroovy/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/signing/maven/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/signing/conditional/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/junit/categories/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/jacoco/quickstart/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/jacoco/quickstart/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/jacoco/application/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/testng/groups/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/testng/suitexmlbuilder/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/testng/suitexmlbuilder/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/testng/java-jdk14-passing/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/testng/java-jdk14-passing/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/testng/java-jdk15-passing/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/testng/java-jdk15-passing/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/testReport/core/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/testing/testReport/util/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/ant/useExternalAntTaskWithConfig/src" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/java/sourceSets/src/intTest/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/api/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/shared/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/shared/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/services/personService/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/multiproject/dependencies/java/services/personService/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/multiproject/dependencies/webDist/date/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/multiproject/dependencies/webDist/hello/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/multiproject/dependencies/javaWithCustomConf/api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/userguide/multiproject/dependencies/javaWithCustomConf/shared/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/ivypublish/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/ivypublish/subproject/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/toolingApi/idea/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/toolingApi/model/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/toolingApi/eclipse/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/toolingApi/runBuild/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/toolingApi/customModel/plugin/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/toolingApi/customModel/tooling/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/application/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/codeQuality/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/sonarRunner/quickstart/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/sonarRunner/quickstart/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/maven-publish/quickstart/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/maven-publish/javaProject/subproject/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/webApplication/customised/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/webApplication/customised/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/webApplication/quickstart/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/docs/src/samples/clientModuleDependencies/shared/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/osgi/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/osgi/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/antlr/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/jetty/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/maven/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/maven/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/scala/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/scala/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/scala/src/integTest/resources/org/gradle/scala/compile/jdk6/ZincScalaCompilerJdk6IntegrationTest/compilesJavaCodeIncrementally/src/main/scala" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/scala/src/integTest/resources/org/gradle/scala/compile/IncrementalScalaCompileIntegrationTest/recompilesSourceWhenPropertiesChange/src/main/scala" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/nested/nested2/nestedProject/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/nested/nested2/nestedProject/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/skippedProject/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/skippedProject/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/customizedProject/src" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/customizedProject/test" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/javaProjectWithJacoco/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/sonar/runner/SonarRunnerSmokeIntegrationTest/shared/javaProjectWithJacoco/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/nested/nested2/nestedProject/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/nested/nested2/nestedProject/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/skippedProject/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/skippedProject/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/customizedProject/src" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/customizedProject/test" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/javaProjectWithJacoco/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/sonar/src/integTest/resources/org/gradle/api/plugins/sonar/SonarSmokeIntegrationTest/shared/javaProjectWithJacoco/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/jacoco/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/native/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesDependentClasses/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesDependentClasses" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesSourceWhenPropertiesChange/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesDependentClassesAcrossProjectBoundaries/app/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesDependentClassesAcrossProjectBoundaries/lib/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/java/compile/IncrementalJavaCompileIntegrationTest/recompilesDependentClassesAcrossProjectBoundaries" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/groovy/compile/GroovyCompilerIntegrationSpec/canUseThirdPartyAstTransform/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/groovy/compile/GroovyCompilerIntegrationSpec/canUseAstTransformThatReferencesGroovyTestCase/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/groovy/compile/BasicGroovyCompilerIntegrationSpec/compileBadJavaCode/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/groovy/compile/IncrementalGroovyCompileIntegrationTest/recompilesSourceWhenPropertiesChange/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/compile/daemon/ParallelCompilerDaemonIntegrationTest/shared" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/javadoc/JavadocIntegrationTest/handlesTagsAndTaglets/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/javadoc/JavadocIntegrationTest/handlesTagsAndTaglets/src/taglet/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/javadoc/JavadocIntegrationTest/canCombineLocalOptionWithOtherOptions/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/javadoc/JavadocIntegrationTest/canCombineLocalOptionWithOtherOptions/src/taglet/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources/org/gradle/testing/junit/JUnitIntegrationTest/junit3Tests/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/integTest/resources" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/plugins/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/publish/src/main/groovy/org/gradle/api/publish/plugins" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/publish/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/wrapper/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/wrapper/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/announce/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/launcher/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/launcher/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/open-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/open-api/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/core-impl/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/core-impl/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/messaging/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/messaging/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/reporting/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/integ-test/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/ExecIntegrationTest/shared/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/ProjectLayoutIntegrationTest/canUseANonStandardBuildDir/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/ProjectLayoutIntegrationTest/canUseANonStandardBuildDir/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/IncrementalTestIntegrationTest/shared/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/IncrementalTestIntegrationTest/doesNotRunStaleTests/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/IncrementalTestIntegrationTest/executesTestsWhenSourceChanges/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/IncrementalTestIntegrationTest/executesTestsWhenSourceChanges" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/integ-test/src/integTest/resources/org/gradle/integtests/IncrementalTestIntegrationTest/executesTestsWhenSelectedTestsChange/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/javascript/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/testjar/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/testjar/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/multiModule/webinar-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/singleModule/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/singleModule/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/enforcerplugin/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-setup/src/integTest/resources/org/gradle/buildsetup/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/test/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/diagnostics/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/diagnostics/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/diagnostics/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/performance/src/configPlugin" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/performance/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/tooling-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/tooling-api/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/code-quality/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/language-jvm/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/base-services/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/base-services/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/language-base/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-comparison/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/source/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/target/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/internal-testing/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/base-services-groovy/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/base-services-groovy/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.6-rc-1-src.zip!/gradle-1.6-rc-1/subprojects/internal-integ-testing/src/main/groovy" />
         </SOURCES>
       </library>
     </orderEntry>
diff --git a/plugins/gradle/lib/gradle-1.6-rc-1-src.zip b/plugins/gradle/lib/gradle-1.6-rc-1-src.zip
new file mode 100644
index 0000000..cde909e
--- /dev/null
+++ b/plugins/gradle/lib/gradle-1.6-rc-1-src.zip
Binary files differ
diff --git a/plugins/gradle/lib/gradle-base-services-1.6-20130404052254+0000.jar b/plugins/gradle/lib/gradle-base-services-1.6-rc-1.jar
similarity index 83%
rename from plugins/gradle/lib/gradle-base-services-1.6-20130404052254+0000.jar
rename to plugins/gradle/lib/gradle-base-services-1.6-rc-1.jar
index 7fa1b67..af8bd55 100644
--- a/plugins/gradle/lib/gradle-base-services-1.6-20130404052254+0000.jar
+++ b/plugins/gradle/lib/gradle-base-services-1.6-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/lib/gradle-core-1.6-20130404052254+0000.jar b/plugins/gradle/lib/gradle-core-1.6-rc-1.jar
similarity index 71%
rename from plugins/gradle/lib/gradle-core-1.6-20130404052254+0000.jar
rename to plugins/gradle/lib/gradle-core-1.6-rc-1.jar
index 26cc409..a9b5657 100644
--- a/plugins/gradle/lib/gradle-core-1.6-20130404052254+0000.jar
+++ b/plugins/gradle/lib/gradle-core-1.6-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/lib/gradle-messaging-1.6-20130404052254+0000.jar b/plugins/gradle/lib/gradle-messaging-1.6-rc-1.jar
similarity index 86%
rename from plugins/gradle/lib/gradle-messaging-1.6-20130404052254+0000.jar
rename to plugins/gradle/lib/gradle-messaging-1.6-rc-1.jar
index cc146e1..d14871e 100644
--- a/plugins/gradle/lib/gradle-messaging-1.6-20130404052254+0000.jar
+++ b/plugins/gradle/lib/gradle-messaging-1.6-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/lib/gradle-src.zip b/plugins/gradle/lib/gradle-src.zip
deleted file mode 100644
index 46f3865..0000000
--- a/plugins/gradle/lib/gradle-src.zip
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/lib/gradle-tooling-api-1.6-20130404052254+0000.jar b/plugins/gradle/lib/gradle-tooling-api-1.6-rc-1.jar
similarity index 71%
rename from plugins/gradle/lib/gradle-tooling-api-1.6-20130404052254+0000.jar
rename to plugins/gradle/lib/gradle-tooling-api-1.6-rc-1.jar
index 2f95666..0806cb4 100644
--- a/plugins/gradle/lib/gradle-tooling-api-1.6-20130404052254+0000.jar
+++ b/plugins/gradle/lib/gradle-tooling-api-1.6-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/lib/gradle-wrapper-1.6-20130404052254+0000.jar b/plugins/gradle/lib/gradle-wrapper-1.6-rc-1.jar
similarity index 89%
rename from plugins/gradle/lib/gradle-wrapper-1.6-20130404052254+0000.jar
rename to plugins/gradle/lib/gradle-wrapper-1.6-rc-1.jar
index 8b43adc..2ea6cde 100644
--- a/plugins/gradle/lib/gradle-wrapper-1.6-20130404052254+0000.jar
+++ b/plugins/gradle/lib/gradle-wrapper-1.6-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/resources/i18n/GradleBundle.properties b/plugins/gradle/resources/i18n/GradleBundle.properties
index a23cb0a5..7c1c845 100644
--- a/plugins/gradle/resources/i18n/GradleBundle.properties
+++ b/plugins/gradle/resources/i18n/GradleBundle.properties
@@ -1,23 +1,14 @@
 gradle.name=Gradle
-gradle.ide=IDE
 
-gradle.project.structure.tree.node.dependencies=dependencies
-
-gradle.config.text.use.wrapper=Use gradle wrapper (recommended)
-gradle.config.text.use.wrapper.disabled=Use gradle wrapper (not configured for the current project)
-gradle.config.text.use.local.distribution=Use local gradle distribution
+gradle.settings.text.use.wrapper=Use gradle wrapper (recommended)
+gradle.settings.text.use.wrapper.disabled=Use gradle wrapper (not configured for the current project)
+gradle.settings..text.use.local.distribution=Use local gradle distribution
 
 gradle.settings.label.select.project=Gradle project:
 gradle.settings.text.home.path=Gradle home:
 gradle.settings.text.service.dir.path=Service directory path:
 gradle.settings.title.service.dir.path=Select gradle service directory to use
-<<<<<<< HEAD
-<<<<<<< HEAD
-=======
 gradle.settings.text.use.auto.import=Use auto-import
->>>>>>> 38a9775... IDEA-104500 Gradle: Allow to reuse common logic for other external systems
-=======
->>>>>>> 5fd2c47... IDEA-104500 Gradle: Allow to reuse common logic for other external systems
 gradle.import.progress.text=Building Gradle project info
 gradle.import.label.project.structure=Project structure:
 gradle.import.label.details=Details:
diff --git a/plugins/gradle/src/META-INF/plugin.xml b/plugins/gradle/src/META-INF/plugin.xml
index 2000bee..84b45e3 100644
--- a/plugins/gradle/src/META-INF/plugin.xml
+++ b/plugins/gradle/src/META-INF/plugin.xml
@@ -28,6 +28,8 @@
   </extensionPoints>
 
   <extensions defaultExtensionNs="com.intellij">
+    <postStartupActivity implementation="com.intellij.openapi.externalSystem.service.ExternalSystemStartupActivity"/>
+
     <errorHandler implementation="com.intellij.diagnostic.ITNReporter"/>
     <projectImportProvider implementation="org.jetbrains.plugins.gradle.service.settings.GradleProjectImportProvider"/>
     <projectImportBuilder implementation="org.jetbrains.plugins.gradle.service.settings.GradleProjectImportBuilder"/>
@@ -36,10 +38,9 @@
                          key="gradle.name" bundle="i18n.GradleBundle"/>
     <library.presentationProvider implementation="org.jetbrains.plugins.gradle.config.GradleLibraryPresentationProvider" order="last"/>
     <java.elementFinder implementation="org.jetbrains.plugins.gradle.config.GradleClassFinder"/>
-    <!--<projectOpenProcessor implementation="com.intellij.openapi.externalSystem.service.project.wizard.ExternalProjectOpenProcessor"/>-->
+    <projectOpenProcessor implementation="org.jetbrains.plugins.gradle.service.settings.GradleProjectOpenProcessor"/>
 
     <externalSystemManager implementation="org.jetbrains.plugins.gradle.GradleManager"/>
-    <postStartupActivity implementation="org.jetbrains.plugins.gradle.sync.GradleStartupActivity"/>
 
     <applicationService serviceImplementation="org.jetbrains.plugins.gradle.service.GradleInstallationManager"/>
 
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java
index f7bd4be..1f7f6f1 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java
@@ -31,6 +31,7 @@
 import com.intellij.openapi.module.StdModuleTypes;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.NotNullLazyValue;
+import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.util.Function;
@@ -44,10 +45,7 @@
 import org.jetbrains.plugins.gradle.service.GradleInstallationManager;
 import org.jetbrains.plugins.gradle.service.project.GradleProjectResolver;
 import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverExtension;
-import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings;
-import org.jetbrains.plugins.gradle.settings.GradleLocalSettings;
-import org.jetbrains.plugins.gradle.settings.GradleSettings;
-import org.jetbrains.plugins.gradle.settings.GradleSettingsListener;
+import org.jetbrains.plugins.gradle.settings.*;
 import org.jetbrains.plugins.gradle.util.GradleBundle;
 import org.jetbrains.plugins.gradle.util.GradleConstants;
 
@@ -61,8 +59,12 @@
  * @author Denis Zhdanov
  * @since 4/10/13 1:19 PM
  */
-public class GradleManager
-  implements ExternalSystemManager<GradleSettingsListener, GradleSettings, GradleLocalSettings, GradleExecutionSettings>
+public class GradleManager implements ExternalSystemManager<
+  GradleProjectSettings,
+  GradleSettingsListener,
+  GradleSettings,
+  GradleLocalSettings,
+  GradleExecutionSettings>
 {
 
   private static final Logger LOG = Logger.getInstance("#" + GradleManager.class.getName());
@@ -91,11 +93,6 @@
     return GradleConstants.SYSTEM_ID;
   }
 
-  @Override
-  public boolean isReady(@NotNull Project project) {
-    return myInstallationManager.getGradleHome(project) != null;
-  }
-
   @NotNull
   @Override
   public Function<Project, GradleSettings> getSettingsProvider() {
@@ -120,15 +117,15 @@
 
   @NotNull
   @Override
-  public Function<Project, GradleExecutionSettings> getExecutionSettingsProvider() {
-    return new Function<Project, GradleExecutionSettings>() {
+  public Function<Pair<Project, String>, GradleExecutionSettings> getExecutionSettingsProvider() {
+    return new Function<Pair<Project, String>, GradleExecutionSettings>() {
 
       private final GradleJavaHelper myJavaHelper = new GradleJavaHelper();
 
       @Override
-      public GradleExecutionSettings fun(Project project) {
-        GradleSettings settings = GradleSettings.getInstance(project);
-        File gradleHome = myInstallationManager.getGradleHome(project);
+      public GradleExecutionSettings fun(Pair<Project, String> pair) {
+        GradleSettings settings = GradleSettings.getInstance(pair.first);
+        File gradleHome = myInstallationManager.getGradleHome(pair.first, pair.second);
         String localGradlePath = null;
         if (gradleHome != null) {
           try {
@@ -141,11 +138,13 @@
         }
         GradleExecutionSettings result = new GradleExecutionSettings(localGradlePath,
                                                                      settings.getServiceDirectoryPath(),
-                                                                     settings.isPreferLocalInstallationToWrapper());
+                                                                     false);
+        // TODO den implement
+//                                                                     settings.isPreferLocalInstallationToWrapper());
         for (GradleProjectResolverExtension extension : RESOLVER_EXTENSIONS.getValue()) {
           result.addResolverExtensionClass(extension.getClass().getName());
         }
-        String javaHome = myJavaHelper.getJdkHome(project);
+        String javaHome = myJavaHelper.getJdkHome(pair.first);
         if (!StringUtil.isEmpty(javaHome)) {
           LOG.info("Instructing gradle to use java from " + javaHome);
         }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java
index 5410646..451fdd9 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/AbstractGradleLinkedProjectAction.java
@@ -55,9 +55,10 @@
     if (project == null) {
       return null;
     }
-    
-    final String path = GradleSettings.getInstance(project).getLinkedExternalProjectPath();
-    return path == null ? null : new Pair<Project, String>(project, path);
+    // TODO den implement
+   return null; 
+//    final String path = GradleSettings.getInstance(project).getLinkedExternalProjectPath();
+//    return path == null ? null : new Pair<Project, String>(project, path);
   }
 
   protected abstract void doUpdate(@NotNull AnActionEvent event, @NotNull Project project, @NotNull String linkedProjectPath);
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRefreshProjectAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRefreshProjectAction.java
index f92ca08..454917c 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRefreshProjectAction.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRefreshProjectAction.java
@@ -62,12 +62,13 @@
     FileDocumentManager.getInstance().saveAllDocuments();
 
     GradleConfigNotificationManager notificationManager = ServiceManager.getService(project, GradleConfigNotificationManager.class);
-    if (!GradleUtil.isGradleAvailable(project)) {
-      notificationManager.processUnknownGradleHome();
-      return;
-    }
+    // TODO den implement
+    //if (!GradleUtil.isGradleAvailable(project)) {
+    //  notificationManager.processUnknownGradleHome();
+    //  return;
+    //}
 
-    myErrorMessage.set(null);
-    ExternalSystemUtil.refreshProject(project, GradleConstants.SYSTEM_ID, myErrorMessage);
+    //myErrorMessage.set(null);
+    //ExternalSystemUtil.refreshProject(project, GradleConstants.SYSTEM_ID, myErrorMessage);
   }
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java
index ef22528..6f9dbfb 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleToolWindowHelpAction.java
@@ -23,10 +23,11 @@
       return;
     }
 
-    if (StringUtil.isEmpty(GradleSettings.getInstance(project).getLinkedExternalProjectPath())) {
-      event.getPresentation().setVisible(false);
-      return;
-    }
+    // TODO den implement
+//    if (StringUtil.isEmpty(GradleSettings.getInstance(project).getLinkedExternalProjectPath())) {
+//      event.getPresentation().setVisible(false);
+//      return;
+//    }
     event.getPresentation().setVisible(true);
     super.update(event);
   }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleGroovyConfigNotification.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleGroovyConfigNotification.java
index e9f7c76..89ec8b4 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleGroovyConfigNotification.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleGroovyConfigNotification.java
@@ -1,7 +1,9 @@
 package org.jetbrains.plugins.gradle.config;
 
 import com.intellij.openapi.externalSystem.service.project.PlatformFacade;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
 import com.intellij.openapi.module.Module;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import org.jetbrains.annotations.NotNull;
 import com.intellij.openapi.externalSystem.service.project.ModuleAwareContentRoot;
@@ -42,6 +44,14 @@
   public boolean hasFrameworkLibrary(@NotNull Module module) {
     // Expecting groovy library to always be available at the gradle distribution. I.e. consider that when correct gradle
     // distribution is defined for the project, groovy jar is there.
-    return super.hasFrameworkLibrary(module) || myLibraryManager.getAllLibraries(module.getProject()) != null;
+    if (super.hasFrameworkLibrary(module)) {
+      return true;
+    }
+    String linkedProjectPath = module.getOptionValue(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY);
+    if (StringUtil.isEmpty(linkedProjectPath)) {
+      return false;
+    }
+    assert linkedProjectPath != null;
+    return myLibraryManager.getAllLibraries(module.getProject(), linkedProjectPath) != null;
   }
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradlePatcher.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradlePatcher.java
index 9dd6b78..6b405fb 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradlePatcher.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradlePatcher.java
@@ -35,19 +35,19 @@
     }
 
     // Propagate gradle settings from the current project to the default project if necessary.
-    final GradleSettings defaultProjectSettings = GradleSettings.getInstance(defaultProject);
-    final GradleSettings currentProjectSettings = GradleSettings.getInstance(project);
-    String projectGradleHome = currentProjectSettings.getGradleHome();
-    String defaultGradleHome = defaultProjectSettings.getGradleHome();
-    if (StringUtil.isEmpty(projectGradleHome) || !StringUtil.isEmpty(defaultGradleHome)) {
-      return;
-    }
-    GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class);
-    File autodetectedGradleHome = libraryManager.getAutodetectedGradleHome();
-    // We don't want to store auto-detected value at the settings.
-    if (autodetectedGradleHome == null || !FileUtil.filesEqual(autodetectedGradleHome, new File(projectGradleHome))) {
-      // TODO den implement
+    // TODO den implement
+//    final GradleSettings defaultProjectSettings = GradleSettings.getInstance(defaultProject);
+//    final GradleSettings currentProjectSettings = GradleSettings.getInstance(project);
+//    String projectGradleHome = currentProjectSettings.getGradleHome();
+//    String defaultGradleHome = defaultProjectSettings.getGradleHome();
+//    if (StringUtil.isEmpty(projectGradleHome) || !StringUtil.isEmpty(defaultGradleHome)) {
+//      return;
+//    }
+//    GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class);
+//    File autodetectedGradleHome = libraryManager.getAutodetectedGradleHome();
+//    // We don't want to store auto-detected value at the settings.
+//    if (autodetectedGradleHome == null || !FileUtil.filesEqual(autodetectedGradleHome, new File(projectGradleHome))) {
 //      GradleSettings.applyGradleHome(projectGradleHome, defaultProject);
-    }
+//    }
   }
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradlePositionManager.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradlePositionManager.java
index ed462b0..34bc3d0 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradlePositionManager.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradlePositionManager.java
@@ -16,12 +16,14 @@
 package org.jetbrains.plugins.gradle.config;
 
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleUtilCore;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.ProjectRootManager;
 import com.intellij.openapi.util.Key;
 import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VfsUtil;
 import com.intellij.openapi.vfs.VfsUtilCore;
@@ -127,7 +129,12 @@
 
   @Nullable
   private ClassLoader createGradleClassLoader(@NotNull Module module) {
-    final VirtualFile sdkHome = myLibraryManager.getGradleHome(module, module.getProject());
+    String linkedProjectPath = module.getOptionValue(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY);
+    if (StringUtil.isEmpty(linkedProjectPath)) {
+      return null;
+    }
+    assert linkedProjectPath != null;
+    final VirtualFile sdkHome = myLibraryManager.getGradleHome(module, module.getProject(), linkedProjectPath);
     if (sdkHome == null) {
       return null;
     }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleScriptType.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleScriptType.java
index daa5cb6b..9fb7c2b 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleScriptType.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleScriptType.java
@@ -21,10 +21,9 @@
 import com.intellij.execution.configurations.JavaParameters;
 import com.intellij.execution.configurations.RunProfile;
 import com.intellij.openapi.components.ServiceManager;
-import com.intellij.openapi.externalSystem.service.settings.AbstractExternalProjectConfigurable;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleUtilCore;
-import com.intellij.openapi.options.ShowSettingsUtil;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.OrderEnumerator;
 import com.intellij.openapi.util.io.FileUtil;
@@ -182,9 +181,9 @@
           }
         }
         final GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class);
-        if (libraryManager.getGradleHome(module, project) == null) {
-          int result = 0;
-          // TODO den implement
+        // TODO den implement
+        //if (libraryManager.getGradleHome(module, project) == null) {
+        //  int result = 0;
 //          int result = Messages.showOkCancelDialog(
 //            ExternalSystemBundle.message("gradle.run.no.sdk.text"),
 //            ExternalSystemBundle.message("gradle.run.no.sdk.title"),
@@ -193,10 +192,10 @@
 //          if (result == 0) {
 //            ShowSettingsUtil.getInstance().editConfigurable(project, new AbstractExternalProjectConfigurable(project));
 //          }
-          if (libraryManager.getGradleHome(module, project) == null) {
-            return false;
-          }
-        }
+//          if (libraryManager.getGradleHome(module, project) == null) {
+//            return false;
+//          }
+//        }
         return true;
       }
 
@@ -211,7 +210,15 @@
         String scriptParameters = configuration.getScriptParameters();
 
         final GradleInstallationManager libraryManager = ServiceManager.getService(GradleInstallationManager.class);
-        final VirtualFile gradleHome = libraryManager.getGradleHome(module, project);
+        if (module == null) {
+          throw new CantRunException("Target module is undefined");
+        }
+        String linkedProjectPath = module.getOptionValue(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY);
+        if (StringUtil.isEmpty(linkedProjectPath)) {
+          throw new CantRunException(String.format("Module '%s' is not backed by gradle", module.getName()));
+        }
+        assert linkedProjectPath != null;
+        final VirtualFile gradleHome = libraryManager.getGradleHome(module, project, linkedProjectPath);
         assert gradleHome != null;
 
         params.setMainClass(findMainClass(gradleHome, script, project));
@@ -219,7 +226,8 @@
         final File[] groovyJars = GroovyConfigUtils.getGroovyAllJars(gradleHome.getPath() + "/lib/");
         if (groovyJars.length > 0) {
           params.getClassPath().add(groovyJars[0].getAbsolutePath());
-        } else if (module != null) {
+        }
+        else {
           final VirtualFile groovyJar = findGroovyJar(module);
           if (groovyJar != null) {
             params.getClassPath().add(groovyJar);
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java
index 2c3e04a..33f2ae9 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleSettingsListenerAdapter.java
@@ -1,8 +1,12 @@
 package org.jetbrains.plugins.gradle.config;
 
+import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.gradle.settings.GradleProjectSettings;
 import org.jetbrains.plugins.gradle.settings.GradleSettingsListener;
 
+import java.util.Collection;
+
 /**
  * @author Denis Zhdanov
  * @since 3/13/12 3:53 PM
@@ -10,15 +14,11 @@
 public abstract class GradleSettingsListenerAdapter implements GradleSettingsListener {
 
   @Override
-  public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath) {
+  public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath, @NotNull String linkedProjectPath) {
   }
 
   @Override
-  public void onLinkedProjectPathChange(@Nullable String oldPath, @Nullable String newPath) {
-  }
-
-  @Override
-  public void onPreferLocalGradleDistributionToWrapperChange(boolean currentValue) {
+  public void onPreferLocalGradleDistributionToWrapperChange(boolean currentValue, @NotNull String linkedProjectPath) {
   }
 
   @Override
@@ -26,7 +26,15 @@
   }
 
   @Override
-  public void onUseAutoImportChange(boolean currentValue) {
+  public void onProjectsLinked(@NotNull Collection<GradleProjectSettings> settings) {
+  }
+
+  @Override
+  public void onProjectsUnlinked(@NotNull Collection<String> linkedProjectPaths) {
+  }
+
+  @Override
+  public void onUseAutoImportChange(boolean currentValue, @NotNull String linkedProjectPath) {
   }
 
   @Override
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java
index 91da39a..4d5b803 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleToolWindowPanel.java
@@ -60,16 +60,16 @@
 
     MessageBusConnection connection = project.getMessageBus().connect(project);
     connection.subscribe(GradleSettingsListener.TOPIC, new GradleSettingsListenerAdapter() {
-      
-      @Override public void onLinkedProjectPathChange(@Nullable String oldPath, @Nullable String newPath) {
-        if (StringUtil.isEmpty(newPath)) {
-          myLayout.show(myContent, NON_LINKED_CARD_NAME);
-          return;
-        }
-        if (StringUtil.isEmpty(oldPath) && !StringUtil.isEmpty(newPath)) {
-          myLayout.show(myContent, CONTENT_CARD_NAME);
-        }
-      }
+      // TODO den implement
+//      @Override public void onLinkedProjectConfigChange(@Nullable String oldPath, @Nullable String newPath) {
+//        if (StringUtil.isEmpty(newPath)) {
+//          myLayout.show(myContent, NON_LINKED_CARD_NAME);
+//          return;
+//        }
+//        if (StringUtil.isEmpty(oldPath) && !StringUtil.isEmpty(newPath)) {
+//          myLayout.show(myContent, CONTENT_CARD_NAME);
+//        }
+//      }
     });
   }
 
@@ -118,7 +118,9 @@
    */
   public void update() {
     final GradleSettings settings = GradleSettings.getInstance(myProject);
-    String cardToShow = StringUtil.isEmpty(settings.getLinkedExternalProjectPath()) ? NON_LINKED_CARD_NAME : CONTENT_CARD_NAME;
+    // TODO den implement
+    String cardToShow = "sf";
+//    String cardToShow = StringUtil.isEmpty(settings.getLinkedExternalProjectPath()) ? NON_LINKED_CARD_NAME : CONTENT_CARD_NAME;
     myLayout.show(myContent, cardToShow);
     boolean showToolbar = cardToShow != NON_LINKED_CARD_NAME;
     for (JComponent component : getToolbarControls()) {
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/internal/task/ExternalSystemExecuteTaskTask.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/internal/task/ExternalSystemExecuteTaskTask.java
index 6355659..6fa7cab 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/internal/task/ExternalSystemExecuteTaskTask.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/internal/task/ExternalSystemExecuteTaskTask.java
@@ -40,7 +40,7 @@
                                        @NotNull String gradleProjectPath,
                                        @NotNull List<String> tasksToExecute)
   {
-    super(externalSystemId, ExternalSystemTaskType.EXECUTE_TASK, project);
+    super(externalSystemId, ExternalSystemTaskType.EXECUTE_TASK, project, gradleProjectPath);
     myGradleProjectPath = gradleProjectPath;
     myTasksToExecute = tasksToExecute;
   }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/internal/task/ExternalSystemRefreshTasksListTask.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/internal/task/ExternalSystemRefreshTasksListTask.java
index be51849..243b62c 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/internal/task/ExternalSystemRefreshTasksListTask.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/internal/task/ExternalSystemRefreshTasksListTask.java
@@ -36,7 +36,7 @@
                                             @NotNull Project project,
                                             @NotNull String projectPath)
   {
-    super(externalSystemId, ExternalSystemTaskType.REFRESH_TASKS_LIST, project);
+    super(externalSystemId, ExternalSystemTaskType.REFRESH_TASKS_LIST, project, projectPath);
     myProjectPath = projectPath;
   }
 
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/notification/GradleConfigNotificationManager.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/notification/GradleConfigNotificationManager.java
index 7258e26..5475cba 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/notification/GradleConfigNotificationManager.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/notification/GradleConfigNotificationManager.java
@@ -40,7 +40,6 @@
     myProject = project;
     myLibraryManager = manager;
     final GradleSettingsListenerAdapter handler = new GradleSettingsListenerAdapter() {
-      @Override
       public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath) {
         processGradleHomeChange();
       }
@@ -51,15 +50,16 @@
 
   private void processGradleHomeChange() {
     EditorNotifications.getInstance(myProject).updateAllNotifications();
-
-    if (!GradleUtil.isGradleAvailable(myProject)) {
-      return;
-    }
-
-    final Notification notification = myNotification.get();
-    if (notification != null && myNotification.compareAndSet(notification, null)) {
-      notification.expire();
-    }
+    
+    // TODO den implement
+    //if (!GradleUtil.isGradleAvailable(myProject)) {
+    //  return;
+    //}
+    //
+    //final Notification notification = myNotification.get();
+    //if (notification != null && myNotification.compareAndSet(notification, null)) {
+    //  notification.expire();
+    //}
   }
 
   public void processRefreshError(@NotNull String message) {
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/GradleInstallationManager.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/GradleInstallationManager.java
index bdc81a6..2b3290c 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/GradleInstallationManager.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/GradleInstallationManager.java
@@ -1,7 +1,10 @@
 package org.jetbrains.plugins.gradle.service;
 
+import com.intellij.openapi.externalSystem.service.project.PlatformFacade;
+import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.project.ProjectManager;
 import com.intellij.openapi.roots.OrderEnumerator;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.JarFileSystem;
@@ -9,7 +12,9 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.gradle.settings.GradleProjectSettings;
 import org.jetbrains.plugins.gradle.settings.GradleSettings;
 import org.jetbrains.plugins.gradle.util.GradleEnvironment;
 import org.jetbrains.plugins.gradle.util.GradleLog;
@@ -17,6 +22,7 @@
 import org.jetbrains.plugins.groovy.config.GroovyConfigUtils;
 
 import java.io.File;
+import java.io.FileFilter;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
@@ -45,18 +51,25 @@
     GRADLE_START_FILE_NAMES = System.getProperty("gradle.start.file.names", "gradle:gradle.cmd:gradle.sh").split(":");
     GRADLE_ENV_PROPERTY_NAME = System.getProperty("gradle.home.env.key", "GRADLE_HOME");
   }
+  
+  @NotNull private final PlatformFacade myPlatformFacade;
+
+  public GradleInstallationManager(@NotNull PlatformFacade facade) {
+    myPlatformFacade = facade;
+  }
 
   /**
    * Allows to get file handles for the gradle binaries to use.
    *
-   * @param project  target project
-   * @return file handles for the gradle binaries; <code>null</code> if gradle is not discovered
+   * @param project            target project
+   * @param linkedProjectPath  path to the target external project's config
+   * @return                   file handles for the gradle binaries; <code>null</code> if gradle is not discovered
    */
   @Nullable
-  public Collection<File> getAllLibraries(@Nullable Project project) {
+  public Collection<File> getAllLibraries(@Nullable Project project, @NotNull String linkedProjectPath) {
 
     // Manually defined gradle home
-    File gradleHome = getGradleHome(project);
+    File gradleHome = getGradleHome(project, linkedProjectPath);
 
     if (gradleHome == null || !gradleHome.isDirectory()) {
       return null;
@@ -79,16 +92,17 @@
   /**
    * Tries to return file handle that points to the gradle installation home.
    *
-   * @param project  target project (if any)
-   * @return file handle that points to the gradle installation home (if any)
+   * @param project            target project (if any)
+   * @param linkedProjectPath  path to the target linked project config
+   * @return                   file handle that points to the gradle installation home (if any)
    */
   @Nullable
-  public File getGradleHome(@Nullable Project project) {
-    File result = getWrapperHome(project);
+  public File getGradleHome(@Nullable Project project, @NotNull String linkedProjectPath) {
+    File result = getWrapperHome(project, linkedProjectPath);
     if (result != null) {
       return result;
     }
-    result = getManuallyDefinedGradleHome(project);
+    result = getManuallyDefinedGradleHome(project, linkedProjectPath);
     if (result != null) {
       return result;
     }
@@ -137,33 +151,33 @@
    * @return         gradle home derived from the settings of the given entities (if any); <code>null</code> otherwise
    */
   @Nullable
-  public VirtualFile getGradleHome(@Nullable Module module, @Nullable Project project) {
+  public VirtualFile getGradleHome(@Nullable Module module, @Nullable Project project, @NotNull String linkedProjectPath) {
     final VirtualFile result = getGradleHome(module);
     if (result != null) {
       return result;
     }
 
-    final File home = getGradleHome(project);
+    final File home = getGradleHome(project, linkedProjectPath);
     return home == null ? null : LocalFileSystem.getInstance().refreshAndFindFileByIoFile(home);
   }
 
   @Nullable
-  public File getWrapperHome(@Nullable Project project) {
+  public File getWrapperHome(@Nullable Project project, @NotNull String linkedProjectPath) {
     if (project == null) {
       return null;
     }
-    GradleSettings settings = GradleSettings.getInstance(project);
-    String gradleProjectPath = settings.getLinkedExternalProjectPath();
-    if (StringUtil.isEmpty(gradleProjectPath)) {
+
+    GradleProjectSettings settings = GradleSettings.getInstance(project).getLinkedProjectSettings(linkedProjectPath);
+    if (settings == null) {
       return null;
     }
-
+    
     if (settings.isPreferLocalInstallationToWrapper()) {
       return null;
     }
 
-    String version = GradleUtil.getWrapperVersion(gradleProjectPath);
-    if (version == null) {
+    String distribution = GradleUtil.getWrapperDistribution(linkedProjectPath);
+    if (distribution == null) {
       return null;
     }
     File gradleSystemDir = new File(System.getProperty("user.home"), ".gradle");
@@ -176,7 +190,7 @@
       return null;
     }
 
-    File targetDistributionHome = new File(gradleWrapperDistributionsHome, String.format("gradle-%s-bin", version));
+    File targetDistributionHome = new File(gradleWrapperDistributionsHome, distribution);
     if (!targetDistributionHome.isDirectory()) {
       return null;
     }
@@ -187,13 +201,18 @@
       return null;
     }
 
-    File result = new File(files[0], String.format("gradle-%s", version));
-    if (result.isDirectory()) {
-      return result;
-    }
-    else {
+    File[] distFiles = files[0].listFiles(new FileFilter() {
+      @Override
+      public boolean accept(File f) {
+        return f.isDirectory();
+      }
+    });
+    if (distFiles == null || distFiles.length != 1) {
+      // There should exist only the gradle directory in the distribution directory
       return null;
     }
+
+    return distFiles[0].isDirectory() ? distFiles[0] : null;
   }
 
   /**
@@ -203,11 +222,15 @@
    * @return         path to the gradle distribution (if the one is explicitly configured)
    */
   @Nullable
-  public File getManuallyDefinedGradleHome(@Nullable Project project) {
+  public File getManuallyDefinedGradleHome(@Nullable Project project, @NotNull String linkedProjectPath) {
     if (project == null) {
       return null;
     }
-    GradleSettings settings = GradleSettings.getInstance(project);
+    GradleProjectSettings settings = GradleSettings.getInstance(project).getLinkedProjectSettings(linkedProjectPath);
+    if (settings == null) {
+      return null;
+    }
+    
     String path = settings.getGradleHome();
     if (path == null) {
       return null;
@@ -360,21 +383,33 @@
    */
   @Nullable
   public List<VirtualFile> getClassRoots(@Nullable Project project) {
-    final Collection<File> libraries = getAllLibraries(project);
-    if (libraries == null) {
-      return null;
+    if (project == null) {
+      project = ProjectManager.getInstance().getDefaultProject();
     }
-    final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
-    final JarFileSystem jarFileSystem = JarFileSystem.getInstance();
-    List<VirtualFile> result = new ArrayList<VirtualFile>();
-    for (File file : libraries) {
-      if (ANY_GRADLE_JAR_FILE_PATTERN.matcher(file.getName()).matches() || GroovyConfigUtils.matchesGroovyAll(file.getName())) {
-        final VirtualFile virtualFile = localFileSystem.refreshAndFindFileByIoFile(file);
-        if (virtualFile != null) {
-          ContainerUtil.addIfNotNull(result, jarFileSystem.getJarRootForLocalFile(virtualFile));
+
+    for (Module module : myPlatformFacade.getModules(project)) {
+      String path = module.getOptionValue(ExternalSystemConstants.LINKED_PROJECT_PATH_KEY);
+      if (StringUtil.isEmpty(path)) {
+        continue;
+      }
+      assert path != null;
+      final Collection<File> libraries = getAllLibraries(project, path);
+      if (libraries == null) {
+        continue;
+      }
+      final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
+      final JarFileSystem jarFileSystem = JarFileSystem.getInstance();
+      List<VirtualFile> result = new ArrayList<VirtualFile>();
+      for (File file : libraries) {
+        if (ANY_GRADLE_JAR_FILE_PATTERN.matcher(file.getName()).matches() || GroovyConfigUtils.matchesGroovyAll(file.getName())) {
+          final VirtualFile virtualFile = localFileSystem.refreshAndFindFileByIoFile(file);
+          if (virtualFile != null) {
+            ContainerUtil.addIfNotNull(result, jarFileSystem.getJarRootForLocalFile(virtualFile));
+          }
         }
       }
+      return result;
     }
-    return result;
+    return null;
   }
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
index 25d2dcd..f9551ae 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
@@ -109,7 +109,7 @@
   private static DataNode<ProjectData> populateProject(@NotNull IdeaProject project, @NotNull String projectPath) {
     String projectDirPath = ExternalSystemApiUtil.toCanonicalPath(PathUtil.getParentPath(projectPath));
 
-    ProjectData projectData = new ProjectData(GradleConstants.SYSTEM_ID, projectDirPath);
+    ProjectData projectData = new ProjectData(GradleConstants.SYSTEM_ID, projectDirPath, projectPath);
     projectData.setName(project.getName());
 
     // Gradle API doesn't expose project compile output path yet.
@@ -143,7 +143,7 @@
       }
       ProjectData projectData = ideProject.getData();
       ModuleData ideModule = new ModuleData(
-        GradleConstants.SYSTEM_ID, StdModuleTypes.JAVA.getId(), moduleName, projectData.getProjectFileDirectoryPath()
+        GradleConstants.SYSTEM_ID, StdModuleTypes.JAVA.getId(), moduleName, projectData.getIdeProjectFileDirectoryPath()
       );
       Pair<DataNode<ModuleData>, IdeaModule> previouslyParsedModule = result.get(moduleName);
       if (previouslyParsedModule != null) {
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java
index 6573307..2aa5532 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleConfigurable.java
@@ -15,95 +15,45 @@
  */
 package org.jetbrains.plugins.gradle.service.settings;
 
-import com.intellij.openapi.components.ServiceManager;
-import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.externalSystem.model.settings.LocationSettingType;
-import com.intellij.openapi.externalSystem.service.settings.AbstractExternalProjectConfigurable;
-import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil;
-import com.intellij.openapi.fileChooser.FileChooserDescriptor;
+import com.intellij.openapi.externalSystem.service.settings.AbstractExternalSystemConfigurable;
+import com.intellij.openapi.externalSystem.service.settings.ExternalSettingsControl;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.project.ProjectManager;
-import com.intellij.openapi.ui.MessageType;
-import com.intellij.openapi.ui.TextComponentAccessor;
-import com.intellij.openapi.ui.TextFieldWithBrowseButton;
-import com.intellij.openapi.util.Comparing;
-import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.ui.components.JBLabel;
-import com.intellij.ui.components.JBRadioButton;
-import com.intellij.util.Alarm;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.service.GradleInstallationManager;
+import org.jetbrains.plugins.gradle.settings.GradleProjectSettings;
 import org.jetbrains.plugins.gradle.settings.GradleSettings;
 import org.jetbrains.plugins.gradle.settings.GradleSettingsListener;
-import org.jetbrains.plugins.gradle.util.GradleBundle;
 import org.jetbrains.plugins.gradle.util.GradleConstants;
-import org.jetbrains.plugins.gradle.util.GradleEnvironment;
-import org.jetbrains.plugins.gradle.util.GradleUtil;
-
-import javax.swing.*;
-import javax.swing.event.DocumentEvent;
-import javax.swing.event.DocumentListener;
-import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
-import java.io.File;
-import java.util.concurrent.TimeUnit;
 
 /**
  * @author Denis Zhdanov
- * @since 4/15/13 2:50 PM
+ * @since 4/30/13 11:42 PM
  */
-public class GradleConfigurable extends AbstractExternalProjectConfigurable<GradleSettingsListener, GradleSettings> {
-
-  private static final Logger LOG = Logger.getInstance("#" + GradleConfigurable.class.getName());
+public class GradleConfigurable extends AbstractExternalSystemConfigurable<GradleProjectSettings, GradleSettingsListener, GradleSettings> {
 
   @NonNls public static final String HELP_TOPIC = "reference.settingsdialog.project.gradle";
 
-  private static final long BALLOON_DELAY_MILLIS = TimeUnit.SECONDS.toMillis(1);
-
-  @NotNull private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
-
-  @NotNull private LocationSettingType myGradleHomeSettingType = LocationSettingType.UNKNOWN;
-
-  @NotNull private JLabel myGradleHomeLabel       = new JBLabel(GradleBundle.message("gradle.settings.text.home.path"));
-  @NotNull private JLabel myServiceDirectoryLabel = new JBLabel(GradleBundle.message("gradle.settings.text.service.dir.path"));
-
-  @NotNull private final Helper myHelper;
-
-  @NotNull private TextFieldWithBrowseButton myGradleHomePathField;
-  @NotNull private TextFieldWithBrowseButton myServiceDirectoryPathField;
-  @NotNull private JBRadioButton             myUseWrapperButton;
-  @NotNull private JBRadioButton             myUseLocalDistributionButton;
-
-  private boolean myShowBalloonIfNecessary;
-  private boolean myGradleHomeModifiedByUser;
-  private boolean myServiceDirectoryModifiedByUser;
-
-  public GradleConfigurable(@Nullable Project project) {
-    this(project, ServiceManager.getService(GradleInstallationManager.class));
+  public GradleConfigurable(@NotNull Project project) {
+    super(project, GradleConstants.SYSTEM_ID);
   }
 
-  public GradleConfigurable(@Nullable Project project, @NotNull GradleInstallationManager installationManager) {
-    super(project, GradleConstants.SYSTEM_ID, false);
-    myHelper = new DefaultHelper(installationManager);
-    init(false);
+  @NotNull
+  @Override
+  protected ExternalSettingsControl<GradleProjectSettings> createProjectSettingsControl(@NotNull GradleProjectSettings settings) {
+    return new GradleProjectSettingsControl(settings);
   }
 
-  public GradleConfigurable(@Nullable Project project, @NotNull Helper helper) {
-    super(project, GradleConstants.SYSTEM_ID, true);
-    myHelper = helper;
-    init(true);
+  @Nullable
+  @Override
+  protected ExternalSettingsControl<GradleSettings> createSystemSettingsControl(@NotNull GradleSettings settings) {
+    return new GradleSystemSettingsControl(settings);
   }
 
-  private void init(boolean testMode) {
-    initLinkedProjectPathControl();
-    initWrapperVsLocalControls();
-    initGradleHome(testMode);
-    initServiceDirectoryHome();
+  @NotNull
+  @Override
+  protected GradleProjectSettings newProjectSettings() {
+    return new GradleProjectSettings();
   }
 
   @NotNull
@@ -113,570 +63,8 @@
   }
 
   @NotNull
+  @Override
   public String getHelpTopic() {
     return HELP_TOPIC;
   }
-
-  @NotNull
-  @Override
-  protected JComponent buildContent(boolean testMode) {
-    JPanel result = new JPanel(new GridBagLayout()) {
-      @Override
-      public void paint(Graphics g) {
-        super.paint(g);
-        showBalloonIfNecessary();
-      }
-    };
-    result.addPropertyChangeListener(new PropertyChangeListener() {
-      @Override
-      public void propertyChange(PropertyChangeEvent evt) {
-        if (!"ancestor".equals(evt.getPropertyName())) {
-          return;
-        }
-
-        // Configure the balloon to show on initial configurable drawing.
-        myShowBalloonIfNecessary = evt.getNewValue() != null && evt.getOldValue() == null;
-
-        if (evt.getNewValue() == null && evt.getOldValue() != null) {
-          // Cancel delayed balloons when the configurable is hidden.
-          myAlarm.cancelAllRequests();
-        }
-      }
-    });
-    return result;
-  }
-  
-  protected void fillContent(@NotNull JComponent content) {
-    // Provide radio buttons if gradle wrapper can be used for particular project.
-    content.add(myUseWrapperButton, getFillLineConstraints());
-    content.add(myUseLocalDistributionButton, getFillLineConstraints());
-
-    content.add(myGradleHomeLabel, getLabelConstraints());
-    content.add(myGradleHomePathField, getFillLineConstraints());
-
-    Insets insets = new Insets(5, 0, 0, 0);
-    content.add(myServiceDirectoryLabel, getLabelConstraints().insets(insets));
-    content.add(myServiceDirectoryPathField, getFillLineConstraints().insets(insets));
-  }
-
-  private void initLinkedProjectPathControl() {
-    getLinkedExternalProjectPathField().getTextField().getDocument().addDocumentListener(new DocumentListener() {
-      @Override
-      public void insertUpdate(DocumentEvent e) {
-        onLinkedProjectPathChange();
-      }
-
-      @Override
-      public void removeUpdate(DocumentEvent e) {
-        onLinkedProjectPathChange();
-      }
-
-      @Override
-      public void changedUpdate(DocumentEvent e) {
-        onLinkedProjectPathChange();
-      }
-    });
-
-  }
-  
-  private void initWrapperVsLocalControls() {
-    ActionListener listener = new ActionListener() {
-      @Override
-      public void actionPerformed(ActionEvent e) {
-        boolean enabled = e.getSource() == myUseLocalDistributionButton;
-        myGradleHomePathField.setEnabled(enabled);
-        if (enabled) {
-          showBalloonIfNecessary();
-        }
-        else {
-          myAlarm.cancelAllRequests();
-        }
-      }
-    };
-    myUseWrapperButton = new JBRadioButton(GradleBundle.message("gradle.config.text.use.wrapper"), true);
-    myUseWrapperButton.addActionListener(listener);
-    myUseLocalDistributionButton = new JBRadioButton(GradleBundle.message("gradle.config.text.use.local.distribution"));
-    myUseLocalDistributionButton.addActionListener(listener);
-    ButtonGroup group = new ButtonGroup();
-    group.add(myUseWrapperButton);
-    group.add(myUseLocalDistributionButton);
-  }
-
-  private void initGradleHome(boolean testMode) {
-    myGradleHomePathField = new TextFieldWithBrowseButton();
-
-    FileChooserDescriptor fileChooserDescriptor = testMode ? new FileChooserDescriptor(true, false, false, false, false, false)
-                                                           : GradleUtil.getGradleHomeFileChooserDescriptor();
-
-    myGradleHomePathField.addBrowseFolderListener(
-      "",
-      GradleBundle.message("gradle.settings.text.home.path"),
-      null,
-      fileChooserDescriptor,
-      TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
-      false
-    );
-    myGradleHomePathField.getTextField().getDocument().addDocumentListener(new DocumentListener() {
-      @Override
-      public void insertUpdate(DocumentEvent e) {
-        useColorForPath(LocationSettingType.EXPLICIT_CORRECT, myGradleHomePathField);
-        myGradleHomeModifiedByUser = true;
-      }
-
-      @Override
-      public void removeUpdate(DocumentEvent e) {
-        useColorForPath(LocationSettingType.EXPLICIT_CORRECT, myGradleHomePathField);
-        myGradleHomeModifiedByUser = true;
-      }
-
-      @Override
-      public void changedUpdate(DocumentEvent e) {
-      }
-    });
-  }
-
-  private void initServiceDirectoryHome() {
-    myServiceDirectoryPathField = new TextFieldWithBrowseButton();
-    myServiceDirectoryPathField.addBrowseFolderListener(
-      "",
-      GradleBundle.message("gradle.settings.title.service.dir.path"),
-      getProject(),
-      new FileChooserDescriptor(false, true, false, false, false, false),
-      TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
-      false
-    );
-    myServiceDirectoryPathField.getTextField().getDocument().addDocumentListener(new DocumentListener() {
-      @Override
-      public void insertUpdate(DocumentEvent e) {
-        useColorForPath(LocationSettingType.EXPLICIT_CORRECT, myServiceDirectoryPathField);
-        myServiceDirectoryModifiedByUser = true;
-      }
-
-      @Override
-      public void removeUpdate(DocumentEvent e) {
-        useColorForPath(LocationSettingType.EXPLICIT_CORRECT, myServiceDirectoryPathField);
-        myServiceDirectoryModifiedByUser = true;
-      }
-
-      @Override
-      public void changedUpdate(DocumentEvent e) {
-      }
-    });
-  }
-
-  private void onLinkedProjectPathChange() {
-    String linkedProjectPath = getLinkedExternalProjectPathField().getText();
-    if (StringUtil.isEmpty(linkedProjectPath) || !myHelper.isGradleWrapperDefined(linkedProjectPath)) {
-      myUseWrapperButton.setEnabled(false);
-      myUseWrapperButton.setText(GradleBundle.message("gradle.config.text.use.wrapper.disabled"));
-      myUseLocalDistributionButton.setSelected(true);
-    }
-    else {
-      myUseWrapperButton.setText(GradleBundle.message("gradle.config.text.use.wrapper"));
-      myUseWrapperButton.setEnabled(true);
-      myUseWrapperButton.setSelected(true);
-      myGradleHomePathField.setEnabled(false);
-    }
-  }
-
-  @NotNull
-  @Override
-  protected FileChooserDescriptor getLinkedProjectConfigDescriptor() {
-    return GradleUtil.getGradleProjectFileChooserDescriptor();
-  }
-
-  @NotNull
-  public TextFieldWithBrowseButton getGradleHomePathField() {
-    return myGradleHomePathField;
-  }
-
-  @Nullable
-  public String getGradleHomePath() {
-    return myGradleHomePathField.getText();
-  }
-
-  public boolean isPreferLocalInstallationToWrapper() {
-    return myUseLocalDistributionButton.isSelected();
-  }
-
-  @NotNull
-  JBRadioButton getUseWrapperButton() {
-    return myUseWrapperButton;
-  }
-
-  @NotNull
-  @Override
-  protected GradleSettings getSettings(@NotNull Project project) {
-    return myHelper.getSettings(project);
-  }
-
-  @Override
-  protected boolean isExtraSettingModified() {
-    Project project = getProject();
-    if (project == null) {
-      return false;
-    }
-    GradleSettings settings = getSettings(project);
-    if (myUseWrapperButton.isEnabled() && settings.isPreferLocalInstallationToWrapper() != myUseLocalDistributionButton.isSelected()) {
-      return true;
-    }
-
-    if (myGradleHomeModifiedByUser &&
-        !Comparing.equal(normalizePath(myGradleHomePathField.getText()), normalizePath(settings.getGradleHome())))
-    {
-      return true;
-    }
-
-    if (myServiceDirectoryModifiedByUser &&
-        !Comparing.equal(normalizePath(myServiceDirectoryPathField.getText()), normalizePath(settings.getServiceDirectoryPath())))
-    {
-      return true;
-    }
-
-    return false; 
-  }
-
-  @Override
-  protected void doApply(@NotNull String linkedExternalProjectPath, boolean useAutoImport) {
-    Project project = getProject();
-    if (project == null) {
-      return;
-    }
-    GradleSettings settings = getSettings(project);
-    final String gradleHomePath = getPathToUse(myGradleHomeModifiedByUser, settings.getGradleHome(), myGradleHomePathField.getText());
-    final String serviceDirPath = getPathToUse(myServiceDirectoryModifiedByUser,
-                                               settings.getServiceDirectoryPath(),
-                                               myServiceDirectoryPathField.getText());
-
-    final boolean preferLocalToWrapper;
-    if (myUseWrapperButton.isEnabled()) {
-      preferLocalToWrapper = myUseLocalDistributionButton.isSelected();
-    }
-    else {
-      // No point in switching the value if gradle wrapper is not defined for the target project.
-      preferLocalToWrapper = settings.isPreferLocalInstallationToWrapper();
-    }
-
-    myHelper.applySettings(linkedExternalProjectPath, gradleHomePath, preferLocalToWrapper, useAutoImport, serviceDirPath, project);
-
-    Project defaultProject = myHelper.getDefaultProject();
-    if (project != defaultProject) {
-      myHelper.applyPreferLocalInstallationToWrapper(preferLocalToWrapper, defaultProject);
-    }
-
-    if (isValidGradleHome(gradleHomePath)) {
-      if (myGradleHomeModifiedByUser) {
-        myGradleHomeSettingType = LocationSettingType.EXPLICIT_CORRECT;
-        // There is a possible case that user defines gradle home for particular open project. We want to apply that value
-        // to the default project as well if it's still non-defined.
-        if (defaultProject != project && !isValidGradleHome(GradleSettings.getInstance(defaultProject).getGradleHome())) {
-          GradleSettings.getInstance(defaultProject).setGradleHome(gradleHomePath);
-        }
-      }
-      else {
-        myGradleHomeSettingType = LocationSettingType.DEDUCED;
-      }
-    }
-    else if (preferLocalToWrapper) {
-      if (StringUtil.isEmpty(gradleHomePath)) {
-        myGradleHomeSettingType = LocationSettingType.UNKNOWN;
-      }
-      else {
-        myGradleHomeSettingType = LocationSettingType.EXPLICIT_INCORRECT;
-        myHelper.showBalloon(MessageType.ERROR, myGradleHomeSettingType, 0);
-      }
-    }
-  }
-
-  private boolean isValidGradleHome(@Nullable String path) {
-    if (StringUtil.isEmpty(path)) {
-      return false;
-    }
-    assert path != null;
-    return myHelper.isGradleSdkHome(new File(path));
-  }
-
-  @Override
-  protected void doReset() {
-    Project project = getProject();
-    if (project == null) {
-      project = ProjectManager.getInstance().getDefaultProject();
-    }
-
-    // Process gradle wrapper/local distribution settings.
-    // There are the following possible cases:
-    //   1. Default project or non-default project with no linked gradle project - 'use gradle wrapper whenever possible' check box
-    //      should be shown;
-    //   2. Non-default project with linked gradle project:
-    //      2.1. Gradle wrapper is configured for the target project - radio buttons on whether to use wrapper or particular local gradle
-    //           distribution should be show;
-    //      2.2. Gradle wrapper is not configured for the target project - radio buttons should be shown and 
-    //           'use gradle wrapper' option should be disabled;
-    useColorForPath(LocationSettingType.EXPLICIT_CORRECT, myGradleHomePathField);
-    useColorForPath(LocationSettingType.EXPLICIT_CORRECT, myServiceDirectoryPathField);
-
-    String linkedExternalProjectPath = getLinkedExternalProjectPathField().getText();
-    myUseWrapperButton.setVisible(isAlwaysShowLinkedProjectControls() || (!project.isDefault() && linkedExternalProjectPath != null));
-    myUseLocalDistributionButton.setVisible(isAlwaysShowLinkedProjectControls()
-                                            || (!project.isDefault() && linkedExternalProjectPath != null));
-    if (isAlwaysShowLinkedProjectControls() && linkedExternalProjectPath == null) {
-      myUseWrapperButton.setEnabled(false);
-      myUseLocalDistributionButton.setSelected(true);
-    }
-    else if (linkedExternalProjectPath != null) {
-      if (myHelper.isGradleWrapperDefined(linkedExternalProjectPath)) {
-        myUseWrapperButton.setEnabled(true);
-        myUseWrapperButton.setText(GradleBundle.message("gradle.config.text.use.wrapper"));
-        if (project.isDefault() || !getSettings(project).isPreferLocalInstallationToWrapper()) {
-          myUseWrapperButton.setSelected(true);
-          myGradleHomePathField.setEnabled(false);
-        }
-        else {
-          myUseLocalDistributionButton.setSelected(true);
-          myGradleHomePathField.setEnabled(true);
-        }
-      }
-      else {
-        myUseWrapperButton.setText(GradleBundle.message("gradle.config.text.use.wrapper.disabled"));
-        myUseWrapperButton.setEnabled(false);
-        myUseLocalDistributionButton.setSelected(true);
-      }
-    }
-
-    String localDistributionPath = getSettings(project).getGradleHome();
-    if (StringUtil.isEmpty(localDistributionPath)) {
-      myGradleHomeSettingType = LocationSettingType.UNKNOWN;
-      deduceGradleHomeIfPossible();
-    }
-    else {
-      assert localDistributionPath != null;
-      myGradleHomeSettingType = myHelper.isGradleSdkHome(new File(localDistributionPath)) ?
-                                LocationSettingType.EXPLICIT_CORRECT :
-                                LocationSettingType.EXPLICIT_INCORRECT;
-      myAlarm.cancelAllRequests();
-      if (myGradleHomeSettingType == LocationSettingType.EXPLICIT_INCORRECT && getSettings(project).isPreferLocalInstallationToWrapper()) {
-        myHelper.showBalloon(MessageType.ERROR, myGradleHomeSettingType, 0);
-      }
-      myGradleHomePathField.setText(localDistributionPath);
-    }
-
-    String serviceDirectoryPath = getSettings(project).getServiceDirectoryPath();
-    if (StringUtil.isEmpty(serviceDirectoryPath)) {
-      deduceServiceDirectoryIfPossible();
-    }
-    else {
-      myServiceDirectoryPathField.setText(serviceDirectoryPath);
-      useColorForPath(LocationSettingType.EXPLICIT_CORRECT, myServiceDirectoryPathField);
-    }
-  }
-
-  @SuppressWarnings("ConstantConditions")
-  @Override
-  public void disposeUIResources() {
-    super.disposeUIResources();
-    myGradleHomeLabel = null;
-    myGradleHomePathField = null;
-    myServiceDirectoryLabel = null;
-    myServiceDirectoryPathField = null;
-    myUseWrapperButton = null;
-    myUseLocalDistributionButton = null;
-  }
-
-  @Nullable
-  @Override
-  public ValidationError validate() {
-    final LocationSettingType settingType = getCurrentGradleHomeSettingType();
-    if (isPreferLocalInstallationToWrapper()) {
-      if (settingType == LocationSettingType.EXPLICIT_INCORRECT) {
-        return new ValidationError(GradleBundle.message("gradle.home.setting.type.explicit.incorrect"), myGradleHomePathField);
-      }
-      else if (settingType == LocationSettingType.UNKNOWN) {
-        return new ValidationError(GradleBundle.message("gradle.home.setting.type.unknown"), myGradleHomePathField);
-      }
-    }
-    return null;
-  }
-
-  @SuppressWarnings("UseOfArchaicSystemPropertyAccessors")
-  @NotNull
-  public LocationSettingType getCurrentGradleHomeSettingType() {
-    String path = myGradleHomePathField.getText();
-    if (GradleEnvironment.DEBUG_GRADLE_HOME_PROCESSING) {
-      LOG.info(String.format("Checking 'gradle home' status. Manually entered value is '%s'", path));
-    }
-    if (path == null || StringUtil.isEmpty(path.trim())) {
-      return LocationSettingType.UNKNOWN;
-    }
-    if (isModified()) {
-      return myHelper.isGradleSdkHome(new File(path)) ? LocationSettingType.EXPLICIT_CORRECT
-                                                      : LocationSettingType.EXPLICIT_INCORRECT;
-    }
-    return myGradleHomeSettingType;
-  }
-  
-  void showBalloonIfNecessary() {
-    if (!myShowBalloonIfNecessary || !myGradleHomePathField.isEnabled()) {
-      return;
-    }
-    myShowBalloonIfNecessary = false;
-    MessageType messageType = null;
-    switch (myGradleHomeSettingType) {
-      case DEDUCED:
-        messageType = MessageType.INFO;
-        break;
-      case EXPLICIT_INCORRECT:
-      case UNKNOWN:
-        messageType = MessageType.ERROR;
-        break;
-      default:
-    }
-    if (messageType != null) {
-      myHelper.showBalloon(messageType, myGradleHomeSettingType, BALLOON_DELAY_MILLIS);
-    }
-  }
-
-  /**
-   * Updates GUI of the gradle configurable in order to show deduced path to gradle (if possible).
-   */
-  private void deduceGradleHomeIfPossible() {
-    File gradleHome = myHelper.getGradleHome(getProject());
-    if (gradleHome == null) {
-      myHelper.showBalloon(MessageType.WARNING, LocationSettingType.UNKNOWN, BALLOON_DELAY_MILLIS);
-      return;
-    }
-    myGradleHomeSettingType = LocationSettingType.DEDUCED;
-    myHelper.showBalloon(MessageType.INFO, LocationSettingType.DEDUCED, BALLOON_DELAY_MILLIS);
-    myGradleHomePathField.setText(gradleHome.getPath());
-    useColorForPath(LocationSettingType.DEDUCED, myGradleHomePathField);
-    myGradleHomePathField.getTextField().setForeground(UIManager.getColor("TextField.inactiveForeground"));
-    myGradleHomeModifiedByUser = false;
-  }
-
-  private void deduceServiceDirectoryIfPossible() {
-    String path = System.getenv().get(GradleUtil.SYSTEM_DIRECTORY_PATH_KEY);
-    if (StringUtil.isEmpty(path)) {
-      path = new File(System.getProperty("user.home"), ".gradle").getAbsolutePath();
-    }
-    myServiceDirectoryPathField.setText(path);
-    useColorForPath(LocationSettingType.DEDUCED, myServiceDirectoryPathField);
-    myServiceDirectoryModifiedByUser = false;
-  }
-  
-  private class DelayedBalloonInfo implements Runnable {
-    private final MessageType myMessageType;
-    private final String      myText;
-    private final long        myTriggerTime;
-
-    DelayedBalloonInfo(@NotNull MessageType messageType, @NotNull LocationSettingType settingType, long delayMillis) {
-      myMessageType = messageType;
-      myText = settingType.getDescription(GradleConstants.SYSTEM_ID);
-      myTriggerTime = System.currentTimeMillis() + delayMillis;
-    }
-
-    @Override
-    public void run() {
-      long diff = myTriggerTime - System.currentTimeMillis();
-      if (diff > 0) {
-        myAlarm.cancelAllRequests();
-        myAlarm.addRequest(this, diff);
-        return;
-      }
-      if (!myGradleHomePathField.isShowing()) {
-        // Don't schedule the balloon if the configurable is hidden.
-        return;
-      }
-      ExternalSystemUiUtil.showBalloon(myGradleHomePathField, myMessageType, myText);
-    }
-  }
-
-  /**
-   * Encapsulates functionality which default implementation is backed by static API usage (IJ infrastructure limitation).
-   * <p/>
-   * The main idea is to allow to provide a mock implementation for {@link AbstractExternalProjectConfigurable} logic testing.
-   */
-  interface Helper {
-    boolean isGradleSdkHome(@NotNull File file);
-
-    @Nullable
-    File getGradleHome(@Nullable Project project);
-
-    @NotNull
-    Project getDefaultProject();
-
-    @NotNull
-    GradleSettings getSettings(@NotNull Project project);
-
-    void applySettings(@Nullable String linkedProjectPath,
-                       @Nullable String gradleHomePath,
-                       boolean preferLocalInstallationToWrapper,
-                       boolean useAutoImport,
-                       @Nullable String serviceDirectoryPath,
-                       @NotNull Project project);
-
-    void applyPreferLocalInstallationToWrapper(boolean preferLocalToWrapper, @NotNull Project project);
-
-    boolean isGradleWrapperDefined(@Nullable String linkedProjectPath);
-
-    void showBalloon(@NotNull MessageType messageType, @NotNull LocationSettingType settingType, long delayMillis);
-  }
-
-  private class DefaultHelper implements Helper {
-
-    @NotNull private final GradleInstallationManager myInstallationManager;
-
-    DefaultHelper(@NotNull GradleInstallationManager installationManager) {
-      myInstallationManager = installationManager;
-    }
-
-    @Override
-    public boolean isGradleSdkHome(@NotNull File file) {
-      return myInstallationManager.isGradleSdkHome(file);
-    }
-
-    @Nullable
-    @Override
-    public File getGradleHome(@Nullable Project project) {
-      return myInstallationManager.getGradleHome(project);
-    }
-
-    @NotNull
-    @Override
-    public Project getDefaultProject() {
-      return ProjectManager.getInstance().getDefaultProject();
-    }
-
-    @NotNull
-    @Override
-    public GradleSettings getSettings(@NotNull Project project) {
-      return GradleSettings.getInstance(project);
-    }
-
-    @Override
-    public void applySettings(@Nullable String linkedProjectPath,
-                              @Nullable String gradleHomePath,
-                              boolean preferLocalInstallationToWrapper,
-                              boolean useAutoImport,
-                              @Nullable String serviceDirectoryPath,
-                              @NotNull Project project)
-    {
-      GradleSettings.getInstance(project).applySettings(
-        linkedProjectPath, gradleHomePath, preferLocalInstallationToWrapper, useAutoImport, serviceDirectoryPath
-      ); 
-    }
-
-    @Override
-    public void applyPreferLocalInstallationToWrapper(boolean preferLocalToWrapper, @NotNull Project project) {
-      GradleSettings.getInstance(project).setPreferLocalInstallationToWrapper(preferLocalToWrapper);
-    }
-
-    @Override
-    public boolean isGradleWrapperDefined(@Nullable String linkedProjectPath) {
-      return GradleUtil.isGradleWrapperDefined(linkedProjectPath);
-    }
-
-    @Override
-    public void showBalloon(@NotNull MessageType messageType, @NotNull LocationSettingType settingType, long delayMillis) {
-      new DelayedBalloonInfo(messageType, settingType, delayMillis).run();
-    }
-  }
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectImportBuilder.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectImportBuilder.java
index c5faad8..375e046 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectImportBuilder.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectImportBuilder.java
@@ -43,10 +43,10 @@
  * @author Denis Zhdanov
  * @since 4/15/13 2:29 PM
  */
-public class GradleProjectImportBuilder extends AbstractExternalProjectImportBuilder<GradleConfigurable> {
+public class GradleProjectImportBuilder extends AbstractExternalProjectImportBuilder<ImportFromGradleControl> {
 
   public GradleProjectImportBuilder(@NotNull ExternalSystemSettingsManager settingsManager, @NotNull ProjectDataManager dataManager) {
-    super(settingsManager, dataManager, new GradleConfigurable(null), GradleConstants.SYSTEM_ID);
+    super(settingsManager, dataManager, new ImportFromGradleControl(), GradleConstants.SYSTEM_ID);
   }
 
   @NotNull
@@ -66,11 +66,14 @@
     if (!pathToUse.endsWith(GradleConstants.DEFAULT_SCRIPT_NAME)) {
       pathToUse = new File(pathToUse, GradleConstants.DEFAULT_SCRIPT_NAME).getAbsolutePath();
     }
-    getConfigurable().setLinkedExternalProjectPath(pathToUse);
+    getControl().setLinkedProjectPath(pathToUse);
   }
 
   @Override
   protected void beforeCommit(@NotNull DataNode<ProjectData> dataNode, @NotNull Project project) {
+    if (!ExternalSystemApiUtil.isNewProjectConstruction()) {
+      return;
+    }
     DataNode<JavaProjectData> javaProjectNode = ExternalSystemApiUtil.find(dataNode, JavaProjectData.KEY);
     if (javaProjectNode == null) {
       return;
@@ -123,12 +126,14 @@
   @Override
   protected void onProjectInit(@NotNull Project project) {
     GradleSettings settings = (GradleSettings)getSettingsManager().getSettings(project, GradleConstants.SYSTEM_ID);
-    settings.setPreferLocalInstallationToWrapper(getConfigurable().isPreferLocalInstallationToWrapper());
-    settings.setGradleHome(getConfigurable().getGradleHomePath());
+    // TODO den implement
+//    settings.setPreferLocalInstallationToWrapper(getConfigurable().isPreferLocalInstallationToWrapper());
+//    settings.setGradleHome(getConfigurable().getGradleHomePath());
 
     // Reset linked gradle home for default project (legacy bug).
     Project defaultProject = ProjectManager.getInstance().getDefaultProject();
-    getSettingsManager().getSettings(defaultProject, GradleConstants.SYSTEM_ID).setLinkedExternalProjectPath(null);
+    // TODO den implement
+//    getSettingsManager().getSettings(defaultProject, GradleConstants.SYSTEM_ID).setLinkedExternalProjectPath(null);
   }
 
   @Override
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectOpenProcessor.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectOpenProcessor.java
new file mode 100644
index 0000000..dc4fd6e
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectOpenProcessor.java
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.gradle.service.settings;
+
+import com.intellij.ide.util.newProjectWizard.AddModuleWizard;
+import com.intellij.ide.util.projectWizard.WizardContext;
+import com.intellij.ide.wizard.Step;
+import com.intellij.openapi.externalSystem.service.project.wizard.SelectExternalProjectStepBase;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.projectImport.ProjectOpenProcessorBase;
+import com.intellij.util.Function;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.gradle.util.GradleConstants;
+
+/**
+ * @author Denis Zhdanov
+ * @since 4/30/13 11:22 PM
+ */
+public class GradleProjectOpenProcessor extends ProjectOpenProcessorBase<GradleProjectImportBuilder> {
+
+  @NotNull public static final String[] BUILD_FILE_NAMES = {GradleConstants.DEFAULT_SCRIPT_NAME};
+
+  public GradleProjectOpenProcessor(@NotNull GradleProjectImportBuilder builder) {
+    super(builder);
+  }
+
+  @Nullable
+  @Override
+  public String[] getSupportedExtensions() {
+    return BUILD_FILE_NAMES;
+  }
+  
+  @Override
+  protected boolean doQuickImport(VirtualFile file, WizardContext wizardContext) {
+    AddModuleWizard dialog = new AddModuleWizard(null, file.getPath(), new GradleProjectImportProvider(getBuilder()));
+    getBuilder().prepare(wizardContext);
+    getBuilder().getControl().setLinkedProjectPath(file.getPath());
+    dialog.getWizardContext().setProjectBuilder(getBuilder());
+    dialog.navigateToStep(new Function<Step, Boolean>() {
+      @Override
+      public Boolean fun(Step step) {
+        return step instanceof SelectExternalProjectStepBase;
+      }
+    });
+    dialog.doNextAction();
+    if (StringUtil.isEmpty(wizardContext.getProjectName())) {
+      final String projectName = dialog.getWizardContext().getProjectName();
+      if (!StringUtil.isEmpty(projectName)) {
+        wizardContext.setProjectName(projectName);
+      }
+    }
+
+    dialog.show();
+    return dialog.isOK();
+  }
+
+  @Override
+  public boolean lookForProjectsInDirectory() {
+    return false;
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java
new file mode 100644
index 0000000..141722c
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java
@@ -0,0 +1,338 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.gradle.service.settings;
+
+import com.intellij.openapi.components.ServiceManager;
+import com.intellij.openapi.externalSystem.model.settings.LocationSettingType;
+import com.intellij.openapi.externalSystem.service.settings.AbstractExternalProjectSettingsControl;
+import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil;
+import com.intellij.openapi.externalSystem.util.PaintAwarePanel;
+import com.intellij.openapi.fileChooser.FileChooserDescriptor;
+import com.intellij.openapi.ui.MessageType;
+import com.intellij.openapi.ui.TextComponentAccessor;
+import com.intellij.openapi.ui.TextFieldWithBrowseButton;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.ui.components.JBLabel;
+import com.intellij.ui.components.JBRadioButton;
+import com.intellij.util.Alarm;
+import com.intellij.util.Consumer;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.gradle.service.GradleInstallationManager;
+import org.jetbrains.plugins.gradle.settings.GradleProjectSettings;
+import org.jetbrains.plugins.gradle.util.GradleBundle;
+import org.jetbrains.plugins.gradle.util.GradleConstants;
+import org.jetbrains.plugins.gradle.util.GradleUtil;
+
+import javax.swing.*;
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+import java.io.File;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @author Denis Zhdanov
+ * @since 4/24/13 1:45 PM
+ */
+public class GradleProjectSettingsControl extends AbstractExternalProjectSettingsControl<GradleProjectSettings> {
+
+  private static final long BALLOON_DELAY_MILLIS = TimeUnit.SECONDS.toMillis(1);
+
+  @NotNull private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
+
+  @NotNull private LocationSettingType myGradleHomeSettingType = LocationSettingType.UNKNOWN;
+  
+  @NotNull private final GradleInstallationManager myInstallationManager;
+  
+  private JLabel                    myGradleHomeLabel;
+  private TextFieldWithBrowseButton myGradleHomePathField;
+  private JBRadioButton             myUseWrapperButton;
+  private JBRadioButton             myUseLocalDistributionButton;
+
+  private boolean myShowBalloonIfNecessary;
+  private boolean myGradleHomeModifiedByUser;
+
+  public GradleProjectSettingsControl(@NotNull GradleProjectSettings initialSettings) {
+    super(initialSettings);
+    myInstallationManager = ServiceManager.getService(GradleInstallationManager.class);
+  }
+
+  @Override
+  protected void fillExtraControls(@NotNull PaintAwarePanel content, int indentLevel) {
+    content.setPaintCallback(new Consumer<Graphics>() {
+      @Override
+      public void consume(Graphics graphics) {
+        showBalloonIfNecessary(); 
+      }
+    });
+
+    content.addPropertyChangeListener(new PropertyChangeListener() {
+      @Override
+      public void propertyChange(PropertyChangeEvent evt) {
+        if (!"ancestor".equals(evt.getPropertyName())) {
+          return;
+        }
+
+        // Configure the balloon to show on initial configurable drawing.
+        myShowBalloonIfNecessary = evt.getNewValue() != null && evt.getOldValue() == null;
+
+        if (evt.getNewValue() == null && evt.getOldValue() != null) {
+          // Cancel delayed balloons when the configurable is hidden.
+          myAlarm.cancelAllRequests();
+        }
+      }
+    });
+    
+    myGradleHomeLabel = new JBLabel(GradleBundle.message("gradle.settings.text.home.path"));
+    initGradleHome();
+
+    initWrapperControls();
+    content.add(myUseWrapperButton, ExternalSystemUiUtil.getFillLineConstraints(indentLevel));
+    content.add(myUseLocalDistributionButton, ExternalSystemUiUtil.getFillLineConstraints(indentLevel));
+
+    content.add(myGradleHomeLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel));
+    content.add(myGradleHomePathField, ExternalSystemUiUtil.getFillLineConstraints(0));
+  }
+
+  @Override
+  protected void showExtraUi(boolean show) {
+    myGradleHomeLabel.setVisible(show);
+    myGradleHomePathField.setVisible(show);
+    myUseWrapperButton.setVisible(show);
+    myUseLocalDistributionButton.setVisible(show);
+    myGradleHomeLabel.setVisible(show);
+    myGradleHomePathField.setVisible(show);
+  }
+
+  private void initWrapperControls() {
+    ActionListener listener = new ActionListener() {
+            @Override
+      public void actionPerformed(ActionEvent e) {
+        boolean enabled = e.getSource() == myUseLocalDistributionButton;
+        myGradleHomePathField.setEnabled(enabled);
+        if (enabled) {
+          showBalloonIfNecessary();
+        }
+        else {
+          myAlarm.cancelAllRequests();
+        }
+      }
+    };
+    myUseWrapperButton = new JBRadioButton(GradleBundle.message("gradle.settings.text.use.wrapper"), true);
+    myUseWrapperButton.addActionListener(listener);
+    myUseLocalDistributionButton = new JBRadioButton(GradleBundle.message("gradle.settings..text.use.local.distribution"));
+    myUseLocalDistributionButton.addActionListener(listener);
+    ButtonGroup buttonGroup = new ButtonGroup();
+    buttonGroup.add(myUseWrapperButton);
+    buttonGroup.add(myUseLocalDistributionButton);
+  }
+
+  private void initGradleHome() {
+    myGradleHomePathField = new TextFieldWithBrowseButton();
+
+    FileChooserDescriptor fileChooserDescriptor = GradleUtil.getGradleHomeFileChooserDescriptor();
+
+    myGradleHomePathField.addBrowseFolderListener(
+      "",
+      GradleBundle.message("gradle.settings.text.home.path"),
+      null,
+      fileChooserDescriptor,
+      TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
+      false
+    );
+    myGradleHomePathField.getTextField().getDocument().addDocumentListener(new DocumentListener() {
+      @Override
+      public void insertUpdate(DocumentEvent e) {
+        myGradleHomePathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor());
+        myGradleHomeModifiedByUser = true;
+      }
+
+      @Override
+      public void removeUpdate(DocumentEvent e) {
+        myGradleHomePathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor());
+        myGradleHomeModifiedByUser = true;
+      }
+
+      @Override
+      public void changedUpdate(DocumentEvent e) {
+      }
+    });
+  }
+
+  @Override
+  @Nullable
+  protected String applyExtraSettings(@NotNull GradleProjectSettings settings) {
+    String gradleHomePath = myGradleHomePathField.getText();
+    if (myGradleHomeModifiedByUser) {
+      if (StringUtil.isEmpty(gradleHomePath)) {
+        settings.setGradleHome(null);
+      }
+      else {
+        settings.setGradleHome(gradleHomePath);
+      }
+    }
+    else {
+      settings.setGradleHome(getInitialSettings().getGradleHome());
+    }
+
+    if (myUseLocalDistributionButton.isSelected()) {
+      if (StringUtil.isEmpty(gradleHomePath)) {
+        myGradleHomeSettingType = LocationSettingType.UNKNOWN;
+      }
+      else if (!myInstallationManager.isGradleSdkHome(new File(gradleHomePath))) {
+        myGradleHomeSettingType = LocationSettingType.EXPLICIT_INCORRECT;
+        new DelayedBalloonInfo(MessageType.ERROR, myGradleHomeSettingType, 0).run();
+        return GradleBundle.message("gradle.home.setting.type.explicit.incorrect");
+      }
+    }
+    settings.setPreferLocalInstallationToWrapper(myUseLocalDistributionButton.isSelected());
+    return null;
+  }
+  
+  @Override
+  protected boolean isExtraSettingModified() {
+    if (myUseLocalDistributionButton.isSelected() != getInitialSettings().isPreferLocalInstallationToWrapper()) {
+      return true;
+    }
+
+    String gradleHome = myGradleHomePathField.getText();
+    if (StringUtil.isEmpty(gradleHome)) {
+      return !StringUtil.isEmpty(getInitialSettings().getGradleHome());
+    }
+    else {
+      return !gradleHome.equals(getInitialSettings().getGradleHome());
+    }
+  }
+
+  @Override
+  protected void resetExtraSettings() {
+    myGradleHomeModifiedByUser = false;
+    String gradleHome = getInitialSettings().getGradleHome();
+    myGradleHomePathField.setText(gradleHome == null ? "" : gradleHome);
+    myGradleHomePathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor());
+    
+    updateWrapperControls(getInitialSettings().getExternalProjectPath());
+
+    if (StringUtil.isEmpty(gradleHome)) {
+      myGradleHomeSettingType = LocationSettingType.UNKNOWN;
+      deduceGradleHomeIfPossible();
+    }
+    else {
+      myGradleHomeSettingType = myInstallationManager.isGradleSdkHome(new File(gradleHome)) ?
+                                LocationSettingType.EXPLICIT_CORRECT :
+                                LocationSettingType.EXPLICIT_INCORRECT;
+      myAlarm.cancelAllRequests();
+      if (myGradleHomeSettingType == LocationSettingType.EXPLICIT_INCORRECT && getInitialSettings().isPreferLocalInstallationToWrapper()) {
+        new DelayedBalloonInfo(MessageType.ERROR, myGradleHomeSettingType, 0).run();
+      }
+    }
+  }
+
+  public void updateWrapperControls(@Nullable String linkedProjectPath) {
+    if (linkedProjectPath != null && GradleUtil.isGradleWrapperDefined(linkedProjectPath)) {
+      myUseWrapperButton.setText(GradleBundle.message("gradle.settings.text.use.wrapper"));
+      myUseWrapperButton.setEnabled(true);
+      if (getInitialSettings().isPreferLocalInstallationToWrapper()) {
+        myUseLocalDistributionButton.setSelected(true);
+      }
+      else {
+        myUseWrapperButton.setSelected(true);
+      }
+    }
+    else {
+      myUseWrapperButton.setText(GradleBundle.message("gradle.settings.text.use.wrapper.disabled"));
+      myUseWrapperButton.setEnabled(false);
+      myUseLocalDistributionButton.setSelected(true);
+    }
+  }
+
+  /**
+   * Updates GUI of the gradle configurable in order to show deduced path to gradle (if possible).
+   */
+  private void deduceGradleHomeIfPossible() {
+    File gradleHome = myInstallationManager.getAutodetectedGradleHome();
+    if (gradleHome == null) {
+      new DelayedBalloonInfo(MessageType.WARNING, LocationSettingType.UNKNOWN, BALLOON_DELAY_MILLIS).run();
+      return;
+    }
+    myGradleHomeSettingType = LocationSettingType.DEDUCED;
+    new DelayedBalloonInfo(MessageType.INFO, LocationSettingType.DEDUCED, BALLOON_DELAY_MILLIS).run();
+    myGradleHomePathField.setText(gradleHome.getPath());
+    myGradleHomePathField.getTextField().setForeground(LocationSettingType.DEDUCED.getColor());
+    myGradleHomeModifiedByUser = false;
+  }
+  
+  @Override
+  protected void disposeExtraUIControls() {
+    myGradleHomeLabel = null;
+    myGradleHomePathField = null;
+    myUseWrapperButton = null;
+    myUseLocalDistributionButton = null;
+  }
+
+  void showBalloonIfNecessary() {
+    if (!myShowBalloonIfNecessary || !myGradleHomePathField.isEnabled()) {
+      return;
+    }
+    myShowBalloonIfNecessary = false;
+    MessageType messageType = null;
+    switch (myGradleHomeSettingType) {
+      case DEDUCED:
+        messageType = MessageType.INFO;
+        break;
+      case EXPLICIT_INCORRECT:
+      case UNKNOWN:
+        messageType = MessageType.ERROR;
+        break;
+      default:
+    }
+    if (messageType != null) {
+      new DelayedBalloonInfo(messageType, myGradleHomeSettingType, BALLOON_DELAY_MILLIS).run();
+    }
+  }
+
+  private class DelayedBalloonInfo implements Runnable {
+    private final MessageType myMessageType;
+    private final String      myText;
+    private final long        myTriggerTime;
+
+    DelayedBalloonInfo(@NotNull MessageType messageType, @NotNull LocationSettingType settingType, long delayMillis) {
+      myMessageType = messageType;
+      myText = settingType.getDescription(GradleConstants.SYSTEM_ID);
+      myTriggerTime = System.currentTimeMillis() + delayMillis;
+    }
+
+    @Override
+    public void run() {
+      long diff = myTriggerTime - System.currentTimeMillis();
+      if (diff > 0) {
+        myAlarm.cancelAllRequests();
+        myAlarm.addRequest(this, diff);
+        return;
+      }
+      if (!myGradleHomePathField.isShowing()) {
+        // Don't schedule the balloon if the configurable is hidden.
+        return;
+      }
+      ExternalSystemUiUtil.showBalloon(myGradleHomePathField, myMessageType, myText);
+    }
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java
new file mode 100644
index 0000000..27545bc
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleSystemSettingsControl.java
@@ -0,0 +1,145 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.gradle.service.settings;
+
+import com.intellij.openapi.externalSystem.model.settings.LocationSettingType;
+import com.intellij.openapi.externalSystem.service.settings.ExternalSettingsControl;
+import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemUiUtil;
+import com.intellij.openapi.externalSystem.util.PaintAwarePanel;
+import com.intellij.openapi.fileChooser.FileChooserDescriptor;
+import com.intellij.openapi.ui.TextComponentAccessor;
+import com.intellij.openapi.ui.TextFieldWithBrowseButton;
+import com.intellij.openapi.util.Comparing;
+import com.intellij.openapi.util.text.StringUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.gradle.settings.GradleSettings;
+import org.jetbrains.plugins.gradle.util.GradleBundle;
+import org.jetbrains.plugins.gradle.util.GradleConstants;
+
+import javax.swing.*;
+import javax.swing.event.DocumentEvent;
+import javax.swing.event.DocumentListener;
+import java.io.File;
+
+/**
+ * Manages gradle settings not specific to particular project (e.g. 'use wrapper' is project-level setting but 'gradle user home' is
+ * a global one).
+ * 
+ * @author Denis Zhdanov
+ * @since 4/28/13 11:06 AM
+ */
+public class GradleSystemSettingsControl implements ExternalSettingsControl<GradleSettings> {
+  
+  @NotNull private final GradleSettings myInitialSettings;
+  
+  private JLabel                    myServiceDirectoryLabel;
+  private TextFieldWithBrowseButton myServiceDirectoryPathField;
+  private boolean                   myServiceDirectoryPathModifiedByUser;
+
+  public GradleSystemSettingsControl(@NotNull GradleSettings settings) {
+    myInitialSettings = settings;
+  }
+
+  @Override
+  public void fillUi(@NotNull PaintAwarePanel canvas, int indentLevel) {
+    myServiceDirectoryLabel = new JLabel(GradleBundle.message("gradle.settings.text.service.dir.path"));
+    preparePathControl();
+    canvas.add(myServiceDirectoryLabel, ExternalSystemUiUtil.getLabelConstraints(indentLevel));
+    canvas.add(myServiceDirectoryPathField, ExternalSystemUiUtil.getFillLineConstraints(0));
+  }
+
+  @Override
+  public void showUi(boolean show) {
+    myServiceDirectoryLabel.setVisible(show);
+    myServiceDirectoryPathField.setVisible(show);
+  }
+
+  private void preparePathControl() {
+    myServiceDirectoryPathField = new TextFieldWithBrowseButton();
+    myServiceDirectoryPathField.addBrowseFolderListener(
+      "",
+      GradleBundle.message("gradle.settings.title.service.dir.path"),
+      null,
+      new FileChooserDescriptor(false, true, false, false, false, false),
+      TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
+      false
+    );
+    myServiceDirectoryPathField.getTextField().getDocument().addDocumentListener(new DocumentListener() {
+      @Override
+      public void insertUpdate(DocumentEvent e) {
+        myServiceDirectoryPathModifiedByUser = true;
+        myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor());
+      }
+
+      @Override
+      public void removeUpdate(DocumentEvent e) {
+        myServiceDirectoryPathModifiedByUser = true;
+        myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor());
+      }
+
+      @Override
+      public void changedUpdate(DocumentEvent e) {
+      }
+    });
+  }
+
+  @Override
+  public void reset() {
+    myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.EXPLICIT_CORRECT.getColor());
+    myServiceDirectoryPathField.setText("");
+    String path = myInitialSettings.getServiceDirectoryPath();
+    if (StringUtil.isEmpty(path)) {
+      deduceServiceDirectoryIfPossible();
+    }
+    else {
+      myServiceDirectoryPathField.setText(path);
+    }
+  }
+
+  private void deduceServiceDirectoryIfPossible() {
+    String path = System.getenv().get(GradleConstants.SYSTEM_DIRECTORY_PATH_KEY);
+    if (StringUtil.isEmpty(path)) {
+      path = new File(System.getProperty("user.home"), ".gradle").getAbsolutePath();
+    }
+    myServiceDirectoryPathField.setText(path);
+    myServiceDirectoryPathField.getTextField().setForeground(LocationSettingType.DEDUCED.getColor());
+    myServiceDirectoryPathModifiedByUser = false;
+  }
+
+  @Override
+  public boolean isModified() {
+    return myServiceDirectoryPathModifiedByUser
+           && !Comparing.equal(ExternalSystemApiUtil.normalizePath(myServiceDirectoryPathField.getText()),
+                               ExternalSystemApiUtil.normalizePath(myInitialSettings.getServiceDirectoryPath()));
+  }
+
+  @Override
+  @Nullable
+  public String apply(@NotNull GradleSettings settings) {
+    if (myServiceDirectoryPathModifiedByUser) {
+      settings.setServiceDirectoryPath(ExternalSystemApiUtil.normalizePath(myServiceDirectoryPathField.getText()));
+    }
+    return null;
+  }
+
+  @Override
+  public void disposeUIResources() {
+    myServiceDirectoryLabel = null; 
+    myServiceDirectoryPathField = null; 
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java
new file mode 100644
index 0000000..68674b0
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/ImportFromGradleControl.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.gradle.service.settings;
+
+import com.intellij.openapi.externalSystem.service.settings.AbstractImportFromExternalSystemControl;
+import com.intellij.openapi.externalSystem.service.settings.ExternalSettingsControl;
+import com.intellij.openapi.fileChooser.FileChooserDescriptor;
+import com.intellij.openapi.project.ProjectManager;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.gradle.settings.GradleProjectSettings;
+import org.jetbrains.plugins.gradle.settings.GradleSettings;
+import org.jetbrains.plugins.gradle.settings.GradleSettingsListener;
+import org.jetbrains.plugins.gradle.util.GradleConstants;
+import org.jetbrains.plugins.gradle.util.GradleUtil;
+
+/**
+ * @author Denis Zhdanov
+ * @since 4/30/13 4:58 PM
+ */
+public class ImportFromGradleControl
+  extends AbstractImportFromExternalSystemControl<GradleProjectSettings, GradleSettingsListener, GradleSettings>
+{
+  public ImportFromGradleControl() {
+    super(GradleConstants.SYSTEM_ID, new GradleSettings(ProjectManager.getInstance().getDefaultProject()), new GradleProjectSettings());
+  }
+  
+  @NotNull
+  @Override
+  protected ExternalSettingsControl<GradleProjectSettings> createProjectSettingsControl(@NotNull GradleProjectSettings settings) {
+    return new GradleProjectSettingsControl(settings);
+  }
+
+  @Nullable
+  @Override
+  protected ExternalSettingsControl<GradleSettings> createSystemSettingsControl(@NotNull GradleSettings settings) {
+    return new GradleSystemSettingsControl(settings);
+  }
+
+  @NotNull
+  @Override
+  protected FileChooserDescriptor getLinkedProjectChooserDescriptor() {
+    return GradleUtil.getGradleProjectFileChooserDescriptor();
+  }
+
+  @Override
+  protected void onLinkedProjectPathChange(@NotNull String path) {
+    ((GradleProjectSettingsControl)getProjectSettingsControl()).updateWrapperControls(path);
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleProjectSettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleProjectSettings.java
new file mode 100644
index 0000000..369f2f9
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleProjectSettings.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.gradle.settings;
+
+import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * @author Denis Zhdanov
+ * @since 4/24/13 11:57 AM
+ */
+public class GradleProjectSettings extends ExternalProjectSettings {
+
+  @Nullable private String  myGradleHome;
+  private boolean myPreferLocalInstallationToWrapper;
+
+  @Nullable
+  public String getGradleHome() {
+    return myGradleHome;
+  }
+
+  public void setGradleHome(@Nullable String gradleHome) {
+    myGradleHome = gradleHome;
+  }
+
+  public boolean isPreferLocalInstallationToWrapper() {
+    return myPreferLocalInstallationToWrapper;
+  }
+
+  public void setPreferLocalInstallationToWrapper(boolean preferLocalInstallationToWrapper) {
+    myPreferLocalInstallationToWrapper = preferLocalInstallationToWrapper;
+  }
+
+  @NotNull
+  @Override
+  public ExternalProjectSettings clone() {
+    GradleProjectSettings result = new GradleProjectSettings();
+    copyTo(result);
+    result.myGradleHome = myGradleHome;
+    result.myPreferLocalInstallationToWrapper = myPreferLocalInstallationToWrapper;
+    return result;
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleSettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleSettings.java
index e7e6c55..aff64ca 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleSettings.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleSettings.java
@@ -19,9 +19,13 @@
 import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Comparing;
+import com.intellij.util.containers.ContainerUtilRt;
+import com.intellij.util.xmlb.annotations.AbstractCollection;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.util.Set;
+
 /**
  * Holds shared project-level gradle-related settings (should be kept at the '*.ipr' or under '.idea').
  * 
@@ -34,14 +38,12 @@
       @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/gradle.xml", scheme = StorageScheme.DIRECTORY_BASED)
     }
 )
-public class GradleSettings extends AbstractExternalSystemSettings<GradleSettingsListener, GradleSettings>
+public class GradleSettings extends AbstractExternalSystemSettings<GradleProjectSettings, GradleSettingsListener>
   implements PersistentStateComponent<GradleSettings.MyState>
 {
 
-  private String  myGradleHome;
   private String  myServiceDirectoryPath;
-  private boolean myPreferLocalInstallationToWrapper;
-  
+
   public GradleSettings(@NotNull Project project) {
     super(GradleSettingsListener.TOPIC, project);
   }
@@ -57,43 +59,14 @@
   public GradleSettings.MyState getState() {
     MyState state = new MyState();
     fillState(state);
-    state.gradleHome = myGradleHome;
     state.serviceDirectoryPath = myServiceDirectoryPath;
-    state.preferLocalInstallationToWrapper = myPreferLocalInstallationToWrapper;
     return state;
   }
 
   @Override
   public void loadState(MyState state) {
     super.loadState(state);
-    myGradleHome = state.gradleHome;
     myServiceDirectoryPath = state.serviceDirectoryPath;
-    myPreferLocalInstallationToWrapper = state.preferLocalInstallationToWrapper;
-  }
-  
-  @Nullable
-  public String getGradleHome() {
-    return myGradleHome;
-  }
-
-  @SuppressWarnings("UnusedDeclaration")
-  public void setGradleHome(@Nullable String gradleHome) {
-    if (!Comparing.equal(myGradleHome, gradleHome)) {
-      final String oldHome = myGradleHome;
-      myGradleHome = gradleHome;
-      getPublisher().onGradleHomeChange(oldHome, myGradleHome);
-    }
-  }
-
-  public boolean isPreferLocalInstallationToWrapper() {
-    return myPreferLocalInstallationToWrapper;
-  }
-
-  public void setPreferLocalInstallationToWrapper(boolean preferLocalInstallationToWrapper) {
-    if (myPreferLocalInstallationToWrapper != preferLocalInstallationToWrapper) {
-      myPreferLocalInstallationToWrapper = preferLocalInstallationToWrapper;
-      getPublisher().onPreferLocalGradleDistributionToWrapperChange(preferLocalInstallationToWrapper);
-    }
   }
 
   /**
@@ -114,35 +87,31 @@
     } 
   }
 
-  public void applySettings(@Nullable String linkedProjectPath,
-                            @Nullable String gradleHomePath,
-                            boolean preferLocalInstallationToWrapper,
-                            boolean useAutoImport,
-                            @Nullable String serviceDirectoryPath)
-  {
-    
-    GradleSettingsListener publisher = getPublisher();
-    publisher.onBulkChangeStart();
-    try {
-      setLinkedExternalProjectPath(linkedProjectPath);
-      setGradleHome(gradleHomePath);
-      setPreferLocalInstallationToWrapper(preferLocalInstallationToWrapper);
-      setUseAutoImport(useAutoImport);
-      setServiceDirectoryPath(serviceDirectoryPath);
+  @Override
+  protected void checkSettings(@NotNull GradleProjectSettings old, @NotNull GradleProjectSettings current) {
+    if (!Comparing.equal(old.getGradleHome(), current.getGradleHome())) {
+      getPublisher().onGradleHomeChange(old.getGradleHome(), current.getGradleHome(), current.getExternalProjectPath());
     }
-    finally {
-      publisher.onBulkChangeEnd();
+    if (old.isPreferLocalInstallationToWrapper() != current.isPreferLocalInstallationToWrapper()) {
+      getPublisher().onPreferLocalGradleDistributionToWrapperChange(current.isPreferLocalInstallationToWrapper(),
+                                                                    current.getExternalProjectPath());
     }
   }
 
-  @Override
-  public String toString() {
-    return "home: " + myGradleHome + ", path: " + getLinkedExternalProjectPath();
-  }
-  
-  public static class MyState extends State {
-    public String gradleHome;
+  public static class MyState implements State<GradleProjectSettings> {
+
+    private Set<GradleProjectSettings> myProjectSettings = ContainerUtilRt.newTreeSet();
     public String serviceDirectoryPath;
-    public boolean preferLocalInstallationToWrapper;
+
+    @AbstractCollection(surroundWithTag = false, elementTypes = {GradleProjectSettings.class})
+    public Set<GradleProjectSettings> getLinkedExternalProjectsSettings() {
+      return myProjectSettings;
+    }
+
+    public void setLinkedExternalProjectsSettings(Set<GradleProjectSettings> settings) {
+      if (settings != null) {
+        myProjectSettings.addAll(settings);
+      }
+    }
   }
 }
\ No newline at end of file
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleSettingsListener.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleSettingsListener.java
index 0ac8d1e..148d714 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleSettingsListener.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleSettingsListener.java
@@ -2,6 +2,7 @@
 
 import com.intellij.openapi.externalSystem.settings.ExternalSystemSettingsListener;
 import com.intellij.util.messages.Topic;
+import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 /**
@@ -12,7 +13,7 @@
  * @author Denis Zhdanov
  * @since 1/17/12 1:02 PM
  */
-public interface GradleSettingsListener extends ExternalSystemSettingsListener {
+public interface GradleSettingsListener extends ExternalSystemSettingsListener<GradleProjectSettings> {
 
   Topic<GradleSettingsListener> TOPIC = Topic.create("Gradle-specific settings", GradleSettingsListener.class);
 
@@ -21,10 +22,11 @@
    * <p/>
    * <b>Note:</b> this callback is executed <b>after</b> the actual config change.
    *
-   * @param oldPath  old path (if any)
-   * @param newPath  new path (if any)
+   * @param oldPath            old path (if any)
+   * @param newPath            new path (if any)
+   * @param linkedProjectPath  target linked gradle project path
    */
-  void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath);
+  void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath, @NotNull String linkedProjectPath);
 
   /**
    * Is expected to be invoked when 'prefer local gradle distribution to wrapper' setting is changed (generally this
@@ -32,9 +34,10 @@
    * <p/>
    * <b>Note:</b> this callback is executed <b>after</b> the actual config change.
    * 
-   * @param currentValue    current value
+   * @param currentValue       current value
+   * @param linkedProjectPath  target linked gradle project path
    */
-  void onPreferLocalGradleDistributionToWrapperChange(boolean currentValue);
+  void onPreferLocalGradleDistributionToWrapperChange(boolean currentValue, @NotNull String linkedProjectPath);
 
   /**
    * Is expected to be invoked when service directory path is changed.
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleStartupActivity.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleStartupActivity.java
deleted file mode 100644
index 3841703..0000000
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/sync/GradleStartupActivity.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package org.jetbrains.plugins.gradle.sync;
-
-import com.intellij.openapi.externalSystem.model.ProjectSystemId;
-import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
-import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
-import com.intellij.openapi.project.Project;
-import com.intellij.openapi.startup.StartupActivity;
-import com.intellij.openapi.startup.StartupManager;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.plugins.gradle.config.GradlePatcher;
-import org.jetbrains.plugins.gradle.util.GradleConstants;
-import org.jetbrains.plugins.gradle.util.GradleUtil;
-
-/**
- * Performs gradle-specific actions on IJ project loading.
- * <p/>
- * Thread-safe.
- * 
- * @author Denis Zhdanov
- * @since 3/13/12 12:01 PM
- */
-// TODO den generalize and move to 'external-system'
-public class GradleStartupActivity implements StartupActivity {
-  @SuppressWarnings("UseOfArchaicSystemPropertyAccessors")
-  @Override
-  public void runActivity(@NotNull final Project project) {
-    Runnable task = new Runnable() {
-      @Override
-      public void run() {
-        new GradlePatcher().patch(project);
-        
-        if (!Boolean.getBoolean(ExternalSystemConstants.NEWLY_IMPORTED_PROJECT)) {
-          ExternalSystemUtil.refreshProject(project, GradleConstants.SYSTEM_ID);
-        }
-      }
-    };
-    
-    if (project.isInitialized()) {
-      task.run();
-    }
-    else {
-      StartupManager.getInstance(project).registerPostStartupActivity(task);
-    }
-  }
-}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/tasks/GradleTasksPanel.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/tasks/GradleTasksPanel.java
index b7abaa3..7c025f7 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/tasks/GradleTasksPanel.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/tasks/GradleTasksPanel.java
@@ -231,7 +231,9 @@
       return null;
     }
 
-    String gradleProjectPath = GradleSettings.getInstance(getProject()).getLinkedExternalProjectPath();
+    // TODO den implement
+    String gradleProjectPath = null;
+//    String gradleProjectPath = GradleSettings.getInstance(getProject()).getLinkedExternalProjectPath();
     if (StringUtil.isEmpty(gradleProjectPath)) {
       return null;
     }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleConstants.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleConstants.java
index 41affcf..ba5418b 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleConstants.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleConstants.java
@@ -17,6 +17,8 @@
   @NonNls public static final String EXTENSION           = "gradle";
   @NonNls public static final String DEFAULT_SCRIPT_NAME = "build.gradle";
 
+  public static final  String  SYSTEM_DIRECTORY_PATH_KEY    = "GRADLE_USER_HOME";
+
   @NonNls public static final String TOOL_WINDOW_ID = "JetGradle";
 
   @NonNls public static final String TOOL_WINDOW_TOOLBAR_PLACE    = "GRADLE_SYNC_CHANGES_TOOLBAR";
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleUtil.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleUtil.java
index c6f048d..094bb90 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleUtil.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleUtil.java
@@ -1,24 +1,16 @@
 package org.jetbrains.plugins.gradle.util;
 
 import com.intellij.ide.actions.OpenProjectFileChooserDescriptor;
-import com.intellij.openapi.components.ServiceManager;
 import com.intellij.openapi.fileChooser.FileChooserDescriptor;
 import com.intellij.openapi.fileChooser.FileTypeDescriptor;
-import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.NotNullLazyValue;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.service.GradleInstallationManager;
-import org.jetbrains.plugins.gradle.settings.GradleSettings;
-import org.jetbrains.plugins.gradle.ui.MatrixControlBuilder;
 
 import java.io.*;
 import java.util.Arrays;
 import java.util.Properties;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
 
 /**
  * Holds miscellaneous utility methods.
@@ -28,18 +20,7 @@
  */
 public class GradleUtil {
 
-  public static final  String  SYSTEM_DIRECTORY_PATH_KEY    = "GRADLE_USER_HOME";
   private static final String  WRAPPER_VERSION_PROPERTY_KEY = "distributionUrl";
-  private static final Pattern WRAPPER_VERSION_PATTERN      = Pattern.compile(".*gradle-(.+)-bin.zip");
-
-  private static final NotNullLazyValue<GradleInstallationManager> INSTALLATION_MANAGER =
-    new NotNullLazyValue<GradleInstallationManager>() {
-      @NotNull
-      @Override
-      protected GradleInstallationManager compute() {
-        return ServiceManager.getService(GradleInstallationManager.class);
-      }
-    };
 
   private GradleUtil() {
   }
@@ -64,7 +45,7 @@
 
   @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
   public static boolean isGradleWrapperDefined(@Nullable String gradleProjectPath) {
-    return !StringUtil.isEmpty(getWrapperVersion(gradleProjectPath));
+    return !StringUtil.isEmpty(getWrapperDistribution(gradleProjectPath));
   }
 
   /**
@@ -75,7 +56,7 @@
    *                           if any; <code>null</code> otherwise
    */
   @Nullable
-  public static String getWrapperVersion(@Nullable String gradleProjectPath) {
+  public static String getWrapperDistribution(@Nullable String gradleProjectPath) {
     if (gradleProjectPath == null) {
       return null;
     }
@@ -118,14 +99,12 @@
       //noinspection IOResourceOpenedButNotSafelyClosed
       reader = new BufferedReader(new FileReader(candidates[0]));
       props.load(reader);
-      String value = props.getProperty(WRAPPER_VERSION_PROPERTY_KEY);
-      if (StringUtil.isEmpty(value)) {
+      String distribution = props.getProperty(WRAPPER_VERSION_PROPERTY_KEY);
+      if (StringUtil.isEmpty(distribution)) {
         return null;
       }
-      Matcher matcher = WRAPPER_VERSION_PATTERN.matcher(value);
-      if (matcher.matches()) {
-        return matcher.group(1);
-      }
+      String shortName = StringUtil.getShortName(distribution, '/');
+      return StringUtil.trimEnd(shortName, ".zip");
     }
     catch (IOException e) {
       GradleLog.LOG.warn(
@@ -147,29 +126,6 @@
   }
 
   /**
-   * @return    {@link MatrixControlBuilder} with predefined set of columns ('gradle' and 'intellij')
-   */
-  @NotNull
-  public static MatrixControlBuilder getConflictChangeBuilder() {
-    // TODO den implement
-    final String gradle = "";
-    final String intellij = "";
-//    final String gradle = ExternalSystemBundle.message("gradle.name");
-//    final String intellij = ExternalSystemBundle.message("gradle.ide");
-    return new MatrixControlBuilder(gradle, intellij);
-  }
-
-  public static boolean isGradleAvailable(@Nullable Project project) {
-    if (project != null) {
-      GradleSettings settings = GradleSettings.getInstance(project);
-      if (!settings.isPreferLocalInstallationToWrapper() && isGradleWrapperDefined(settings.getLinkedExternalProjectPath())) {
-        return true;
-      }
-    }
-    return INSTALLATION_MANAGER.getValue().getGradleHome(project) != null;
-  }
-
-  /**
    * We use this class in order to avoid static initialisation of the wrapped object - it loads number of pico container-based
    * dependencies that are unavailable to the slave gradle project, so, we don't want to get unexpected NPE there.
    */
diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/config/GradleConfigurableTest.groovy b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/config/GradleConfigurableTest.groovy
index e79149c..867c39a 100644
--- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/config/GradleConfigurableTest.groovy
+++ b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/config/GradleConfigurableTest.groovy
@@ -1,6 +1,5 @@
 package org.jetbrains.plugins.gradle.config
 
-import com.intellij.openapi.externalSystem.service.settings.AbstractExternalProjectConfigurable
 import com.intellij.openapi.project.Project
 import org.jetbrains.plugins.gradle.settings.GradleSettings
 import org.junit.Before
@@ -16,7 +15,6 @@
   static def INVALID_GRADLE_HOME = "invalid"
   static def VALID_LINKED_PATH_WITH_WRAPPER = "linked path with wrapper"
   
-  def AbstractExternalProjectConfigurable configurable
   def projectImpl
   Project defaultProject = {} as Project
   Project project
diff --git a/plugins/groovy/resources/fileTemplates/j2ee/GroovyServerPage.gsp.ft b/plugins/groovy/resources/fileTemplates/j2ee/GroovyServerPage.gsp.ft
index 52d4ffe..2f59b5e 100644
--- a/plugins/groovy/resources/fileTemplates/j2ee/GroovyServerPage.gsp.ft
+++ b/plugins/groovy/resources/fileTemplates/j2ee/GroovyServerPage.gsp.ft
@@ -3,7 +3,6 @@
   User: ${USER}
   Date: ${DATE}
   Time: ${TIME}
-  To change this template use File | Settings | File Templates.
 --%>
 
 <%@ page contentType="text/html;charset=UTF-8" %>
diff --git a/plugins/groovy/resources/intentionDescriptions/FlipIfIntention/after.groovy.template b/plugins/groovy/resources/intentionDescriptions/FlipIfIntention/after.groovy.template
new file mode 100644
index 0000000..25d4592
--- /dev/null
+++ b/plugins/groovy/resources/intentionDescriptions/FlipIfIntention/after.groovy.template
@@ -0,0 +1,6 @@
+if (cond2) {
+  <spot>doSomething2()</spot>
+}
+else if (cond1) {
+  <spot>doSomething1()</spot>
+}
\ No newline at end of file
diff --git a/plugins/groovy/resources/intentionDescriptions/FlipIfIntention/before.groovy.template b/plugins/groovy/resources/intentionDescriptions/FlipIfIntention/before.groovy.template
new file mode 100644
index 0000000..75c88f5
--- /dev/null
+++ b/plugins/groovy/resources/intentionDescriptions/FlipIfIntention/before.groovy.template
@@ -0,0 +1,6 @@
+if (cond1) {
+  <spot>doSomething1()</spot>
+}
+else if (cond2) {
+  <spot>doSomething2()</spot>
+}
\ No newline at end of file
diff --git a/plugins/groovy/resources/intentionDescriptions/FlipIfIntention/description.html b/plugins/groovy/resources/intentionDescriptions/FlipIfIntention/description.html
new file mode 100644
index 0000000..f678475
--- /dev/null
+++ b/plugins/groovy/resources/intentionDescriptions/FlipIfIntention/description.html
@@ -0,0 +1,5 @@
+<html>
+<body>
+This intention changes the order of if-statements in if-else-if chain.
+</body>
+</html>
diff --git a/plugins/groovy/resources/intentionDescriptions/ReplaceIfWithTernaryIntention/after.groovy.template b/plugins/groovy/resources/intentionDescriptions/ReplaceIfWithTernaryIntention/after.groovy.template
new file mode 100644
index 0000000..0f413f6
--- /dev/null
+++ b/plugins/groovy/resources/intentionDescriptions/ReplaceIfWithTernaryIntention/after.groovy.template
@@ -0,0 +1 @@
+return cond() : first() : second()
\ No newline at end of file
diff --git a/plugins/groovy/resources/intentionDescriptions/ReplaceIfWithTernaryIntention/before.groovy.template b/plugins/groovy/resources/intentionDescriptions/ReplaceIfWithTernaryIntention/before.groovy.template
new file mode 100644
index 0000000..c9bf0d6
--- /dev/null
+++ b/plugins/groovy/resources/intentionDescriptions/ReplaceIfWithTernaryIntention/before.groovy.template
@@ -0,0 +1,6 @@
+<spot>if</spot> (cond()) {
+  return first()
+}
+else {
+  return second()
+}
\ No newline at end of file
diff --git a/plugins/groovy/resources/intentionDescriptions/ReplaceIfWithTernaryIntention/description.html b/plugins/groovy/resources/intentionDescriptions/ReplaceIfWithTernaryIntention/description.html
new file mode 100644
index 0000000..e7e00ed
--- /dev/null
+++ b/plugins/groovy/resources/intentionDescriptions/ReplaceIfWithTernaryIntention/description.html
@@ -0,0 +1,7 @@
+<html>
+<body>
+This intention replaces if-statement with equivalent ternary operator
+<!-- tooltip end -->
+Text after this comment will not be shown in tooltips.
+</body>
+</html>
\ No newline at end of file
diff --git a/plugins/groovy/src/META-INF/plugin.xml b/plugins/groovy/src/META-INF/plugin.xml
index 2652660..c214cd7 100644
--- a/plugins/groovy/src/META-INF/plugin.xml
+++ b/plugins/groovy/src/META-INF/plugin.xml
@@ -1012,11 +1012,21 @@
     <intentionAction>
       <bundleName>org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle</bundleName>
       <categoryKey>intention.category.groovy/intention.category.control.flow</categoryKey>
+      <className>org.jetbrains.plugins.groovy.intentions.control.FlipIfIntention</className>
+    </intentionAction>
+    <intentionAction>
+      <bundleName>org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle</bundleName>
+      <categoryKey>intention.category.groovy/intention.category.control.flow</categoryKey>
       <className>org.jetbrains.plugins.groovy.intentions.control.ReplaceTernaryWithIfElseIntention</className>
     </intentionAction>
     <intentionAction>
       <bundleName>org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle</bundleName>
       <categoryKey>intention.category.groovy/intention.category.control.flow</categoryKey>
+      <className>org.jetbrains.plugins.groovy.intentions.control.ReplaceIfWithTernaryIntention</className>
+    </intentionAction>
+    <intentionAction>
+      <bundleName>org.jetbrains.plugins.groovy.intentions.GroovyIntentionsBundle</bundleName>
+      <categoryKey>intention.category.groovy/intention.category.control.flow</categoryKey>
       <className>org.jetbrains.plugins.groovy.intentions.control.SimplifyTernaryOperatorIntention</className>
     </intentionAction>
     <intentionAction>
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java
index 4f71412..f336963 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/GroovyAnnotator.java
@@ -1374,14 +1374,21 @@
     if (value instanceof GrReferenceExpression) {
       PsiElement resolved = ((GrReferenceExpression)value).resolve();
       if (resolved instanceof PsiClass) return false;
+      if (resolved instanceof PsiEnumConstant) return false;
 
       if (resolved instanceof GrAccessorMethod) resolved = ((GrAccessorMethod)resolved).getProperty();
       if (resolved instanceof PsiField) {
         GrExpression initializer;
         try {
-          initializer = resolved instanceof GrField
-                        ? ((GrField)resolved).getInitializerGroovy()
-                        : (GrExpression)ExpressionConverter.getExpression(((PsiField)resolved).getInitializer(), GroovyFileType.GROOVY_LANGUAGE, value.getProject());
+          if (resolved instanceof GrField) {
+            initializer = ((GrField)resolved).getInitializerGroovy();
+          }
+          else {
+            final PsiExpression _initializer = ((PsiField)resolved).getInitializer();
+            initializer = _initializer != null
+                          ? (GrExpression)ExpressionConverter.getExpression(_initializer, GroovyFileType.GROOVY_LANGUAGE, value.getProject())
+                          : null;
+          }
         }
         catch (IncorrectOperationException e) {
           initializer = null;
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java
index 64443d4..ef3bf4b 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/CreateLocalVariableFromUsageFix.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -33,7 +33,6 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.groovy.GroovyBundle;
-import org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression;
 import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariableDeclaration;
@@ -42,6 +41,7 @@
 import org.jetbrains.plugins.groovy.lang.psi.api.util.GrVariableDeclarationOwner;
 import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider;
 import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.TypeConstraint;
+import org.jetbrains.plugins.groovy.template.expressions.ChooseTypeExpression;
 
 /**
  * @author ven
@@ -82,8 +82,7 @@
 
   public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
     PsiClassType type = JavaPsiFacade.getInstance(project).getElementFactory().createTypeByFQClassName("Object", GlobalSearchScope.allScope(project));
-    GrVariableDeclaration decl = GroovyPsiElementFactory.getInstance(project).createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY,
-        null, type, myRefExpression.getReferenceName());
+    GrVariableDeclaration decl = GroovyPsiElementFactory.getInstance(project).createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, "", type, myRefExpression.getReferenceName());
     int offset = myRefExpression.getTextRange().getStartOffset();
     GrStatement anchor = findAnchor(file, offset);
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/declaration/GrMethodMayBeStaticInspection.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/declaration/GrMethodMayBeStaticInspection.java
index 7987191..1dfe90c 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/declaration/GrMethodMayBeStaticInspection.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/declaration/GrMethodMayBeStaticInspection.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -112,6 +112,7 @@
     final GrParameter[] parameters = method.getParameters();
     if (method.getName().equals("propertyMissing") && (parameters.length == 2 || parameters.length == 1)) return true;
     if (method.getName().equals("methodMissing") && (parameters.length == 2 || parameters.length == 1)) return true;
+    if (method.getContainingClass() instanceof PsiAnonymousClass) return true;
 
     for (GrMethodMayBeStaticInspectionFilter filter : GrMethodMayBeStaticInspectionFilter.EP_NAME.getExtensions()) {
       if (filter.isIgnored(method)) {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/noReturnMethod/MissingReturnInspection.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/noReturnMethod/MissingReturnInspection.java
index bf16de65..2248419 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/noReturnMethod/MissingReturnInspection.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/noReturnMethod/MissingReturnInspection.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -32,7 +32,6 @@
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
-import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrAssertStatement;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
@@ -120,38 +119,19 @@
     ControlFlowUtils.visitAllExitPoints(block, new ControlFlowUtils.ExitPointVisitor() {
       @Override
       public boolean visitExitPoint(Instruction instruction, @Nullable GrExpression returnValue) {
-        if (instruction instanceof MaybeReturnInstruction) {
-          if (((MaybeReturnInstruction)instruction).mayReturnValue()) {
-            sometimesHaveReturn.set(true);
-          }
-          else {
-            alwaysHaveReturn.set(false);
-          }
+        if (instruction instanceof ThrowingInstruction) return true;
+        if (instruction instanceof MaybeReturnInstruction && ((MaybeReturnInstruction)instruction).mayReturnValue()) {
+          sometimesHaveReturn.set(true);
           return true;
         }
-        final PsiElement element = instruction.getElement();
-        if (element instanceof GrReturnStatement) {
+
+        if (instruction.getElement() instanceof GrReturnStatement && returnValue != null) {
           sometimesHaveReturn.set(true);
-          if (returnValue != null) {
-            hasExplicitReturn.set(true);
-          }
+          hasExplicitReturn.set(true);
+          return true;
         }
-        else if (instruction instanceof ThrowingInstruction) {
-          sometimesHaveReturn.set(true);
-        }
-        else if (element instanceof GrAssertStatement) {
-          sometimesHaveReturn.set(true);
-          int count = 0;
-          for (Instruction _i : instruction.allSuccessors()) {
-            count++;
-          }
-          if (count <= 1) {
-            alwaysHaveReturn.set(false);
-          }
-        }
-        else {
-          alwaysHaveReturn.set(false);
-        }
+
+        alwaysHaveReturn.set(false);
         return true;
       }
     });
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeStyle/GroovyLanguageCodeStyleSettingsProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeStyle/GroovyLanguageCodeStyleSettingsProvider.java
index 8ac2121..995ac82 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeStyle/GroovyLanguageCodeStyleSettingsProvider.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeStyle/GroovyLanguageCodeStyleSettingsProvider.java
@@ -221,6 +221,28 @@
       consumer.showCustomOption(GroovyCodeStyleSettings.class, "SPACE_WITHIN_TUPLE_EXPRESSION", "Tuple assignment expression", CodeStyleSettingsCustomizable.SPACES_WITHIN);
       return;
     }
+    if (settingsType == SettingsType.BLANK_LINES_SETTINGS) {
+
+      consumer.showStandardOptions(
+        "KEEP_BLANK_LINES_IN_DECLARATIONS",
+        "KEEP_BLANK_LINES_IN_CODE",
+        "KEEP_BLANK_LINES_BEFORE_RBRACE",
+
+        "BLANK_LINES_BEFORE_PACKAGE",
+        "BLANK_LINES_AFTER_PACKAGE",
+        "BLANK_LINES_BEFORE_IMPORTS",
+        "BLANK_LINES_AFTER_IMPORTS",
+        "BLANK_LINES_AROUND_CLASS",
+        "BLANK_LINES_AFTER_CLASS_HEADER",
+        //"BLANK_LINES_AFTER_ANONYMOUS_CLASS_HEADER",
+        "BLANK_LINES_AROUND_FIELD_IN_INTERFACE",
+        "BLANK_LINES_AROUND_FIELD",
+        "BLANK_LINES_AROUND_METHOD_IN_INTERFACE",
+        "BLANK_LINES_AROUND_METHOD",
+        "BLANK_LINES_BEFORE_METHOD_BODY"
+      );
+      return;
+    }
     consumer.showAllStandardOptions();
   }
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessor.java
index d292539..8fb369f 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessor.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessor.java
@@ -61,13 +61,13 @@
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrEnumConstant;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
 import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement;
-import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.packaging.GrPackageDefinition;
 import org.jetbrains.plugins.groovy.lang.psi.api.types.GrArrayTypeElement;
 import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeArgumentList;
 import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameterList;
 
 import static org.jetbrains.plugins.groovy.GroovyFileType.GROOVY_LANGUAGE;
 import static org.jetbrains.plugins.groovy.formatter.models.spacing.SpacingTokens.*;
+import static org.jetbrains.plugins.groovy.formatter.models.spacing.SpacingTokens.GROOVY_DOC_COMMENT;
 import static org.jetbrains.plugins.groovy.formatter.models.spacing.SpacingTokens.mCOMMA;
 import static org.jetbrains.plugins.groovy.formatter.models.spacing.SpacingTokens.mELVIS;
 import static org.jetbrains.plugins.groovy.formatter.models.spacing.SpacingTokens.mQUESTION;
@@ -177,7 +177,7 @@
       prev = FormatterUtil.getPreviousNonWhitespaceLeaf(prev);
     }
     if (prev != null && prev.getElementType() == mSL_COMMENT) {
-      myResult = Spacing.createSpacing(0, Integer.MAX_VALUE, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+      myResult = Spacing.createSpacing(0, Integer.MAX_VALUE, 1, mySettings.KEEP_LINE_BREAKS, keepBlankLines());
       return true;
     }
     return false;
@@ -223,7 +223,7 @@
 
   private void createDependentLFSpacing(final boolean isLineFeed, final boolean isSpace, @NotNull final TextRange range) {
     if (isLineFeed) {
-      myResult = Spacing.createDependentLFSpacing(isSpace ? 1 : 0, isSpace ? 1 : 0, range, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+      myResult = Spacing.createDependentLFSpacing(isSpace ? 1 : 0, isSpace ? 1 : 0, range, mySettings.KEEP_LINE_BREAKS, keepBlankLines());
     }
     else {
       createSpaceInCode(isSpace);
@@ -331,13 +331,51 @@
 
   @Override
   public void visitFile(GroovyFileBase file) {
-    if (myType1 == PACKAGE_DEFINITION && myType2 != mSEMI ||
-        myType1 == mSEMI && getStatementBySemicolon(myChild1.getPsi()) instanceof GrPackageDefinition) {
-      myResult = Spacing.createSpacing(0, 0, mySettings.BLANK_LINES_AFTER_PACKAGE + 1, mySettings.KEEP_LINE_BREAKS, 100);
+    if (isAfterElementOrSemi(PACKAGE_DEFINITION)) {
+      myResult = Spacing.createSpacing(0, 0, mySettings.BLANK_LINES_AFTER_PACKAGE + 1, mySettings.KEEP_LINE_BREAKS, Integer.MAX_VALUE / 2);
     }
     else if (myType2 == PACKAGE_DEFINITION) {
-      myResult = Spacing.createSpacing(0, 0, mySettings.BLANK_LINES_BEFORE_PACKAGE + 1, mySettings.KEEP_LINE_BREAKS, 100);
+      myResult = Spacing.createSpacing(0, 0, mySettings.BLANK_LINES_BEFORE_PACKAGE + 1, mySettings.KEEP_LINE_BREAKS, Integer.MAX_VALUE / 2);
     }
+    else if (TYPE_DEFINITION_TYPES.contains(myType1) || TYPE_DEFINITION_TYPES.contains(myType2)) {
+      if (myType1 == GROOVY_DOC_COMMENT) {
+        createLF(true);
+      }
+      else {
+        myResult = Spacing.createSpacing(0, 0, mySettings.BLANK_LINES_AROUND_CLASS + 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_DECLARATIONS);
+      }
+    }
+    else if (isAfterElementOrSemi(IMPORT_STATEMENT) && myType2 != IMPORT_STATEMENT) { //after imports
+      myResult = Spacing.createSpacing(0, 0, mySettings.BLANK_LINES_AFTER_IMPORTS + 1, mySettings.KEEP_LINE_BREAKS, Integer.MAX_VALUE / 2);
+    }
+    else if (myType1 != IMPORT_STATEMENT && !isSemiAfter(IMPORT_STATEMENT) && myType2 == IMPORT_STATEMENT) { //before imports
+      myResult = Spacing.createSpacing(0, 0, mySettings.BLANK_LINES_BEFORE_IMPORTS, mySettings.KEEP_LINE_BREAKS, Integer.MAX_VALUE / 2);
+    }
+    else if (isAfterElementOrSemi(IMPORT_STATEMENT) && myType2 == IMPORT_STATEMENT) {
+      myResult = Spacing.createSpacing(0, 0, 1, mySettings.KEEP_LINE_BREAKS, Integer.MAX_VALUE / 2);
+    }
+    else {
+      processClassMembers(null);
+    }
+  }
+
+  private boolean isAfterElementOrSemi(final IElementType elementType) {
+    return myType1 == elementType && myType2 != mSEMI || isSemiAfter(PACKAGE_DEFINITION);
+  }
+
+  private boolean isSemiAfter(@NotNull IElementType statement) {
+    return myType1 == mSEMI && getStatementTypeBySemi(myChild1) == statement;
+  }
+
+  private boolean isSemiAfter(@NotNull TokenSet set) {
+    return myType1 == mSEMI && set.contains(getStatementTypeBySemi(myChild1));
+  }
+
+  @Nullable
+  private static IElementType getStatementTypeBySemi(@NotNull ASTNode semi) {
+    final GrTopStatement statement = getStatementBySemicolon(semi.getPsi());
+    if (statement == null) return null;
+    return statement.getNode().getElementType();
   }
 
   @Nullable
@@ -369,16 +407,13 @@
       }
     }
     else if (myType1 == mLCURLY && myType2 == mRCURLY) {  //empty closure
-      myResult = Spacing.createSpacing(0, 0, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+      createSpaceInCode(false);
     }
     else if (myType1 == mLCURLY && myType2 != PARAMETERS_LIST && myType2 != mCLOSABLE_BLOCK_OP || myType2 == mRCURLY) { //spaces between statements
-
       boolean spacesWithinBraces = closure.getParent() instanceof GrStringInjection
                   ? myGroovySettings.SPACE_WITHIN_GSTRING_INJECTION_BRACES
                   : mySettings.SPACE_WITHIN_BRACES;
-      int space = spacesWithinBraces ? 1 : 0;
-      myResult = Spacing.createDependentLFSpacing(space, space, closure.getTextRange(), mySettings.KEEP_LINE_BREAKS,
-                                                  mySettings.KEEP_BLANK_LINES_IN_CODE);
+      createDependentLFSpacing(true, spacesWithinBraces, closure.getTextRange());
     }
     else if (myType1 == mCLOSABLE_BLOCK_OP) {
       myResult = GroovySpacingProcessorBasic.createDependentSpacingForClosure(mySettings, myGroovySettings, closure, true);
@@ -393,20 +428,27 @@
   }
 
   public void visitOpenBlock(GrOpenBlock block) {
-
-    final PsiElement parent = block.getParent();
-    boolean keepInOneLine = parent instanceof GrMethod ? mySettings.KEEP_SIMPLE_METHODS_IN_ONE_LINE :
-                            mySettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE;
+    boolean isMethod = block.getParent() instanceof GrMethod;
+    boolean keepInOneLine = isMethod ? mySettings.KEEP_SIMPLE_METHODS_IN_ONE_LINE : mySettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE;
 
     if (myType1 == mLCURLY && myType2 == mRCURLY) {
-      myResult = Spacing.createSpacing(0, 0, keepInOneLine ? 0 : 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+      createLF(!keepInOneLine);
     }
-    else if (myType1 == mLCURLY || myType2 == mRCURLY) {
+    else if (myType1 == mLCURLY) {
       if (keepInOneLine) {
-        myResult = Spacing.createDependentLFSpacing(1, 1, block.getTextRange(), mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+        createDependentLFSpacing(true, mySettings.SPACE_WITHIN_BRACES, block.getTextRange());
       }
       else {
-        myResult = Spacing.createSpacing(1, 1, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+        int lineFeedsCount = isMethod ? mySettings.BLANK_LINES_BEFORE_METHOD_BODY + 1 : 1;
+        myResult = Spacing.createSpacing(0, 0, lineFeedsCount, mySettings.KEEP_LINE_BREAKS, keepBlankLines());
+      }
+    }
+    else if (myType2 == mRCURLY) {
+      if (keepInOneLine) {
+        createDependentLFSpacing(true, mySettings.SPACE_WITHIN_BRACES, block.getTextRange());
+      }
+      else {
+        createLF(true);
       }
     }
   }
@@ -434,16 +476,54 @@
   public void visitTypeDefinitionBody(GrTypeDefinitionBody typeDefinitionBody) {
     if (myType1 == mLCURLY && myType2 == mRCURLY) {
       if (mySettings.KEEP_SIMPLE_CLASSES_IN_ONE_LINE) {
-        myResult = Spacing.createSpacing(0, 0, 0, mySettings.KEEP_LINE_BREAKS, 0);
+        createSpaceInCode(false);
       }
       else {
-        myResult = Spacing.createSpacing(0, 0, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_BEFORE_RBRACE);
+        createLF(true);
       }
-    } else if (myType1 == mLCURLY) {
-      myResult = Spacing.createSpacing(0, 0, mySettings.BLANK_LINES_AFTER_CLASS_HEADER + 1,
-                                       mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_DECLARATIONS);
-    } else if (myType2 == mRCURLY) {
-      myResult = Spacing.createSpacing(0, Integer.MAX_VALUE, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_BEFORE_RBRACE);
+    }
+    else if (myType1 == mLCURLY) {
+      myResult = Spacing.createSpacing(0, 0, mySettings.BLANK_LINES_AFTER_CLASS_HEADER + 1, mySettings.KEEP_LINE_BREAKS,
+                                       mySettings.KEEP_BLANK_LINES_IN_DECLARATIONS);
+    }
+    else if (myType2 == mRCURLY) {
+      createLF(true);
+    }
+    else {
+      processClassMembers(typeDefinitionBody);
+    }
+  }
+
+  private void processClassMembers(@Nullable GrTypeDefinitionBody typeDefinitionBody) {
+    final boolean isInterface = typeDefinitionBody != null && ((GrTypeDefinition)typeDefinitionBody.getParent()).isInterface();
+
+    if (myType2 == mSEMI) return;
+
+    if (typeDefinitionBody != null) { //check variable definitions only inside class body
+      if ((myType1 == VARIABLE_DEFINITION || isSemiAfter(VARIABLE_DEFINITION)) && METHOD_DEFS.contains(myType2)) {
+        final int minBlankLines = Math.max(
+          isInterface ? mySettings.BLANK_LINES_AROUND_METHOD_IN_INTERFACE : mySettings.BLANK_LINES_AROUND_METHOD,
+          isInterface ? mySettings.BLANK_LINES_AROUND_FIELD_IN_INTERFACE : mySettings.BLANK_LINES_AROUND_FIELD
+        );
+        myResult = Spacing.createSpacing(0, 0, minBlankLines + 1, mySettings.KEEP_LINE_BREAKS, keepBlankLines());
+        return;
+      }
+      else if (myType1 == VARIABLE_DEFINITION || isSemiAfter(VARIABLE_DEFINITION) || myType2 == VARIABLE_DEFINITION) {
+        final int minBlankLines =
+          isInterface ? mySettings.BLANK_LINES_AROUND_FIELD_IN_INTERFACE : mySettings.BLANK_LINES_AROUND_FIELD;
+        myResult = Spacing.createSpacing(0, 0, minBlankLines + 1, mySettings.KEEP_LINE_BREAKS, keepBlankLines());
+        return;
+      }
+    }
+
+    if (METHOD_DEFS.contains(myType1) || isSemiAfter(METHOD_DEFS) || METHOD_DEFS.contains((myType2))) {
+      if (myType1 == GROOVY_DOC_COMMENT) {
+        createLF(true);
+      }
+      else {
+        final int minBlankLines = isInterface ? mySettings.BLANK_LINES_AROUND_METHOD_IN_INTERFACE : mySettings.BLANK_LINES_AROUND_METHOD;
+        myResult = Spacing.createSpacing(0, 0, minBlankLines + 1, mySettings.KEEP_LINE_BREAKS, keepBlankLines());
+      }
     }
   }
 
@@ -489,7 +569,7 @@
     }
     else if (myType1 == mRPAREN && myType2 == THROW_CLAUSE) {
       if (mySettings.THROWS_KEYWORD_WRAP == CommonCodeStyleSettings.WRAP_ALWAYS) {
-        createLF();
+        createLF(true);
       }
       else {
         createSpaceInCode(true);
@@ -505,9 +585,6 @@
     else if (myType1 == MODIFIERS) {
       processModifierList(myChild1);
     }
-    else if (COMMENT_SET.contains(myType1) && (myType2 == MODIFIERS || myType2 == REFERENCE_ELEMENT)) {
-      myResult = Spacing.createSpacing(0, 0, 1, mySettings.KEEP_LINE_BREAKS, 0);
-    }
     else if (myType2 == TYPE_PARAMETER_LIST) {
       manageSpaceBeforeTypeParameters();
     }
@@ -567,7 +644,7 @@
   public void visitModifierList(GrModifierList modifierList) {
     int annotationWrap = getAnnotationWrap(myParent.getParent());
     if (myChild1.getElementType() == ANNOTATION && annotationWrap == CommonCodeStyleSettings.WRAP_ALWAYS) {
-      myResult = Spacing.createSpacing(0, 0, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+      createLF(true);
     }
     else {
       createSpaceProperty(true, false, 0);
@@ -591,19 +668,16 @@
   }
 
   private void visitDocMember() {
-    myResult = Spacing.createSpacing(0, 0, 0, false, 0);
+    createSpaceProperty(false, false, 0);
   }
 
   public void visitDocMethodParameterList(GrDocMethodParams params) {
-    if (myType1 == mGDOC_TAG_VALUE_LPAREN || myType2 == mGDOC_TAG_VALUE_RPAREN) {
-      myResult = Spacing.createSpacing(0, 0, 0, false, 0);
-      return;
+    if (myType1 == mGDOC_TAG_VALUE_LPAREN || myType2 == mGDOC_TAG_VALUE_RPAREN || myType2 == mGDOC_TAG_VALUE_COMMA) {
+      createSpaceProperty(false, false, 0);
     }
-    if (myType2 == mGDOC_TAG_VALUE_COMMA) {
-      myResult = Spacing.createSpacing(0, 0, 0, false, 0);
-      return;
+    else {
+      createSpaceInCode(true);
     }
-    createSpaceInCode(true);
   }
 
   public void visitDocMethodParameter(GrDocMethodParameter parameter) {
@@ -651,13 +725,13 @@
 
   public void visitTryStatement(GrTryCatchStatement tryCatchStatement) {
     if (myType2 == FINALLY_CLAUSE) {
-      processOnNewLineCondition(mySettings.FINALLY_ON_NEW_LINE, mySettings.SPACE_BEFORE_FINALLY_KEYWORD);
+      processTryOnNewLineCondition(mySettings.FINALLY_ON_NEW_LINE, mySettings.SPACE_BEFORE_FINALLY_KEYWORD);
     }
     else if (isOpenBlock(myType2)) {
       createSpaceBeforeLBrace(mySettings.SPACE_BEFORE_TRY_LBRACE, mySettings.BRACE_STYLE, null, mySettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE);
     }
     else if (myType2 == CATCH_CLAUSE) {
-      processOnNewLineCondition(mySettings.CATCH_ON_NEW_LINE, mySettings.SPACE_BEFORE_CATCH_KEYWORD);
+      processTryOnNewLineCondition(mySettings.CATCH_ON_NEW_LINE, mySettings.SPACE_BEFORE_CATCH_KEYWORD);
     }
   }
 
@@ -670,6 +744,7 @@
 
   @Override
   public void visitBinaryExpression(GrBinaryExpression expression) {
+    @SuppressWarnings("SimplifiableConditionalExpression" )
     boolean spaceAround = isLeftOrRight(LOGICAL_OPERATORS)        ? mySettings.SPACE_AROUND_LOGICAL_OPERATORS :
                           isLeftOrRight(EQUALITY_OPERATORS)       ? mySettings.SPACE_AROUND_EQUALITY_OPERATORS :
                           isLeftOrRight(RELATIONAL_OPERATORS)     ? mySettings.SPACE_AROUND_RELATIONAL_OPERATORS :
@@ -710,7 +785,7 @@
                               mySettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE);
     }
     else if (myType1 == mLCURLY || myType2 == mRCURLY) {
-      createLF();
+      createLF(true);
     }
   }
 
@@ -732,27 +807,21 @@
         mySettings.getRootSettings().JD_LEADING_ASTERISKS_ARE_ENABLED) {
       IElementType type = myChild1.getLastChildNode().getElementType();
       if (type == mGDOC_ASTERISKS) {
-        myResult = Spacing.createSpacing(1, 1, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+        createSpaceInCode(true);
       }
     }
   }
 
   public void visitDocTag(GrDocTag docTag) {
-    if (myType1 == mGDOC_INLINE_TAG_START ||
-        myType2 == mGDOC_INLINE_TAG_END) {
-      myResult = Spacing.createSpacing(0, 0, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+    if (myType1 == mGDOC_INLINE_TAG_START || myType2 == mGDOC_INLINE_TAG_END) {
+      createSpaceInCode(false);
     }
   }
 
   @Override
   public void visitNamedArgument(GrNamedArgument argument) {
     if (myType1 == mCOLON) {
-      if (myGroovySettings.SPACE_IN_NAMED_ARGUMENT) {
-        myResult = Spacing.createSpacing(1, 1, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
-      }
-      else {
-        myResult = Spacing.createSpacing(0, 0, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
-      }
+      createSpaceInCode(myGroovySettings.SPACE_IN_NAMED_ARGUMENT);
     }
   }
 
@@ -781,11 +850,11 @@
   public void visitIfStatement(GrIfStatement ifStatement) {
     if (myType2 == kELSE) {
       if (!isOpenBlock(myType1) && myType1 != BLOCK_STATEMENT) {
-        myResult = Spacing.createSpacing(1, 1, 0, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+        createSpaceInCode(true);
       }
       else {
         if (mySettings.ELSE_ON_NEW_LINE) {
-          myResult = Spacing.createSpacing(0, 0, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+          createLF(true);
         }
         else {
           createSpaceProperty(mySettings.SPACE_BEFORE_ELSE_KEYWORD, false, 0);
@@ -798,7 +867,7 @@
           createSpaceProperty(true, false, 0);
         }
         else {
-          myResult = Spacing.createSpacing(1, 1, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+          createLF(true);
         }
       }
       else {
@@ -841,10 +910,10 @@
                                 mySettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE);
       }
       else if (mySettings.KEEP_CONTROL_STATEMENT_IN_ONE_LINE) {
-        myResult = Spacing.createDependentLFSpacing(1, 1, myParent.getTextRange(), false, mySettings.KEEP_BLANK_LINES_IN_CODE);
+        createDependentLFSpacing(true, true, myParent.getTextRange());
       }
       else {
-        createLF();
+        createLF(true);
       }
     }
     else if (myType1 == mRPAREN) {
@@ -874,27 +943,27 @@
   }
 
 
-  private void processOnNewLineCondition(boolean onNewLine, boolean spaceIfNotNewLine) {
+  private void processTryOnNewLineCondition(boolean onNewLine, boolean spaceIfNotNewLine) {
     if (onNewLine) {
       if (mySettings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE) {
-        myResult =
-          Spacing.createDependentLFSpacing(0, 1, myParent.getTextRange(), mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+        myResult = Spacing.createDependentLFSpacing(0, 1, myParent.getTextRange(), mySettings.KEEP_LINE_BREAKS, keepBlankLines());
       }
       else {
-        myResult = Spacing.createSpacing(0, 0, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+        createLF(true);
       }
     }
     else {
-      createSpaceProperty(spaceIfNotNewLine, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+      createSpaceInCode(spaceIfNotNewLine);
     }
   }
 
 
   private void createSpacingBeforeElementInsideControlStatement() {
     if (mySettings.KEEP_CONTROL_STATEMENT_IN_ONE_LINE && myType1 != mSL_COMMENT) {
-      createSpaceProperty(true, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
-    } else {
-      myResult = Spacing.createSpacing(1, 1, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+      createSpaceInCode(true);
+    }
+    else {
+      createLF(true);
     }
   }
 
@@ -903,7 +972,7 @@
     int annotationWrap = getAnnotationWrap(myParent);
     if (modifierList.getLastChildNode().getElementType() == ANNOTATION && annotationWrap == CommonCodeStyleSettings.WRAP_ALWAYS ||
         mySettings.MODIFIER_LIST_WRAP) {
-      myResult = Spacing.createSpacing(0, 0, 1, mySettings.KEEP_LINE_BREAKS, mySettings.KEEP_BLANK_LINES_IN_CODE);
+      createLF(true);
     }
     else {
       createSpaceProperty(true, false, 0);
@@ -936,7 +1005,7 @@
   }
 
   private void createSpaceInCode(final boolean space) {
-    createSpaceProperty(space, mySettings.KEEP_BLANK_LINES_IN_CODE);
+    createSpaceProperty(space, keepBlankLines());
   }
 
   private void createSpaceProperty(boolean space, int keepBlankLines) {
@@ -962,25 +1031,36 @@
     else if (keepOneLine) {
       int space = spaceBeforeLbrace ? 1 : 0;
       myResult = Spacing.createDependentLFSpacing(space, space, myParent.getTextRange(), mySettings.KEEP_LINE_BREAKS,
-                                                  mySettings.KEEP_BLANK_LINES_IN_CODE);
+                                                  keepBlankLines());
     }
     else {
-      createLF();
+      createLF(true);
     }
   }
 
-  private void createLF() {
-    myResult = Spacing.createSpacing(0, 0, 1, false, mySettings.KEEP_BLANK_LINES_IN_CODE);
+  private void createLF(final boolean lf) {
+    myResult = Spacing.createSpacing(0, 0, lf ? 1 : 0, mySettings.KEEP_LINE_BREAKS, keepBlankLines());
   }
 
   private Spacing createNonLFSpace(int spaces, @Nullable final TextRange dependantRange, final boolean keepLineBreaks) {
     final ASTNode prev = FormatterUtil.getPreviousNonWhitespaceLeaf(myChild2);
     if (prev != null && prev.getElementType() == mSL_COMMENT) {
-      return Spacing.createSpacing(0, Integer.MAX_VALUE, 1, keepLineBreaks, mySettings.KEEP_BLANK_LINES_IN_CODE);
-    } else if (dependantRange != null) {
-      return Spacing.createDependentLFSpacing(spaces, spaces, dependantRange, keepLineBreaks, mySettings.KEEP_BLANK_LINES_IN_CODE);
-    } else {
-      return Spacing.createSpacing(spaces, spaces, 0, keepLineBreaks, mySettings.KEEP_BLANK_LINES_IN_CODE);
+      return Spacing.createSpacing(0, Integer.MAX_VALUE, 1, keepLineBreaks, keepBlankLines());
+    }
+    else if (dependantRange != null) {
+      return Spacing.createDependentLFSpacing(spaces, spaces, dependantRange, keepLineBreaks, keepBlankLines());
+    }
+    else {
+      return Spacing.createSpacing(spaces, spaces, 0, keepLineBreaks, keepBlankLines());
+    }
+  }
+
+  private int keepBlankLines() {
+    if (myType2 == mRCURLY) {
+      return mySettings.KEEP_BLANK_LINES_BEFORE_RBRACE;
+    }
+    else {
+      return mySettings.KEEP_BLANK_LINES_IN_CODE;
     }
   }
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessorBasic.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessorBasic.java
index acc4fbc..c7928d3 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessorBasic.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/formatter/processors/GroovySpacingProcessorBasic.java
@@ -46,7 +46,6 @@
 import static org.jetbrains.plugins.groovy.lang.groovydoc.parser.GroovyDocElementTypes.GROOVY_DOC_COMMENT;
 import static org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes.mTRIPLE_DOT;
 import static org.jetbrains.plugins.groovy.lang.lexer.TokenSets.DOTS;
-import static org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes.METHOD_DEFS;
 
 /**
  * @author ilyas
@@ -57,8 +56,6 @@
   private static final Spacing NO_SPACING = Spacing.createSpacing(0, 0, 0, false, 0);
   private static final Spacing COMMON_SPACING = Spacing.createSpacing(1, 1, 0, true, 100);
   private static final Spacing COMMON_SPACING_WITH_NL = Spacing.createSpacing(1, 1, 1, true, 100);
-  private static final Spacing IMPORT_BETWEEN_SPACING = Spacing.createSpacing(0, 0, 1, true, 100);
-  private static final Spacing IMPORT_OTHER_SPACING = Spacing.createSpacing(0, 0, 2, true, 100);
   private static final Spacing LAZY_SPACING = Spacing.createSpacing(0, 239, 0, true, 100);
 
   public static Spacing getSpacing(GroovyBlock child1,
@@ -95,21 +92,7 @@
       return COMMON_SPACING_WITH_NL;
     }
 
-    if (METHOD_DEFS.contains(leftType)) {
-      if (rightType == mSEMI) {
-        return NO_SPACING;
-      }
-      return Spacing.createSpacing(0, 0, settings.BLANK_LINES_AROUND_METHOD + 1, settings.KEEP_LINE_BREAKS, 100);
-    }
-
-    if (METHOD_DEFS.contains(rightType)) {
-      if (leftNode.getElementType() == GROOVY_DOC_COMMENT) {
-        return Spacing.createSpacing(0, 0, settings.BLANK_LINES_AROUND_METHOD, settings.KEEP_LINE_BREAKS, 0);
-      }
-      return Spacing.createSpacing(0, 0, settings.BLANK_LINES_AROUND_METHOD + 1, settings.KEEP_LINE_BREAKS, 100);
-    }
-
-    if (right != null && right instanceof GrTypeArgumentList) {
+    if (right instanceof GrTypeArgumentList) {
       return NO_SPACING_WITH_NEWLINE;
     }
 
@@ -136,16 +119,6 @@
       return NO_SPACING_WITH_NEWLINE;
     }
 
-/********** imports ************/
-    if (IMPORT_STATEMENT.equals(leftType) && IMPORT_STATEMENT.equals(rightType)) {
-      return IMPORT_BETWEEN_SPACING;
-    }
-    if ((IMPORT_STATEMENT.equals(leftType) &&
-         (!IMPORT_STATEMENT.equals(rightType) && !mSEMI.equals(rightType))) ||
-        ((!IMPORT_STATEMENT.equals(leftType) && !mSEMI.equals(leftType)) && IMPORT_STATEMENT.equals(rightType))) {
-      return IMPORT_OTHER_SPACING;
-    }
-
     //todo:check it for multiple assignments
     if ((VARIABLE_DEFINITION.equals(leftType) || VARIABLE_DEFINITION.equals(rightType)) &&
         !(leftNode.getTreeNext() instanceof PsiErrorElement)) {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/GroovyIntentionsBundle.properties b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/GroovyIntentionsBundle.properties
index 79d5f68..6843488 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/GroovyIntentionsBundle.properties
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/GroovyIntentionsBundle.properties
@@ -197,3 +197,7 @@
 cannot.create.class=Cannot create class
 gr.introduce.local.variable.intention.name=Introduce local variable
 gr.introduce.local.variable.intention.family.name=Groovy Introduce local variable
+flip.if.intention.name=Flip if statements
+flip.if.intention.family.name=Flip if statements
+replace.if.with.ternary.intention.name=Replace with ?:
+replace.if.with.ternary.intention.family.name=Replace if-statement with ternary operator
\ No newline at end of file
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/FlipIfIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/FlipIfIntention.java
new file mode 100644
index 0000000..28cf20f
--- /dev/null
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/FlipIfIntention.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.groovy.intentions.control;
+
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.project.Project;
+import com.intellij.psi.PsiElement;
+import com.intellij.util.IncorrectOperationException;
+import org.codehaus.groovy.runtime.DefaultGroovyMethods;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.groovy.intentions.base.Intention;
+import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
+import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrIfStatement;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement;
+
+/**
+ * @author Max Medvedev
+ */
+public class FlipIfIntention extends Intention {
+  @Override
+  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException {
+    final GrIfStatement ifStatement = DefaultGroovyMethods.asType(element.getParent(), GrIfStatement.class);
+    final GrIfStatement elseIf = getElseIf(ifStatement);
+
+    final GrIfStatement elseIfCopy = DefaultGroovyMethods.asType(elseIf.copy(), GrIfStatement.class);
+
+    elseIf.getCondition().replaceWithExpression(ifStatement.getCondition(), true);
+    elseIf.getThenBranch().replaceWithStatement(ifStatement.getThenBranch());
+
+    ifStatement.getCondition().replaceWithExpression(elseIfCopy.getCondition(), true);
+    ifStatement.getThenBranch().replaceWithStatement(elseIfCopy.getThenBranch());
+  }
+
+  @NotNull
+  @Override
+  protected PsiElementPredicate getElementPredicate() {
+    return new PsiElementPredicate() {
+      @Override
+      public boolean satisfiedBy(PsiElement element) {
+        if (!element.getNode().getElementType().equals(GroovyTokenTypes.kIF)) return false;
+        if (!(element.getParent() instanceof GrIfStatement)) return false;
+
+        final GrIfStatement ifStatement = DefaultGroovyMethods.asType(element.getParent(), GrIfStatement.class);
+
+        final GrIfStatement elseIf = getElseIf(ifStatement);
+        return elseIf != null && checkIf(ifStatement) && checkIf(elseIf);
+      }
+    };
+  }
+
+  private static GrIfStatement getElseIf(GrIfStatement ifStatement) {
+    final GrStatement elseBranch = ifStatement.getElseBranch();
+    if (elseBranch == null) return null;
+
+    if (elseBranch instanceof GrIfStatement) {
+      return DefaultGroovyMethods.asType(elseBranch, GrIfStatement.class);
+    }
+    else {
+      return null;
+    }
+  }
+
+  private static boolean checkIf(GrIfStatement ifStatement) {
+    return ifStatement.getCondition() != null && ifStatement.getThenBranch() != null;
+  }
+}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/ReplaceIfWithTernaryIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/ReplaceIfWithTernaryIntention.java
new file mode 100644
index 0000000..1ea8ce2
--- /dev/null
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/ReplaceIfWithTernaryIntention.java
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.groovy.intentions.control;
+
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.project.Project;
+import com.intellij.psi.PsiElement;
+import com.intellij.util.IncorrectOperationException;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.groovy.codeInspection.utils.EquivalenceChecker;
+import org.jetbrains.plugins.groovy.intentions.base.Intention;
+import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate;
+import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrIfStatement;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrConditionalExpression;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
+
+/**
+ * @author Max Medvedev
+ */
+public class ReplaceIfWithTernaryIntention extends Intention {
+  @Override
+  protected void processIntention(@NotNull PsiElement element, Project project, Editor editor) throws IncorrectOperationException {
+    final GrIfStatement ifStatement = (GrIfStatement)element.getParent();
+
+    final PsiElement thenBranch = skipBlock(ifStatement.getThenBranch());
+    final PsiElement elseBranch = skipBlock(ifStatement.getElseBranch());
+
+    if (thenBranch instanceof GrAssignmentExpression && elseBranch instanceof GrAssignmentExpression) {
+      final GrAssignmentExpression assignment = (GrAssignmentExpression)GroovyPsiElementFactory.getInstance(project).createStatementFromText("a = b ? c : d");
+
+      assignment.getLValue().replaceWithExpression(((GrAssignmentExpression)thenBranch).getLValue(), true);
+
+      final GrConditionalExpression conditional = (GrConditionalExpression)assignment.getRValue();
+      replaceConditional(conditional, ifStatement.getCondition(), ((GrAssignmentExpression)thenBranch).getRValue(), ((GrAssignmentExpression)elseBranch).getRValue());
+      ifStatement.replaceWithStatement(assignment);
+    }
+
+
+    if (thenBranch instanceof GrReturnStatement && elseBranch instanceof GrReturnStatement) {
+      final GrReturnStatement returnSt = (GrReturnStatement)GroovyPsiElementFactory.getInstance(project).createStatementFromText("return a ? b : c");
+      final GrConditionalExpression conditional = (GrConditionalExpression)returnSt.getReturnValue();
+      replaceConditional(conditional, ifStatement.getCondition(), ((GrReturnStatement)thenBranch).getReturnValue(), ((GrReturnStatement)elseBranch).getReturnValue());
+
+      ifStatement.replaceWithStatement(returnSt);
+    }
+  }
+
+  @SuppressWarnings("ConstantConditions")
+  private static void replaceConditional(GrConditionalExpression conditional,
+                                         GrExpression condition,
+                                         GrExpression then,
+                                         GrExpression elze) {
+    conditional.getCondition().replaceWithExpression(condition, true);
+    conditional.getThenBranch().replaceWithExpression(then, true);
+    conditional.getElseBranch().replaceWithExpression(elze, true);
+  }
+
+  @NotNull
+  @Override
+  protected PsiElementPredicate getElementPredicate() {
+    return new PsiElementPredicate() {
+      @Override
+      public boolean satisfiedBy(PsiElement e) {
+        if (!e.getNode().getElementType().equals(GroovyTokenTypes.kIF)) return false;
+
+        final GrIfStatement ifStatement = (GrIfStatement)e.getParent();
+        final PsiElement thenBranch = skipBlock(ifStatement.getThenBranch());
+        final PsiElement elseBranch = skipBlock(ifStatement.getElseBranch());
+
+        if (thenBranch instanceof GrAssignmentExpression &&
+            elseBranch instanceof GrAssignmentExpression &&
+            ((GrAssignmentExpression)thenBranch).getRValue() != null &&
+            ((GrAssignmentExpression)elseBranch).getRValue() != null) {
+          final GrExpression lvalue1 = ((GrAssignmentExpression)thenBranch).getLValue();
+          final GrExpression lvalue2 = ((GrAssignmentExpression)elseBranch).getLValue();
+          return EquivalenceChecker.expressionsAreEquivalent(lvalue1, lvalue2);
+        }
+
+        if (thenBranch instanceof GrReturnStatement &&
+            elseBranch instanceof GrReturnStatement &&
+            ((GrReturnStatement)thenBranch).getReturnValue() != null &&
+            ((GrReturnStatement)elseBranch).getReturnValue() != null) {
+          return true;
+        }
+
+        return false;
+      }
+    };
+  }
+
+  private static PsiElement skipBlock(PsiElement e) {
+    if (e instanceof GrBlockStatement && ((GrBlockStatement)e).getBlock().getStatements().length == 1) {
+      return ((GrBlockStatement)e).getBlock().getStatements()[0];
+    }
+    else {
+      return e;
+    }
+  }
+}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/SimplifyTernaryOperatorIntention.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/SimplifyTernaryOperatorIntention.java
index 477772a..367f5f4 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/SimplifyTernaryOperatorIntention.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/intentions/control/SimplifyTernaryOperatorIntention.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -40,7 +40,6 @@
     if (!(element instanceof GrConditionalExpression)) {
       throw new IncorrectOperationException("Not invoked on a conditional");
     }
-    GroovyPsiElementFactory groovyPsiElementFactory = GroovyPsiElementFactory.getInstance(project);
     GrConditionalExpression condExp = (GrConditionalExpression)element;
     GrExpression thenBranch = condExp.getThenBranch();
     GrExpression elseBranch = condExp.getElseBranch();
@@ -53,13 +52,7 @@
       String conditionExpText = getStringToPutIntoOrExpression(conditionExp);
       String elseExpText = getStringToPutIntoOrExpression(elseBranch);
       String newExp = conditionExpText + "||" + elseExpText;
-      int caretOffset = conditionExpText.length() + 2; // after "||"
-
-      GrExpression expressionFromText = groovyPsiElementFactory.createExpressionFromText(newExp, condExp.getContext());
-
-      expressionFromText = (GrExpression)condExp.replace(expressionFromText);
-
-      editor.getCaretModel().moveToOffset(expressionFromText.getTextOffset() + caretOffset); // just past "||"
+      manageReplace(editor, condExp, conditionExpText, newExp);
       return;
     }
 
@@ -73,14 +66,20 @@
 
 
       String newExp = conditionExpText + "&&" + thenExpText;
-      int caretOffset = conditionExpText.length() + 2; // after "&&"
-      GrExpression expressionFromText = groovyPsiElementFactory.createExpressionFromText(newExp, condExp.getContext());
-
-      expressionFromText = (GrExpression)condExp.replace(expressionFromText);
-
-      editor.getCaretModel().moveToOffset(expressionFromText.getTextOffset() + caretOffset); // just past "&&"
+      manageReplace(editor, condExp, conditionExpText, newExp);
     }
+  }
 
+  private static void manageReplace(Editor editor,
+                                    GrConditionalExpression condExp,
+                                    String conditionExpText, String newExp) {
+    int caretOffset = conditionExpText.length() + 2; // after operation sign
+
+    GrExpression expressionFromText = GroovyPsiElementFactory.getInstance(editor.getProject()).createExpressionFromText(newExp, condExp .getContext());
+
+    expressionFromText = (GrExpression)condExp.replace(expressionFromText);
+
+    editor.getCaretModel().moveToOffset(expressionFromText.getTextOffset() + caretOffset); // just past operation sign
   }
 
   /**
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/GroovyPsiElementFactory.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/GroovyPsiElementFactory.java
index 5ca9f84..33114bf 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/GroovyPsiElementFactory.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/GroovyPsiElementFactory.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -140,6 +140,8 @@
 
   public abstract GrVariableDeclaration createVariableDeclaration(@Nullable String[] modifiers, @Nullable GrExpression initializer, @Nullable PsiType type, String... identifiers);
 
+  public abstract GrVariableDeclaration createVariableDeclaration(@Nullable String[] modifiers, @Nullable String initializer, @Nullable PsiType type, String... identifiers);
+
   public abstract GrEnumConstant createEnumConstantFromText(String text);
 
   @NotNull
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/ApplicationStatementUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/ApplicationStatementUtil.java
index e6873b1..27333b9 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/ApplicationStatementUtil.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/ApplicationStatementUtil.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -18,6 +18,7 @@
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.project.Project;
 import com.intellij.psi.PsiElement;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
 import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrApplicationStatement;
@@ -95,8 +96,8 @@
     LOG.assertTrue(pList != null);
 
     final PsiElement anchor = pList.getRightParen();
-    for (PsiElement ch = list.getFirstChild(); ch != null; ch = ch.getNextSibling()) {
-      pList.addBefore(ch, anchor);
+    for (GroovyPsiElement arg : list.getAllArguments()) {
+      pList.addBefore(arg, anchor);
     }
 
     return prototype;
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrAnonymousClassType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrAnonymousClassType.java
new file mode 100644
index 0000000..e7db58c
--- /dev/null
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrAnonymousClassType.java
@@ -0,0 +1,95 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.groovy.lang.psi.impl;
+
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.pom.java.LanguageLevel;
+import com.intellij.psi.*;
+import com.intellij.psi.search.GlobalSearchScope;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrAnonymousClassDefinition;
+import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
+
+/**
+ * @author Max Medvedev
+ */
+public class GrAnonymousClassType extends GrLiteralClassType {
+  private final GrAnonymousClassDefinition myAnonymous;
+
+  public GrAnonymousClassType(@NotNull LanguageLevel languageLevel,
+                              @NotNull GlobalSearchScope scope,
+                              @NotNull JavaPsiFacade facade,
+                              @NotNull GrAnonymousClassDefinition anonymous) {
+    super(languageLevel, scope, facade);
+    myAnonymous = anonymous;
+  }
+
+  @NotNull
+  @Override
+  protected String getJavaClassName() {
+    final GrCodeReferenceElement ref = myAnonymous.getBaseClassReferenceGroovy();
+    final PsiElement resolved = ref.resolve();
+    if (resolved instanceof PsiClass) {
+      return ((PsiClass)resolved).getQualifiedName();
+    }
+    else {
+      return ref.getClassNameText();
+    }
+  }
+
+  @NotNull
+  @Override
+  public String getClassName() {
+    return StringUtil.getShortName(getJavaClassName());
+  }
+
+  @Override
+  public GrAnonymousClassDefinition resolve() {
+    return myAnonymous;
+  }
+
+  @NotNull
+  @Override
+  public PsiType[] getParameters() {
+    return myAnonymous.getBaseClassReferenceGroovy().getTypeArguments();
+  }
+
+  @NotNull
+  @Override
+  public PsiClassType setLanguageLevel(@NotNull LanguageLevel languageLevel) {
+    return new GrAnonymousClassType(languageLevel, myScope, myFacade, myAnonymous);
+  }
+
+  @Override
+  public String getInternalCanonicalText() {
+    return getCanonicalText();
+  }
+
+  @Override
+  public boolean isValid() {
+    return myAnonymous.isValid();
+  }
+
+  @Override
+  public String toString() {
+    return "AnonymousType:" + getPresentableText();
+  }
+
+  @NotNull
+  public PsiClassType getSimpleClassType() {
+    return new GrClassReferenceType(myAnonymous.getBaseClassReferenceGroovy(), myLanguageLevel);
+  }
+}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrClosureType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrClosureType.java
index 8a67dba..e821605 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrClosureType.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrClosureType.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -42,9 +42,9 @@
   private final @NotNull GrSignature mySignature;
   private PsiType[] myTypeArgs = null;
 
-  private GrClosureType(LanguageLevel languageLevel,
-                        GlobalSearchScope scope,
-                        JavaPsiFacade facade,
+  private GrClosureType(@NotNull LanguageLevel languageLevel,
+                        @NotNull GlobalSearchScope scope,
+                        @NotNull JavaPsiFacade facade,
                         @NotNull GrSignature closureSignature,
                         boolean shouldInferTypeParameters) {
     super(languageLevel, scope, facade);
@@ -116,39 +116,8 @@
     return super.equals(obj);
   }
 
-  /*public boolean isAssignableFrom(@NotNull PsiType type) {
-    if (type instanceof GrClosureType) {
-      GrClosureType other = (GrClosureType)type;
-      GrClosureSignature otherSignature = other.mySignature;
-
-      final PsiType myReturnType = mySignature.getReturnType();
-      final PsiType otherReturnType = otherSignature.getReturnType();
-      if (myReturnType == null || otherReturnType == null) {
-        return myReturnType == null && otherReturnType == null;
-      }
-
-      if (!myReturnType.isAssignableFrom(otherReturnType)) return false;
-
-      final GrClosureParameter[] myParameters = mySignature.getParameters();
-      final GrClosureParameter[] otherParameters = otherSignature.getParameters();
-
-      if (myParameters.length != otherParameters.length) return false;
-      for (int i = 0; i < myParameters.length; i++) {
-        if (myParameters[i].isOptional() != otherParameters[i].isOptional()) return false;
-        final PsiType otherParamType = otherParameters[i].getType();
-        final PsiType myParamType = myParameters[i].getType();
-        if (myParamType == null || otherParamType == null) {
-          if (myParamType != null || otherParamType != null) return false;
-        }
-        else if (!otherParamType.isAssignableFrom(myParamType)) return false;
-      }
-      return true;
-    }
-    return super.isAssignableFrom(type);
-  }*/
-
   public boolean equalsToText(@NonNls String text) {
-    return text.equals(GroovyCommonClassNames.GROOVY_LANG_CLOSURE);
+    return text != null && text.equals(GroovyCommonClassNames.GROOVY_LANG_CLOSURE);
   }
 
   @NotNull
@@ -208,7 +177,7 @@
   }
 
   @Nullable
-  public PsiType curry(PsiType[] args, int position, GroovyPsiElement context) {
+  public PsiType curry(@NotNull PsiType[] args, int position, @NotNull GroovyPsiElement context) {
     final GrSignature newSignature = mySignature.curry(args, position, context);
     if (newSignature == null) return null;
     final GrClosureType result = create(newSignature, myScope, myFacade, myLanguageLevel, true);
@@ -220,13 +189,4 @@
   public GrSignature getSignature() {
     return mySignature;
   }
-
-  /*public PsiType[] getClosureParameterTypes() {
-    final GrClosureParameter[] parameters = mySignature.getParameters();
-    final PsiType[] types = new PsiType[parameters.length];
-    for (int i = 0; i < types.length; i++) {
-      types[i] = parameters[i].getType();
-    }
-    return types;
-  }*/
 }
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java
index 80a0c18..55c8d34 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.groovy.lang.psi.impl;
 
 import com.intellij.openapi.util.text.StringUtil;
@@ -18,7 +33,7 @@
   protected final JavaPsiFacade myFacade;
   private final GroovyPsiManager myGroovyPsiManager;
 
-  public GrLiteralClassType(LanguageLevel languageLevel, GlobalSearchScope scope, JavaPsiFacade facade) {
+  public GrLiteralClassType(@NotNull LanguageLevel languageLevel, @NotNull GlobalSearchScope scope, @NotNull JavaPsiFacade facade) {
     super(languageLevel);
     myScope = scope;
     myFacade = facade;
@@ -117,6 +132,7 @@
     return myLanguageLevel;
   }
 
+  @NotNull
   public GlobalSearchScope getScope() {
     return myScope;
   }
@@ -132,7 +148,7 @@
   }
 
   public boolean equalsToText(@NonNls String text) {
-    return text.equals(getJavaClassName());
+    return text != null && text.equals(getJavaClassName());
   }
 
   @NotNull
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiElementFactoryImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiElementFactoryImpl.java
index 8ad0240..71624fe2 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiElementFactoryImpl.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyPsiElementFactoryImpl.java
@@ -216,6 +216,28 @@
                                                          @Nullable GrExpression initializer,
                                                          @Nullable PsiType type,
                                                          String... identifiers) {
+
+    String initializerText;
+    if (initializer != null) {
+      if (initializer instanceof GrApplicationStatement &&
+          !GroovyConfigUtils.getInstance().isVersionAtLeast(initializer, GroovyConfigUtils.GROOVY1_8, false)) {
+        initializer = createMethodCallByAppCall((GrApplicationStatement)initializer);
+      }
+      assert initializer != null;
+      initializerText = initializer.getText();
+    }
+    else {
+      initializerText = null;
+    }
+
+    return createVariableDeclaration(modifiers, initializerText, type, identifiers);
+  }
+
+  @Override
+  public GrVariableDeclaration createVariableDeclaration(@Nullable String[] modifiers,
+                                                         @Nullable String initializer,
+                                                         @Nullable PsiType type,
+                                                         String... identifiers) {
     StringBuilder text = writeModifiers(modifiers);
 
     if (type != null && type != PsiType.NULL) {
@@ -239,13 +261,8 @@
       text.append(')');
     }
 
-    if (initializer != null) {
-      if (initializer instanceof GrApplicationStatement &&
-          !GroovyConfigUtils.getInstance().isVersionAtLeast(initializer, GroovyConfigUtils.GROOVY1_8, false)) {
-        initializer = createMethodCallByAppCall((GrApplicationStatement)initializer);
-      }
-      assert initializer != null;
-      text.append(" = ").append(initializer.getText());
+    if (!StringUtil.isEmptyOrSpaces(initializer)) {
+      text.append(" = ").append(initializer);
     }
 
     GrTopStatement[] topStatements = createGroovyFileChecked(text).getTopStatements();
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrNewExpressionImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrNewExpressionImpl.java
index 344d93d..c3573ad 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrNewExpressionImpl.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrNewExpressionImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -18,6 +18,7 @@
 
 import com.intellij.lang.ASTNode;
 import com.intellij.openapi.util.TextRange;
+import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.*;
 import com.intellij.psi.util.InheritanceUtil;
 import com.intellij.util.Function;
@@ -40,7 +41,10 @@
 import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeArgumentList;
 import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeElement;
 import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper;
-import org.jetbrains.plugins.groovy.lang.psi.impl.*;
+import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnonymousClassType;
+import org.jetbrains.plugins.groovy.lang.psi.impl.GrClassReferenceType;
+import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType;
+import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil;
 import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.path.GrCallExpressionImpl;
 import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
 import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil;
@@ -58,7 +62,8 @@
     public PsiType fun(GrNewExpressionImpl newExpression) {
       final GrAnonymousClassDefinition anonymous = newExpression.getAnonymousClassDefinition();
       if (anonymous != null) {
-        return anonymous.getBaseClassType();
+        return new GrAnonymousClassType(LanguageLevel.JDK_1_5, anonymous.getResolveScope(),
+                                        JavaPsiFacade.getInstance(newExpression.getProject()), anonymous);
       }
       PsiType type = null;
       GrCodeReferenceElement refElement = newExpression.getReferenceElement();
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceResolveUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceResolveUtil.java
index 64ce272..44e3990 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceResolveUtil.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceResolveUtil.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -190,7 +190,13 @@
       return true;
     }
 
-    if (qualifierType instanceof PsiClassType) {
+    /*if (qualifierType instanceof GrAnonymousClassType) {
+      final GrAnonymousClassDefinition anonymous = ((GrAnonymousClassType)qualifierType).getAnonymous();
+      if (!anonymous.processDeclarations(processor, state, null, place)) {
+        return false;
+      }
+    }
+    else */if (qualifierType instanceof PsiClassType) {
       PsiClassType.ClassResolveResult qualifierResult = ((PsiClassType)qualifierType).resolveGenerics();
       PsiClass qualifierClass = qualifierResult.getElement();
       if (qualifierClass != null) {
@@ -200,17 +206,16 @@
       }
     }
     else if (qualifierType instanceof PsiArrayType) {
-      final GrTypeDefinition arrayClass =
-        GroovyPsiManager.getInstance(place.getProject()).getArrayClass(((PsiArrayType)qualifierType).getComponentType());
-      if (!arrayClass.processDeclarations(processor, state, null, place)) return false;
+      final GroovyPsiManager gmanager = GroovyPsiManager.getInstance(place.getProject());
+      final GrTypeDefinition arrayClass = gmanager.getArrayClass(((PsiArrayType)qualifierType).getComponentType());
+      if (arrayClass != null && !arrayClass.processDeclarations(processor, state, null, place)) return false;
     }
 
     if (!(place.getParent() instanceof GrMethodCall) && InheritanceUtil.isInheritor(qualifierType, CommonClassNames.JAVA_UTIL_COLLECTION)) {
       final PsiType componentType = ClosureParameterEnhancer.findTypeForIteration(qualifierType, place);
       if (componentType != null) {
         final SpreadState spreadState = state.get(SpreadState.SPREAD_STATE);
-        processQualifierType(processor, componentType, state.put(SpreadState.SPREAD_STATE, SpreadState.create(qualifierType, spreadState)),
-                             place);
+        processQualifierType(processor, componentType, state.put(SpreadState.SPREAD_STATE, SpreadState.create(qualifierType, spreadState)), place);
       }
     }
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcRunTargetDialog.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcRunTargetDialog.java
index 0b49605..9687048 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcRunTargetDialog.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcRunTargetDialog.java
@@ -26,7 +26,6 @@
 import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.ui.*;
-import com.intellij.util.ArrayUtil;
 import com.intellij.util.TextFieldCompletionProvider;
 import com.intellij.util.TextFieldCompletionProviderDumbAware;
 import org.jetbrains.annotations.NotNull;
@@ -82,7 +81,7 @@
     }
 
     if (hasOneSupportedModule) {
-      myInteractiveRunAction = new DialogWrapperAction("&Run Interactive Console") {
+      myInteractiveRunAction = new DialogWrapperAction("&Start Grails Console in Interactive Mode") {
         @Override
         protected void doAction(ActionEvent e) {
           myFramework.runInteractiveConsole(getSelectedModule());
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ExpressionGenerator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ExpressionGenerator.java
index 0cbb19d..7ee9475 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ExpressionGenerator.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/ExpressionGenerator.java
@@ -316,7 +316,7 @@
     StringBuilder builder = new StringBuilder();
     final PsiMethod setter = GroovyPropertyUtils.findPropertySetter(resolved, fieldName, false, true);
     if (setter != null) {
-      final GrVariableDeclaration var = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, null, type, varName);
+      final GrVariableDeclaration var = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, "", type, varName);
       final GrReferenceExpression caller = factory.createReferenceExpressionFromText(varName, var);
       invokeMethodOn(setter, caller, new GrExpression[]{expression}, GrNamedArgument.EMPTY_ARRAY, EMPTY_ARRAY, substitutor,
                      expression);
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/TypeWriter.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/TypeWriter.java
index 78488fc..4f0aade 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/TypeWriter.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/convertToJava/TypeWriter.java
@@ -19,6 +19,7 @@
 import com.intellij.psi.util.TypeConversionUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.groovy.lang.psi.impl.GrAnonymousClassType;
 import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
 
 /**
@@ -62,6 +63,10 @@
       return;
     }
 
+    if (type instanceof GrAnonymousClassType) {
+      type = ((GrAnonymousClassType)type).getSimpleClassType();
+    }
+
     final boolean acceptEllipsis = isLastParameter(context);
 
     type.accept(new TypeWriter(builder, classNameProvider, acceptEllipsis, context));
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/ExtractUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/ExtractUtil.java
index f674520..41c8e1b 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/ExtractUtil.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/extract/ExtractUtil.java
@@ -179,7 +179,7 @@
 
     if (distinctDeclaration) {
       for (VariableInfo info : varInfos) {
-        result.add(factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, null, info.getType(), info.getName()));
+        result.add(factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, "", info.getType(), info.getName()));
       }
     }
     else {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java
index 95178e7..c25d9a4 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyMethodInliner.java
@@ -255,7 +255,7 @@
       // Process method return statements
       if (returnCount > 1 && PsiType.VOID != methodType && !isTailMethodCall) {
         PsiType type = methodType != null && methodType.equalsToText(CommonClassNames.JAVA_LANG_OBJECT) ? null : methodType;
-        GrVariableDeclaration resultDecl = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, null, type, resultName);
+        GrVariableDeclaration resultDecl = factory.createVariableDeclaration(ArrayUtil.EMPTY_STRING_ARRAY, "", type, resultName);
         GrStatement statement = ((GrStatementOwner) owner).addStatementBefore(resultDecl, anchor);
         GrReferenceAdjuster.shortenReferences(statement);
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/variable/GrIntroduceVariableHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/variable/GrIntroduceVariableHandler.java
index dd3695d..5bff481 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/variable/GrIntroduceVariableHandler.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/variable/GrIntroduceVariableHandler.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -25,6 +25,7 @@
 import com.intellij.util.IncorrectOperationException;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.groovy.lang.GrReferenceAdjuster;
 import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase;
 import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
 import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
@@ -120,10 +121,9 @@
     // Generating variable declaration
 
     final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.getProject());
-    final GrVariableDeclaration varDecl = factory
-      .createVariableDeclaration(settings.isDeclareFinal() ? new String[]{PsiModifier.FINAL} : null,
-                                 (GrExpression)PsiUtil.skipParentheses(context.getExpression(), false), settings.getSelectedType(),
-                                 settings.getName());
+    final String[] modifiers = settings.isDeclareFinal() ? new String[]{PsiModifier.FINAL} : null;
+    final GrVariableDeclaration varDecl = factory.createVariableDeclaration(modifiers, "foo", settings.getSelectedType(), settings.getName());
+    varDecl.getVariables()[0].getInitializerGroovy().replaceWithExpression(context.getExpression(), true);
 
     // Marker for caret position
     try {
@@ -152,6 +152,8 @@
         insertedVar = insertVariableDefinition(context, settings, varDecl);
       }
 
+      GrReferenceAdjuster.shortenReferences(insertedVar);
+
       insertedVar.setType(settings.getSelectedType());
 
       //Replace other occurrences
@@ -260,16 +262,13 @@
     if (realContainer instanceof GrLoopStatement || realContainer instanceof GrIfStatement) {
       boolean isThenBranch = realContainer instanceof GrIfStatement && anchorElement.equals(((GrIfStatement)realContainer).getThenBranch());
 
-      // To replace branch body correctly
-      String refId = varDecl.getVariables()[0].getName();
-
       GrBlockStatement newBody;
       final GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(context.getProject());
       if (context.getExpression().equals(PsiUtil.skipParentheses(anchorElement, false))) {
         newBody = factory.createBlockStatement(varDecl);
       }
       else {
-        replaceExpressionOccurrencesInStatement(anchorElement, context.getExpression(), refId, settings.replaceAllOccurrences());
+        replaceExpressionOccurrencesInStatement(anchorElement, context.getExpression(), settings.getName(), settings.replaceAllOccurrences());
         newBody = factory.createBlockStatement(varDecl, anchorElement);
       }
 
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/GrCommentTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/GrCommentTest.groovy
new file mode 100644
index 0000000..af16cc4
--- /dev/null
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/GrCommentTest.groovy
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.groovy
+
+import com.intellij.codeInsight.actions.CodeInsightAction
+import com.intellij.codeInsight.generation.actions.CommentByBlockCommentAction
+import com.intellij.codeInsight.generation.actions.CommentByLineCommentAction
+import com.intellij.ide.DataManager
+import com.intellij.openapi.actionSystem.ActionManager
+import com.intellij.openapi.actionSystem.AnActionEvent
+import com.intellij.openapi.actionSystem.DataContext
+import org.jetbrains.annotations.NotNull
+import org.jetbrains.plugins.groovy.util.TestUtils
+
+/**
+ * @author Max Medvedev
+ */
+class GrCommentTest extends LightGroovyTestCase {
+  @Override
+  protected String getBasePath() {
+    TestUtils.testDataPath + 'grComment/'
+  }
+
+  void testLine() {
+    lineTest('''\
+<caret>print 2
+''', '''\
+//print 2
+<caret>''')
+  }
+
+
+  void testUncommentLine() {
+    lineTest('''\
+//<caret>print 2
+''', '''\
+print 2
+<caret>''')
+  }
+
+
+  void testBlock0() {
+    blockTest('''\
+<selection>print 2</selection>
+''', '''\
+<selection>/*print 2*/</selection>
+''')
+  }
+
+  void testUncommentBlock0() {
+    blockTest('''\
+<selection>/*print 2*/</selection>
+''', '''\
+<selection>print 2</selection>
+''')
+  }
+
+  void testBlock1() {
+    blockTest('''\
+<selection>print 2
+</selection>
+''', '''\
+<selection>/*
+print 2
+*/
+</selection>
+''')
+  }
+
+  void testUncommentBlock1() {
+    blockTest('''\
+<selection>/*
+print 2
+*/
+</selection>
+''', '''\
+<selection>print 2
+</selection>
+''')
+  }
+
+  void lineTest(String before, String after) {
+    doTest(before, after, new CommentByLineCommentAction())
+  }
+
+  void blockTest(String before, String after) {
+    doTest(before, after, new CommentByBlockCommentAction())
+  }
+
+  private void doTest(@NotNull String before, @NotNull String after, final CodeInsightAction action) {
+    myFixture.configureByText(GroovyFileType.GROOVY_FILE_TYPE, before)
+    final DataContext dataContext = DataManager.instance.dataContextFromFocus.result
+    action.actionPerformed(new AnActionEvent(null, dataContext, "", action.templatePresentation, ActionManager.instance, 0));
+    myFixture.checkResult(after)
+  }
+}
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/FlipIfTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/FlipIfTest.groovy
new file mode 100644
index 0000000..2e7238e
--- /dev/null
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/FlipIfTest.groovy
@@ -0,0 +1,68 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.groovy.intentions
+
+/**
+ * @author Max Medvedev
+ */
+class FlipIfTest extends GrIntentionTestCase {
+  FlipIfTest() {
+    super(GroovyIntentionsBundle.message('flip.if.intention.name'))
+  }
+
+  void test0() {
+    doTextTest('''\
+i<caret>f (abc) {
+  print 1
+}
+else if (cde) {
+  print 2
+}
+''', '''\
+i<caret>f (cde) {
+  print 2
+}
+else if (abc) {
+  print 1
+}
+''')
+  }
+
+  void test1() {
+    doTextTest('''\
+if (abc) {
+  print 1
+}
+else i<caret>f (cde) {
+  print 2
+}
+else if (xyz) {
+  print 3
+}
+''', '''\
+if (abc) {
+  print 1
+}
+else i<caret>f (xyz) {
+  print 3
+}
+else if (cde) {
+  print 2
+}
+''')
+  }
+
+}
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/ReplaceifWithTernaryTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/ReplaceifWithTernaryTest.groovy
new file mode 100644
index 0000000..034db1e
--- /dev/null
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/intentions/ReplaceifWithTernaryTest.groovy
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.groovy.intentions
+
+/**
+ * @author Max Medvedev
+ */
+class ReplaceIfWithTernaryTest extends GrIntentionTestCase {
+  ReplaceIfWithTernaryTest() {
+    super('Replace with ?:')
+  }
+
+  public void testReturn() throws Exception {
+    doTextTest('''\
+def foo() {
+    i<caret>f (cond()) {
+        return 'a'
+    }
+    else return 'b'
+}
+''', '''\
+def foo() {
+    return cond() ? 'a' : 'b'
+}
+''')
+  }
+
+  public void testAssign() throws Exception {
+    doTextTest('''\
+def a
+
+i<caret>f (cond()) {
+    a = 'a'
+}
+else {
+    a = 'b'
+}
+''', '''\
+def a
+
+a = cond() ? 'a' : 'b'
+''')
+  }
+
+  public void testAntiAssign() throws Exception {
+    doAntiTest('''\
+def a
+def b
+
+i<caret>f (cond) {
+    a = 'a'
+}
+else {
+    b = 'b'
+}
+''')
+  }
+
+}
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/MissingReturnTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/MissingReturnTest.groovy
index 67bf5fe..f841bc9 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/MissingReturnTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/MissingReturnTest.groovy
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2013 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 org.jetbrains.plugins.groovy.lang;
 
 
@@ -35,6 +50,23 @@
   public void testFinally() {doTest();}
   public void testClosureWithExplicitExpectedType() {doTest()}
 
+  public void testAssert() {
+    doTextText('''\
+Integer.with {
+  assert valueof('1') == 1
+}                         //no error
+
+Integer.with {
+  if (foo) {
+    return 2
+  }
+  else {
+    print 1
+  }
+<warning descr="Not all execution paths return a value">}</warning>
+''')
+  }
+
 
   public void testInterruptFlowInElseBranch() {
     doTextText('''\
@@ -137,6 +169,47 @@
 ''')
   }
 
+  void testReturnWithoutValue0() {
+    doTextText('''\
+int foo() {
+  if (abc) {
+    return
+  }
+
+  return 2
+<warning>}</warning>
+''')
+  }
+
+  void testReturnWithoutValue1() {
+    doTextText('''\
+int foo() {
+  return
+<warning>}</warning>
+''')
+  }
+
+  void testReturnWithoutValue2() {
+    doTextText('''\
+void foo() {
+  if (abc) {
+    return
+  }
+
+  print 2
+} //no error
+''')
+  }
+
+  void testReturnWithoutValue3() {
+    doTextText('''\
+void foo() {
+  return
+} //no error
+''')
+  }
+
+
   void doTextText(String text) {
     myFixture.configureByText('___.groovy', text)
     myFixture.enableInspections(MissingReturnInspection)
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/formatter/FormatterTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/formatter/FormatterTest.groovy
index 2f620c0..c398fba 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/formatter/FormatterTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/formatter/FormatterTest.groovy
@@ -274,6 +274,7 @@
 ''', '''\
 class A {
 }
+
 class B {
 }
 ''')
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy
index 70a3b26..8a38730 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy
@@ -1333,4 +1333,33 @@
 ''')
   }
 
+  void testEnumConstantAsAnnotationAttribute() {
+    testHighlighting('''\
+enum A {CONST}
+
+@interface I {
+    A foo()
+}
+
+@I(foo = A.CONST) //no error
+def bar
+''')
+  }
+
+  void testUnassignedFieldAsAnnotationAttribute() {
+    testHighlighting('''\
+interface A {
+  String CONST
+}
+
+@interface I {
+    String foo()
+}
+
+@I(foo = <error descr="Expected 'A.CONST' to be an inline constant">A.CONST</error>)
+def bar
+''')
+  }
+
+
 }
\ No newline at end of file
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolveMethodTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolveMethodTest.groovy
index 3106e8c..a3eb757 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolveMethodTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/resolve/ResolveMethodTest.groovy
@@ -1564,4 +1564,15 @@
     assertInstanceOf(method, GrMethodImpl)
   }
 
+  void testResoleAnonymousMethod() {
+    resolveByText('''\
+def anon = new Object() {
+  def foo() {
+    print 2
+  }
+}
+
+anon.fo<caret>o()
+''', GrMethod)
+  }
 }
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/introduceVariable/IntroduceVariableTest.java b/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/introduceVariable/IntroduceVariableTest.groovy
similarity index 85%
rename from plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/introduceVariable/IntroduceVariableTest.java
rename to plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/introduceVariable/IntroduceVariableTest.groovy
index 1574ebf..2c66c5f 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/introduceVariable/IntroduceVariableTest.java
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/introduceVariable/IntroduceVariableTest.groovy
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -14,30 +14,27 @@
  * limitations under the License.
  */
 
-package org.jetbrains.plugins.groovy.refactoring.introduceVariable;
+package org.jetbrains.plugins.groovy.refactoring.introduceVariable
 
-import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.editor.Editor;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiType;
-import com.intellij.psi.impl.source.PostprocessReformattingAspect;
-import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.groovy.GroovyFileType;
-import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase;
-import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
-import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
-import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
-import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil;
-import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceContext;
-import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceContextImpl;
-import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceHandlerBase;
-import org.jetbrains.plugins.groovy.refactoring.introduce.variable.GrIntroduceVariableHandler;
-import org.jetbrains.plugins.groovy.refactoring.introduce.variable.GroovyIntroduceVariableSettings;
-import org.jetbrains.plugins.groovy.util.TestUtils;
-
-import java.util.List;
-
+import com.intellij.openapi.application.ApplicationManager
+import com.intellij.openapi.editor.Editor
+import com.intellij.psi.PsiElement
+import com.intellij.psi.PsiType
+import com.intellij.psi.impl.source.PostprocessReformattingAspect
+import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
+import org.jetbrains.annotations.Nullable
+import org.jetbrains.plugins.groovy.GroovyFileType
+import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
+import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
+import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
+import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil
+import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceContext
+import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceContextImpl
+import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceHandlerBase
+import org.jetbrains.plugins.groovy.refactoring.introduce.variable.GrIntroduceVariableHandler
+import org.jetbrains.plugins.groovy.refactoring.introduce.variable.GroovyIntroduceVariableSettings
+import org.jetbrains.plugins.groovy.util.TestUtils
 /**
  * @author ilyas
  */
@@ -45,7 +42,7 @@
 
   @Override
   protected String getBasePath() {
-    return TestUtils.getTestDataPath() + "groovy/refactoring/introduceVariable/";
+    return TestUtils.testDataPath + "groovy/refactoring/introduceVariable/";
   }
 
   public void testAbs() throws Throwable { doTest(); }
@@ -80,6 +77,18 @@
   
   public void testCallableProperty() {doTest();}
 
+  void testFqn() {
+    myFixture.addClass('''\
+package p;
+public class Foo {
+    public static int foo() {
+        return 1;
+    }
+}
+''')
+    doTest()
+  }
+
   protected static final String ALL_MARKER = "<all>";
 
   protected boolean replaceAllOccurences = false;
@@ -146,7 +155,7 @@
 
           @Override
           public boolean replaceAllOccurrences() {
-            return replaceAllOccurences;
+            return IntroduceVariableTest.this.replaceAllOccurences;
           }
         });
         PostprocessReformattingAspect.getInstance(getProject()).doPostponedFormatting();
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/optimizeImports/OptimizeImportsTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/optimizeImports/OptimizeImportsTest.groovy
index b3d5697..e38546f 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/optimizeImports/OptimizeImportsTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/optimizeImports/OptimizeImportsTest.groovy
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 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.
@@ -253,7 +253,7 @@
 
 import foo.Foo
 import foo.Bar
-import java.test.Test 
+import java.test.Test
 import java.test2.Test2
 import static foo.Bar.foo0
 import static java.test.Test.foo
diff --git a/plugins/groovy/testdata/groovy/refactoring/inlineLocal/varInGString4.test b/plugins/groovy/testdata/groovy/refactoring/inlineLocal/varInGString4.test
index 06b851a..a83125a 100644
--- a/plugins/groovy/testdata/groovy/refactoring/inlineLocal/varInGString4.test
+++ b/plugins/groovy/testdata/groovy/refactoring/inlineLocal/varInGString4.test
@@ -8,4 +8,5 @@
 class X {
     def getFoo(){2}
 }
+
 print "foo ${new X().foo} x"
\ No newline at end of file
diff --git a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos1.test b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos1.test
index e68e03a..b780c9e 100644
--- a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos1.test
+++ b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos1.test
@@ -1,4 +1,4 @@
 foo(1, 2, 3) <begin>{x->x}<end>
 -----
-def preved = { x -> x }
+def preved = {x->x}
 foo(1, 2, 3, preved<caret>)
\ No newline at end of file
diff --git a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos2.test b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos2.test
index 4fa1f21..a7ab0fe 100644
--- a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos2.test
+++ b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos2.test
@@ -1,4 +1,4 @@
 foo(1, 2, 3) {x -> x} {x -> y} <all>{x->x}<end> {x -> z}
 -----
-def preved = { x -> x }
+def preved = {x->x}
 foo(1, 2, 3, preved, { x -> y }, preved<caret>) {x -> z}
\ No newline at end of file
diff --git a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos3.test b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos3.test
index 45d7ba3..abf74ce 100644
--- a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos3.test
+++ b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos3.test
@@ -1,4 +1,4 @@
 foo(1, 2, 3) {x -> x} {x -> y} <begin>{x->x}<end> {x -> z}
 -----
-def preved = { x -> x }
+def preved = {x->x}
 foo(1, 2, 3, { x -> x }, { x -> y }, preved<caret>) {x -> z}
\ No newline at end of file
diff --git a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos4.test b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos4.test
index ad2e141..99ecad3 100644
--- a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos4.test
+++ b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/clos4.test
@@ -2,6 +2,6 @@
 foo {x->x} {x->x} {x->x} (3) {x->x}
 
 -----
-def preved = { x -> x }<caret>
+def preved = {x->x}<caret>
 foo(preved, preved, preved)(3, preved)
 
diff --git a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/fqn.test b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/fqn.test
new file mode 100644
index 0000000..7bbe8d0
--- /dev/null
+++ b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/fqn.test
@@ -0,0 +1,7 @@
+import p.Foo
+
+<begin>Foo.foo()<end>
+-----
+import p.Foo
+
+def preved = Foo.foo()<caret>
\ No newline at end of file
diff --git a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/if2.test b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/if2.test
index 7fd0de7..7d206eb 100644
--- a/plugins/groovy/testdata/groovy/refactoring/introduceVariable/if2.test
+++ b/plugins/groovy/testdata/groovy/refactoring/introduceVariable/if2.test
@@ -1,5 +1,5 @@
 <all>{x->x}<end>
 if (true) ({x->x})
 -----
-def preved = { x -> x }<caret>
+def preved = {x->x}<caret>
 if (true) preved
\ No newline at end of file
diff --git a/plugins/groovy/testdata/optimizeImports/Commented_after.groovy b/plugins/groovy/testdata/optimizeImports/Commented_after.groovy
index 29d323e..70fba0b 100644
--- a/plugins/groovy/testdata/optimizeImports/Commented_after.groovy
+++ b/plugins/groovy/testdata/optimizeImports/Commented_after.groovy
@@ -1,5 +1,4 @@
 import javax.swing.*
-
 // preved!
 
 def frame = new JFrame()
\ No newline at end of file
diff --git a/plugins/groovy/testdata/refactoring/move/moveMembers/doc/after/test.groovy b/plugins/groovy/testdata/refactoring/move/moveMembers/doc/after/test.groovy
index 416d599..7f78c18 100644
--- a/plugins/groovy/testdata/refactoring/move/moveMembers/doc/after/test.groovy
+++ b/plugins/groovy/testdata/refactoring/move/moveMembers/doc/after/test.groovy
@@ -1,4 +1,6 @@
 class A {
+
+
 }
 
 class B {
diff --git a/plugins/groovy/testdata/refactoring/move/moveMembers/fieldForwardRef/after/A.groovy b/plugins/groovy/testdata/refactoring/move/moveMembers/fieldForwardRef/after/A.groovy
index f7e8cc3..eb61624 100644
--- a/plugins/groovy/testdata/refactoring/move/moveMembers/fieldForwardRef/after/A.groovy
+++ b/plugins/groovy/testdata/refactoring/move/moveMembers/fieldForwardRef/after/A.groovy
@@ -1,2 +1,3 @@
 public class A {
+
 }
diff --git a/plugins/groovy/testdata/refactoring/move/moveMembers/scr40947/after/Test.groovy b/plugins/groovy/testdata/refactoring/move/moveMembers/scr40947/after/Test.groovy
index d5038e8..f93d832 100644
--- a/plugins/groovy/testdata/refactoring/move/moveMembers/scr40947/after/Test.groovy
+++ b/plugins/groovy/testdata/refactoring/move/moveMembers/scr40947/after/Test.groovy
@@ -1,4 +1,5 @@
 class A {
+
 }
 
 class Test {
diff --git a/plugins/groovy/testdata/refactoring/move/moveMembers/twoMethods/after/pack1/A.groovy b/plugins/groovy/testdata/refactoring/move/moveMembers/twoMethods/after/pack1/A.groovy
index 46fc78f..4564065 100644
--- a/plugins/groovy/testdata/refactoring/move/moveMembers/twoMethods/after/pack1/A.groovy
+++ b/plugins/groovy/testdata/refactoring/move/moveMembers/twoMethods/after/pack1/A.groovy
@@ -1,4 +1,6 @@
 package pack1;
 
 public class A {
+
+
 }
\ No newline at end of file
diff --git a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java
index e4e8813..be6c500 100644
--- a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java
+++ b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java
@@ -251,7 +251,14 @@
       if (!StringUtil.isEmptyOrSpaces(message)) {
         registerJavaFxPackagerError(message);
       }
-      return process.waitFor();
+      final int result = process.waitFor();
+      if (result != 0) {
+        final String explanationMessage = new String(FileUtil.loadBytes(process.getInputStream()));
+        if (!StringUtil.isEmptyOrSpaces(explanationMessage)) {
+          registerJavaFxPackagerError(explanationMessage);
+        }
+      }
+      return result;
     }
     catch (Exception e) {
       registerJavaFxPackagerError(e);
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenImportingSettingsForm.form b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenImportingSettingsForm.form
index 7865dd6..48408f7 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenImportingSettingsForm.form
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenImportingSettingsForm.form
@@ -3,7 +3,7 @@
   <grid id="27dc6" binding="myPanel" layout-manager="GridLayoutManager" row-count="17" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
     <margin top="0" left="0" bottom="0" right="0"/>
     <constraints>
-      <xy x="20" y="20" width="522" height="565"/>
+      <xy x="20" y="20" width="536" height="565"/>
     </constraints>
     <properties/>
     <border type="none"/>
@@ -13,7 +13,7 @@
           <grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
         </constraints>
         <properties>
-          <text value="Create IDEA &amp;modules for aggregator projects (with 'pom' packaging)"/>
+          <text value="Create $FULLNAME$ &amp;modules for aggregator projects (with 'pom' packaging)"/>
         </properties>
       </component>
       <component id="2b9b5" class="javax.swing.JCheckBox" binding="myCreateGroupsCheckBox" default-binding="true">
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenImportingSettingsForm.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenImportingSettingsForm.java
index 24af3f0..da4dc0a 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenImportingSettingsForm.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenImportingSettingsForm.java
@@ -15,6 +15,7 @@
  */
 package org.jetbrains.idea.maven.project;
 
+import com.intellij.openapi.updateSettings.impl.LabelTextReplacingUtil;
 import com.intellij.ui.ListCellRendererWrapper;
 import com.intellij.ide.util.projectWizard.WizardContext;
 import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
@@ -80,6 +81,8 @@
         }
       }
     });
+
+    LabelTextReplacingUtil.replaceText(myPanel);
   }
 
   private void createUIComponents() {
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentProjectFileProcessor.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentProjectFileProcessor.java
index 205a7de..8c091a5 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentProjectFileProcessor.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenParentProjectFileProcessor.java
@@ -15,7 +15,6 @@
  */
 package org.jetbrains.idea.maven.project;
 
-import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VirtualFile;
 import org.jetbrains.annotations.NotNull;
@@ -32,7 +31,7 @@
                              @NotNull VirtualFile projectFile,
                              @Nullable MavenParentDesc parentDesc) {
     VirtualFile superPom = generalSettings.getEffectiveSuperPom();
-    if (Comparing.equal(projectFile, superPom)) return null;
+    if (projectFile.equals(superPom)) return null;
 
     RESULT_TYPE result = null;
 
diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ReimportingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ReimportingTest.java
index 44d5f0d..7ae1ec7 100644
--- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ReimportingTest.java
+++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/importing/ReimportingTest.java
@@ -224,10 +224,10 @@
     configConfirmationForYesAnswer(); // will ask about absent modules
 
     importProjectWithProfiles("profile1");
-    assertModules("project", "m1", "m2");
+    assertModules("project", "m1");
 
     importProjectWithProfiles("profile2");
-    assertModules("project", "m1", "m2");
+    assertModules("project", "m2");
   }
 
   public void testChangingDependencyTypeToTestJar() throws Exception {
diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java
index 2f118ed2..46d5a78 100644
--- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java
+++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/project/MavenProjectsTreeReadingTest.java
@@ -429,7 +429,7 @@
     l.log = "";
   }
 
-  public void _testUpdatingModelWithNewProfiles() throws Exception {
+  public void testUpdatingModelWithNewProfiles() throws Exception {
     createProjectPom("<groupId>test</groupId>" +
                      "<artifactId>project</artifactId>" +
                      "<version>1</version>" +
@@ -466,9 +466,17 @@
     assertEquals(1, roots.size());
     assertEquals(myProjectPom, roots.get(0).getFile());
 
-    assertEquals(2, myTree.getModules(roots.get(0)).size());
+    assertEquals(1, myTree.getModules(roots.get(0)).size());
     assertEquals(m1, myTree.getModules(roots.get(0)).get(0).getFile());
-    assertEquals(m2, myTree.getModules(roots.get(0)).get(1).getFile());
+
+    updateAll(Collections.singletonList("two"), myProjectPom);
+
+    roots = myTree.getRootProjects();
+    assertEquals(1, roots.size());
+    assertEquals(myProjectPom, roots.get(0).getFile());
+
+    assertEquals(1, myTree.getModules(roots.get(0)).size());
+    assertEquals(m2, myTree.getModules(roots.get(0)).get(0).getFile());
   }
 
   public void testUpdatingParticularProject() throws Exception {
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java
index cc5fa08..96411c3 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/DesignerEditorPanel.java
@@ -155,163 +155,20 @@
   private void createDesignerCard() {
     myLayeredPane = new MyLayeredPane();
 
-    mySurfaceArea = new ComponentEditableArea(myLayeredPane) {
-      @Override
-      protected void fireSelectionChanged() {
-        super.fireSelectionChanged();
-        myLayeredPane.revalidate();
-        myLayeredPane.repaint();
-      }
+    mySurfaceArea = createEditableArea();
 
-      @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;
-      }
-    };
-
-    myToolProvider = new ToolProvider() {
-      @Override
-      public void loadDefaultTool() {
-        setActiveTool(createDefaultTool());
-      }
-
-      @Override
-      public void setActiveTool(InputTool tool) {
-        if (getActiveTool() instanceof CreationTool && !(tool instanceof CreationTool)) {
-          PaletteToolWindowManager.getInstance(getProject()).clearActiveItem();
-        }
-        if (!(tool instanceof SelectionTool)) {
-          hideInspections();
-        }
-        super.setActiveTool(tool);
-      }
-
-      @Override
-      public boolean execute(final ThrowableRunnable<Exception> operation, String command, final boolean updateProperties) {
-        final boolean[] is = {true};
-        CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
-          public void run() {
-            is[0] = DesignerEditorPanel.this.execute(operation, updateProperties);
-          }
-        }, command, null);
-        return is[0];
-      }
-
-      @Override
-      public void executeWithReparse(final ThrowableRunnable<Exception> operation, String 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) {
-        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();
-      }
-    };
+    myToolProvider = createToolProvider();
 
     myGlassLayer = new GlassLayer(myToolProvider, mySurfaceArea);
     myLayeredPane.add(myGlassLayer, LAYER_GLASS);
 
-    myDecorationLayer = new DecorationLayer(this, mySurfaceArea);
+    myDecorationLayer = createDecorationLayer();
     myLayeredPane.add(myDecorationLayer, LAYER_DECORATION);
 
-    myFeedbackLayer = new FeedbackLayer();
+    myFeedbackLayer = createFeedbackLayer();
     myLayeredPane.add(myFeedbackLayer, LAYER_FEEDBACK);
 
-    myInplaceEditingLayer = new InplaceEditingLayer(this);
+    myInplaceEditingLayer = createInplaceEditingLayer();
     myLayeredPane.add(myInplaceEditingLayer, LAYER_INPLACE_EDITING);
 
     JPanel content = new JPanel(new GridBagLayout());
@@ -363,6 +220,26 @@
     });
   }
 
+  protected EditableArea createEditableArea() {
+    return new DesignerEditableArea();
+  }
+
+  protected ToolProvider createToolProvider() {
+    return new DesignerToolProvider();
+  }
+
+  protected DecorationLayer createDecorationLayer() {
+    return new DecorationLayer(this, mySurfaceArea);
+  }
+
+  protected FeedbackLayer createFeedbackLayer() {
+    return new FeedbackLayer();
+  }
+
+  protected InplaceEditingLayer createInplaceEditingLayer() {
+    return new InplaceEditingLayer(this);
+  }
+
   protected CaptionPanel createCaptionPanel(boolean horizontal) {
     return new CaptionPanel(this, horizontal, true);
   }
@@ -988,6 +865,157 @@
     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)) {
+        PaletteToolWindowManager.getInstance(getProject()).clearActiveItem();
+      }
+      if (!(tool instanceof SelectionTool)) {
+        hideInspections();
+      }
+      super.setActiveTool(tool);
+    }
+
+    @Override
+    public boolean execute(final ThrowableRunnable<Exception> operation, String command, final boolean updateProperties) {
+      final boolean[] is = {true};
+      CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
+        public void run() {
+          is[0] = DesignerEditorPanel.this.execute(operation, updateProperties);
+        }
+      }, command, null);
+      return is[0];
+    }
+
+    @Override
+    public void executeWithReparse(final ThrowableRunnable<Exception> operation, String 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) {
+      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--) {
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/tools/SelectionTool.java b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/tools/SelectionTool.java
index c41f332..151117b 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/tools/SelectionTool.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/tools/SelectionTool.java
@@ -127,6 +127,14 @@
         myArea.setDescription(null);
       }
       else {
+        if (myInputEvent instanceof MouseEvent) {
+          try {
+            tracker.mouseMove((MouseEvent)myInputEvent, myArea);
+          }
+          catch (Exception e) {
+            // pass
+          }
+        }
         myArea.setCursor(tracker.getDefaultCursor());
         myArea.setDescription(tracker.getDescription());
       }
diff --git a/resources-en/src/fileTemplates/code/Catch Statement Body.java.ft b/resources-en/src/fileTemplates/code/Catch Statement Body.java.ft
index fea0f59..a6e7209 100644
--- a/resources-en/src/fileTemplates/code/Catch Statement Body.java.ft
+++ b/resources-en/src/fileTemplates/code/Catch Statement Body.java.ft
@@ -1 +1 @@
-${EXCEPTION}.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
\ No newline at end of file
+${EXCEPTION}.printStackTrace();
\ No newline at end of file
diff --git a/resources-en/src/fileTemplates/code/Implemented Method Body.java.ft b/resources-en/src/fileTemplates/code/Implemented Method Body.java.ft
index 3f770be..f055c7f 100644
--- a/resources-en/src/fileTemplates/code/Implemented Method Body.java.ft
+++ b/resources-en/src/fileTemplates/code/Implemented Method Body.java.ft
@@ -1 +1 @@
-#if ( $RETURN_TYPE != "void" )return $DEFAULT_RETURN_VALUE;#end  //To change body of implemented methods use File | Settings | File Templates.
\ No newline at end of file
+#if ( $RETURN_TYPE != "void" )return $DEFAULT_RETURN_VALUE;#end
\ No newline at end of file
diff --git a/resources-en/src/fileTemplates/code/New Method Body.java.ft b/resources-en/src/fileTemplates/code/New Method Body.java.ft
index 5a359cb..f055c7f 100644
--- a/resources-en/src/fileTemplates/code/New Method Body.java.ft
+++ b/resources-en/src/fileTemplates/code/New Method Body.java.ft
@@ -1 +1 @@
-#if ( $RETURN_TYPE != "void" )return $DEFAULT_RETURN_VALUE;#end  //To change body of created methods use File | Settings | File Templates.
\ No newline at end of file
+#if ( $RETURN_TYPE != "void" )return $DEFAULT_RETURN_VALUE;#end
\ No newline at end of file
diff --git a/resources-en/src/fileTemplates/code/Overridden Method Body.java.ft b/resources-en/src/fileTemplates/code/Overridden Method Body.java.ft
index 43116f4..b96e408 100644
--- a/resources-en/src/fileTemplates/code/Overridden Method Body.java.ft
+++ b/resources-en/src/fileTemplates/code/Overridden Method Body.java.ft
@@ -1 +1 @@
-$CALL_SUPER;    //To change body of overridden methods use File | Settings | File Templates.
\ No newline at end of file
+$CALL_SUPER;
\ No newline at end of file
diff --git a/resources-en/src/fileTemplates/includes/File Header.java.ft b/resources-en/src/fileTemplates/includes/File Header.java.ft
index 4b498f0..c6b8d66 100644
--- a/resources-en/src/fileTemplates/includes/File Header.java.ft
+++ b/resources-en/src/fileTemplates/includes/File Header.java.ft
@@ -3,5 +3,4 @@
  * User: ${USER}
  * Date: ${DATE}
  * Time: ${TIME}
- * To change this template use File | Settings | File Templates.
  */
diff --git a/resources-en/src/inspectionDescriptions/DefaultFileTemplate.html b/resources-en/src/inspectionDescriptions/DefaultFileTemplate.html
index e98943a..0e869e6 100644
--- a/resources-en/src/inspectionDescriptions/DefaultFileTemplate.html
+++ b/resources-en/src/inspectionDescriptions/DefaultFileTemplate.html
@@ -7,6 +7,6 @@
     <li>Generated Catch block section.</li>
   </ul>
  <p>
-Also, the inspection proposes to change default file template usages to the actual file templates configured in Settings|IDE|File Templates. 
+Also, the inspection proposes to change default file template and its usage.
 </body>
 </html>
\ No newline at end of file
diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java b/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java
index 4fa7f61..965f1bd 100644
--- a/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java
+++ b/xml/dom-impl/src/com/intellij/util/xml/impl/DomAnchorImpl.java
@@ -36,11 +36,11 @@
 public abstract class DomAnchorImpl<T extends DomElement> implements DomAnchor<T> {
   private static final Logger LOG = Logger.getInstance("#com.intellij.util.xml.impl.DomAnchorImpl");
 
-  public static <T extends DomElement> DomAnchorImpl<T> createAnchor(@NotNull T t) {
+  public static <T extends DomElement> DomAnchor<T> createAnchor(@NotNull T t) {
     return createAnchor(t, false);
   }
 
-  public static <T extends DomElement> DomAnchorImpl<T> createAnchor(@NotNull T t, boolean usePsi) {
+  public static <T extends DomElement> DomAnchor<T> createAnchor(@NotNull T t, boolean usePsi) {
     if (usePsi) {
       final XmlElement element = t.getXmlElement();
       if (element != null) {
@@ -48,6 +48,11 @@
       }
     }
 
+    DomInvocationHandler handler = DomManagerImpl.getNotNullHandler(t);
+    if (handler.getStub() != null) {
+      return new StubAnchor<T>(handler);
+    }
+
     final DomElement parent = t.getParent();
     if (parent == null) {
       LOG.error("Parent null: " + t);
@@ -59,7 +64,7 @@
       return new RootAnchor<T>(fileElement.getFile(), fileElement.getRootElementClass());
     }
 
-    final DomAnchorImpl<DomElement> parentAnchor = createAnchor(parent);
+    final DomAnchorImpl<DomElement> parentAnchor = (DomAnchorImpl<DomElement>)createAnchor(parent);
     final String name = t.getGenericInfo().getElementName(t);
     final AbstractDomChildrenDescription description = t.getChildDescription();
     final List<? extends DomElement> values = description.getValues(parent);
@@ -373,9 +378,4 @@
       return myHandler.getXmlElement();
     }
   }
-
-  public static <T extends DomElement> DomAnchor<T> createStubAnchor(T element) {
-    DomInvocationHandler handler = DomManagerImpl.getDomInvocationHandler(element);
-    return handler.getStub() == null ? createAnchor(element, true) : new StubAnchor<T>(handler);
-  }
 }