Merge remote branch 'origin/master'

This commit is contained in:
irengrig
2012-05-16 12:48:18 +04:00
235 changed files with 12476 additions and 2799 deletions
@@ -228,6 +228,14 @@ public class BuildArtifactsBeforeRunTaskProvider extends BeforeRunTaskProvider<B
public static void setBuildArtifactBeforeRun(@NotNull Project project, @NotNull RunConfiguration configuration, @NotNull Artifact artifact) {
RunManagerEx runManager = RunManagerEx.getInstanceEx(project);
final List<BuildArtifactsBeforeRunTask> buildArtifactsTasks = runManager.getBeforeRunTasks(configuration, ID);
if (buildArtifactsTasks.isEmpty()) { //Add new task if absent
BuildArtifactsBeforeRunTask task = new BuildArtifactsBeforeRunTask(project);
buildArtifactsTasks.add(task);
List<BeforeRunTask> tasks = runManager.getBeforeRunTasks(configuration);
tasks.add(task);
runManager.setBeforeRunTasks(configuration, tasks, false);
}
for (BuildArtifactsBeforeRunTask task : buildArtifactsTasks) {
task.setEnabled(true);
task.addArtifact(artifact);
@@ -33,6 +33,7 @@ import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.Ref;
import com.intellij.util.containers.HashMap;
@@ -148,7 +149,7 @@ public class JavaMarkObjectActionHandler extends MarkObjectActionHandler {
if (node instanceof DebuggerTreeNodeImpl) {
final DebuggerTreeNodeImpl _node = (DebuggerTreeNodeImpl)node;
final NodeDescriptorImpl descriptor = _node.getDescriptor();
if (descriptor instanceof ValueDescriptor && value.equals(((ValueDescriptor)descriptor).getValue())) {
if (descriptor instanceof ValueDescriptor && Comparing.equal(value, ((ValueDescriptor)descriptor).getValue())) {
_node.labelChanged();
}
}
@@ -447,10 +447,12 @@ public abstract class DebugProcessImpl implements DebugProcess {
try {
if (thread != null && thread.frameCount() > 0) {
StackFrameProxyImpl stackFrame = thread.frame(0);
Location location = stackFrame.location();
ReferenceType referenceType = location.declaringType();
if (referenceType != null) {
return referenceType.name();
if (stackFrame != null) {
Location location = stackFrame.location();
ReferenceType referenceType = location.declaringType();
if (referenceType != null) {
return referenceType.name();
}
}
}
}
@@ -19,13 +19,12 @@ import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.actions.*;
import com.intellij.debugger.impl.DebuggerContextImpl;
import com.intellij.debugger.settings.*;
import com.intellij.debugger.ui.breakpoints.Breakpoint;
import com.intellij.debugger.ui.breakpoints.BreakpointFactory;
import com.intellij.debugger.ui.breakpoints.BreakpointPanel;
import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter;
import com.intellij.debugger.ui.breakpoints.*;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.editor.markup.RangeHighlighter;
@@ -33,6 +32,9 @@ import com.intellij.openapi.options.Configurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Key;
import com.intellij.ui.popup.util.ItemWrapper;
import com.intellij.ui.popup.util.SplitterItem;
import com.intellij.xdebugger.AbstractDebuggerSession;
import com.intellij.xdebugger.impl.DebuggerSupport;
import com.intellij.xdebugger.impl.actions.DebuggerActionHandler;
@@ -48,6 +50,7 @@ import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* @author nik
@@ -184,10 +187,12 @@ public class JavaDebuggerSupport extends DebuggerSupport {
}
private static class JavaBreakpointPanelProvider extends BreakpointPanelProvider<Breakpoint> {
private List<MyBreakpointManagerListener> myListeners = new CopyOnWriteArrayList<MyBreakpointManagerListener>();
@NotNull
public Collection<AbstractBreakpointPanel<Breakpoint>> getBreakpointPanels(@NotNull final Project project, @NotNull final DialogWrapper parentDialog) {
List<AbstractBreakpointPanel<Breakpoint>> panels = new ArrayList<AbstractBreakpointPanel<Breakpoint>>();
final BreakpointFactory[] allFactories = ApplicationManager.getApplication().getExtensions(BreakpointFactory.EXTENSION_POINT_NAME);
final BreakpointFactory[] allFactories = BreakpointFactory.getBreakpointFactories();
for (BreakpointFactory factory : allFactories) {
BreakpointPanel panel = factory.createBreakpointPanel(project, parentDialog);
if (panel != null) {
@@ -198,6 +203,33 @@ public class JavaDebuggerSupport extends DebuggerSupport {
return panels;
}
@Override
public AnAction[] getAddBreakpointActions(@NotNull Project project) {
List<AnAction> result = new ArrayList<AnAction>();
BreakpointFactory[] breakpointFactories = BreakpointFactory.getBreakpointFactories();
for (BreakpointFactory breakpointFactory : breakpointFactories) {
result.add(new AddJavaBreakpointAction(breakpointFactory));
}
return result.toArray(new AnAction[result.size()]);
}
@Override
public void addListener(final BreakpointsListener listener, Project project) {
final MyBreakpointManagerListener listener1 = new MyBreakpointManagerListener(listener);
DebuggerManagerEx.getInstanceEx(getCurrentProject()).getBreakpointManager().addBreakpointManagerListener(listener1);
myListeners.add(listener1);
}
@Override
public void removeListener(BreakpointsListener listener) {
for (MyBreakpointManagerListener managerListener : myListeners) {
if (managerListener.myListener == listener) {
myListeners.remove(managerListener);
break;
}
}
}
public int getPriority() {
return 1;
}
@@ -220,6 +252,55 @@ public class JavaDebuggerSupport extends DebuggerSupport {
public void onDialogClosed(final Project project) {
DebuggerManagerEx.getInstanceEx(project).getBreakpointManager().updateAllRequests();
}
@Override
public void provideBreakpointItems(Project project, Collection<ItemWrapper> items) {
for (BreakpointFactory breakpointFactory : BreakpointFactory.getBreakpointFactories()) {
Key<? extends Breakpoint> category = breakpointFactory.getBreakpointCategory();
Breakpoint[] breakpoints = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager().getBreakpoints(category);
if (breakpoints.length > 0) {
items.add(new SplitterItem(breakpointFactory.getDisplayName()));
}
for (Breakpoint breakpoint : breakpoints) {
items.add(breakpointFactory.createBreakpointItem(breakpoint));
}
}
}
private static class AddJavaBreakpointAction extends AnAction {
private BreakpointFactory myBreakpointFactory;
public AddJavaBreakpointAction(BreakpointFactory breakpointFactory) {
myBreakpointFactory = breakpointFactory;
Presentation p = getTemplatePresentation();
p.setIcon(myBreakpointFactory.getIcon());
p.setText(breakpointFactory.getDisplayName());
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setVisible(myBreakpointFactory.canAddBreakpoints());
}
@Override
public void actionPerformed(AnActionEvent e) {
myBreakpointFactory.addBreakpoint(getEventProject(e));
}
}
private static class MyBreakpointManagerListener implements BreakpointManagerListener {
private final BreakpointsListener myListener;
public MyBreakpointManagerListener(BreakpointsListener listener) {
myListener = listener;
}
@Override
public void breakpointsChanged() {
myListener.breakpointsChanged();
}
}
}
public static class JavaDebuggerSettingsPanelProvider extends DebuggerSettingsPanelProvider {
@@ -27,6 +27,7 @@ import com.intellij.debugger.jdi.StackFrameProxyImpl;
import com.intellij.debugger.jdi.ThreadReferenceProxyImpl;
import com.intellij.debugger.ui.breakpoints.*;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DefaultActionGroup;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
@@ -300,7 +301,7 @@ public class PositionHighlighter {
try {
StackFrameProxyImpl frameProxy = myContext.getFrameProxy();
final ThreadReferenceProxyImpl thread = getSuspendContext().getThread();
isExecutionPoint = thread != null && frameProxy.equals(thread.frame(0));
isExecutionPoint = thread != null && frameProxy != null && frameProxy.equals(thread.frame(0));
}
catch(Throwable th) {
LOG.debug(th);
@@ -410,7 +411,7 @@ public class PositionHighlighter {
DefaultActionGroup group = new DefaultActionGroup();
for (Pair<Breakpoint, Event> eventDescriptor : myEventsOutOfLine) {
Breakpoint breakpoint = eventDescriptor.getFirst();
ViewBreakpointsAction viewBreakpointsAction = new ViewBreakpointsAction(breakpoint.getDisplayName(), breakpoint);
AnAction viewBreakpointsAction = new ViewBreakpointsAction(breakpoint.getDisplayName(), breakpoint);
group.add(viewBreakpointsAction);
}
@@ -62,6 +62,11 @@ public class AnyExceptionBreakpointFactory extends BreakpointFactory{
return new BreakpointPanelAction[0]; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean breakpointCanBeRemoved(Breakpoint breakpoint) {
return false;
}
public @Nullable BreakpointPanel createBreakpointPanel(Project project, DialogWrapper parentDialog) {
return null;
}
@@ -21,6 +21,7 @@ import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.util.Key;
import com.intellij.xdebugger.breakpoints.ui.BreakpointItem;
import org.jdom.Element;
import org.jetbrains.annotations.Nullable;
@@ -30,17 +31,21 @@ import javax.swing.*;
* Used to deexternalize breakpoints of certain category while reading saved configuration and for creating configuration UI
*/
public abstract class BreakpointFactory {
public static final ExtensionPointName<BreakpointFactory> EXTENSION_POINT_NAME = ExtensionPointName.create("com.intellij.debugger.breakpointFactory");
public static final ExtensionPointName<BreakpointFactory> EXTENSION_POINT_NAME =
ExtensionPointName.create("com.intellij.debugger.breakpointFactory");
public static BreakpointFactory[] getBreakpointFactories() {
return ApplicationManager.getApplication().getExtensions(EXTENSION_POINT_NAME);
}
public abstract Breakpoint createBreakpoint(Project project, final Element element);
public abstract Key<? extends Breakpoint> getBreakpointCategory();
public BreakpointPanel createBreakpointPanel(final Project project, final DialogWrapper parentDialog) {
BreakpointPanel panel = new BreakpointPanel(project,
createBreakpointPropertiesPanel(project, false),
createBreakpointPanelActions(project, parentDialog),
getBreakpointCategory(), getDisplayName(), getHelpID());
BreakpointPanel panel =
new BreakpointPanel(project, createBreakpointPropertiesPanel(project, false), createBreakpointPanelActions(project, parentDialog),
getBreakpointCategory(), getDisplayName(), getHelpID());
configureBreakpointPanel(panel);
return panel;
}
@@ -51,7 +56,7 @@ public abstract class BreakpointFactory {
@Nullable
public static BreakpointFactory getInstance(Key<? extends Breakpoint> category) {
final BreakpointFactory[] allFactories = ApplicationManager.getApplication().getExtensions(BreakpointFactory.EXTENSION_POINT_NAME);
final BreakpointFactory[] allFactories = getBreakpointFactories();
for (final BreakpointFactory factory : allFactories) {
if (category.equals(factory.getBreakpointCategory())) {
return factory;
@@ -60,13 +65,32 @@ public abstract class BreakpointFactory {
return null;
}
protected void configureBreakpointPanel(BreakpointPanel panel){};
protected void configureBreakpointPanel(BreakpointPanel panel) {
}
protected abstract String getHelpID();
public abstract String getDisplayName();
@Nullable
public abstract BreakpointPropertiesPanel createBreakpointPropertiesPanel(Project project, boolean compact);
protected abstract BreakpointPanelAction[] createBreakpointPanelActions(Project project, DialogWrapper parentDialog);
@Nullable
public Breakpoint addBreakpoint(Project project) {
return null;
}
public boolean canAddBreakpoints() {
return false;
}
public boolean breakpointCanBeRemoved(Breakpoint breakpoint) {
return true;
}
public BreakpointItem createBreakpointItem(final Breakpoint breakpoint) {
return new JavaBreakpointItem(this, breakpoint);
}
}
@@ -51,6 +51,8 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
@@ -108,6 +110,17 @@ public abstract class BreakpointPropertiesPanel {
private static final int MAX_COMBO_WIDTH = 300;
private final FixedSizeButton myConditionMagnifierButton;
private boolean myMoreOptionsVisible = true;
private Breakpoint myBreakpoint;
public boolean isSaveOnRemove() {
return mySaveOnRemove;
}
public void setSaveOnRemove(boolean saveOnRemove) {
mySaveOnRemove = saveOnRemove;
}
private boolean mySaveOnRemove = false;
public boolean isMoreOptionsVisible() {
return myMoreOptionsVisible;
@@ -116,13 +129,14 @@ public abstract class BreakpointPropertiesPanel {
private void createUIComponents() {
myPanel = new JPanel() {
@Override
public boolean requestFocus(boolean b) {
return super.requestFocus(b); //To change body of overridden methods use File | Settings | File Templates.
}
@Override
public void requestFocus() {
super.requestFocus(); //To change body of overridden methods use File | Settings | File Templates.
public void removeNotify() {
super.removeNotify();
if (mySaveOnRemove) {
saveTo(myBreakpoint, new Runnable() {
@Override
public void run() {}
});
}
}
};
}
@@ -262,6 +276,24 @@ public abstract class BreakpointPropertiesPanel {
myBreakpointComboboxHandler = new BreakpointComboboxHandler(myProject, baseBreakpointCombo);
baseBreakpointCombo.setRenderer(new BreakpointComboRenderer(baseBreakpointCombo.getRenderer()));
baseBreakpointCombo.addPopupMenuListener(new PopupMenuListener() {
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
event.getClass();//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
//To change body of implemented methods use File | Settings | File Templates.
event.getClass();
}
@Override
public void popupMenuCanceled(PopupMenuEvent event) {
//To change body of implemented methods use File | Settings | File Templates.
event.getClass();
}
});
baseBreakpointCombo.addItemListener(new ItemListener() {
public void itemStateChanged(final ItemEvent e) {
ComboboxItem item = (ComboboxItem)baseBreakpointCombo.getSelectedItem();
@@ -392,6 +424,7 @@ public abstract class BreakpointPropertiesPanel {
* Init UI components with the values from Breakpoint
*/
public void initFrom(Breakpoint breakpoint, boolean moreOptionsVisible1) {
myBreakpoint = breakpoint;
boolean moreOptionsVisible = moreOptionsVisible1;
boolean actionsPanelVisible = moreOptionsVisible1;
myBreakpointComboboxHandler.initFrom(breakpoint);
@@ -637,7 +637,8 @@ public abstract class BreakpointWithHighlighter extends Breakpoint {
}
}
ViewBreakpointsAction viewBreakpointsAction =
AnAction viewBreakpointsAction =
new ViewBreakpointsAction(ActionsBundle.actionText(XDebuggerActions.VIEW_BREAKPOINTS), this);
DefaultActionGroup group = new DefaultActionGroup();
@@ -39,7 +39,7 @@ import java.awt.event.ActionEvent;
* @author Eugene Zhuravlev
* Date: Apr 26, 2005
*/
public class ExceptionBreakpointFactory extends BreakpointFactory{
public class ExceptionBreakpointFactory extends BreakpointFactory {
public Breakpoint createBreakpoint(Project project, final Element element) {
return new ExceptionBreakpoint(project);
}
@@ -77,47 +77,43 @@ public class ExceptionBreakpointFactory extends BreakpointFactory{
protected BreakpointPanelAction[] createBreakpointPanelActions(final Project project, DialogWrapper parentDialog) {
return new BreakpointPanelAction[]{
new SwitchViewAction(),
new AddExceptionBreakpointAction(project),
new AddAction(this, project),
new RemoveAction(project) {
public void update() {
super.update();
if (getButton().isEnabled()) {
Breakpoint[] selectedBreakpoints = getPanel().getSelectedBreakpoints();
for (Breakpoint bp : selectedBreakpoints) {
if (bp instanceof AnyExceptionBreakpoint) {
getButton().setEnabled(false);
}
public void update() {
super.update();
if (getButton().isEnabled()) {
Breakpoint[] selectedBreakpoints = getPanel().getSelectedBreakpoints();
for (Breakpoint bp : selectedBreakpoints) {
if (bp instanceof AnyExceptionBreakpoint) {
getButton().setEnabled(false);
}
}
}
},
new ToggleGroupByClassesAction(),
new ToggleFlattenPackagesAction(),
};
}
}, new ToggleGroupByClassesAction(), new ToggleFlattenPackagesAction(),};
}
public BreakpointPanel createBreakpointPanel(final Project project, final DialogWrapper parentDialog) {
BreakpointPanel panel = new BreakpointPanel(project,
createBreakpointPropertiesPanel(project, false),
createBreakpointPanelActions(project, parentDialog),
getBreakpointCategory(), getDisplayName(), getHelpID()){
public void resetBreakpoints() {
super.resetBreakpoints();
Breakpoint[] breakpoints = getBreakpointManager().getBreakpoints(getBreakpointCategory());
final AnyExceptionBreakpoint anyExceptionBreakpoint = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager().getAnyExceptionBreakpoint();
boolean found = false;
for (Breakpoint breakpoint : breakpoints) {
if (breakpoint.equals(anyExceptionBreakpoint)) {
found = true;
break;
BreakpointPanel panel =
new BreakpointPanel(project, createBreakpointPropertiesPanel(project, false), createBreakpointPanelActions(project, parentDialog),
getBreakpointCategory(), getDisplayName(), getHelpID()) {
public void resetBreakpoints() {
super.resetBreakpoints();
Breakpoint[] breakpoints = getBreakpointManager().getBreakpoints(getBreakpointCategory());
final AnyExceptionBreakpoint anyExceptionBreakpoint =
DebuggerManagerEx.getInstanceEx(project).getBreakpointManager().getAnyExceptionBreakpoint();
boolean found = false;
for (Breakpoint breakpoint : breakpoints) {
if (breakpoint.equals(anyExceptionBreakpoint)) {
found = true;
break;
}
}
if (!found) {
insertBreakpointAt(anyExceptionBreakpoint, 0);
}
}
if (!found) {
insertBreakpointAt(anyExceptionBreakpoint, 0);
}
}
};
};
configureBreakpointPanel(panel);
return panel;
}
@@ -126,29 +122,27 @@ public class ExceptionBreakpointFactory extends BreakpointFactory{
return ExceptionBreakpoint.CATEGORY;
}
private static class AddExceptionBreakpointAction extends AddAction {
private final Project myProject;
public AddExceptionBreakpointAction(Project project) {
myProject = project;
}
public void actionPerformed(ActionEvent e) {
final PsiClass throwableClass =
JavaPsiFacade.getInstance(myProject).findClass("java.lang.Throwable", GlobalSearchScope.allScope(myProject));
TreeClassChooser chooser =
TreeClassChooserFactory.getInstance(myProject).createInheritanceClassChooser(
DebuggerBundle.message("add.exception.breakpoint.classchooser.title"), GlobalSearchScope.allScope(myProject),
throwableClass, true, true, null);
chooser.showDialog();
PsiClass selectedClass = chooser.getSelected();
String qName = selectedClass == null ? null : JVMNameUtil.getNonAnonymousClassName(selectedClass);
if (qName != null && qName.length() > 0) {
ExceptionBreakpoint breakpoint = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().addExceptionBreakpoint(qName, ((PsiClassOwner)selectedClass.getContainingFile()).getPackageName());
getPanel().addBreakpoint(breakpoint);
}
}
@Override
public boolean canAddBreakpoints() {
return true;
}
@Override
public Breakpoint addBreakpoint(Project project) {
ExceptionBreakpoint breakpoint = null;
final PsiClass throwableClass =
JavaPsiFacade.getInstance(project).findClass("java.lang.Throwable", GlobalSearchScope.allScope(project));
TreeClassChooser chooser = TreeClassChooserFactory.getInstance(project)
.createInheritanceClassChooser(DebuggerBundle.message("add.exception.breakpoint.classchooser.title"),
GlobalSearchScope.allScope(project), throwableClass, true, true, null);
chooser.showDialog();
PsiClass selectedClass = chooser.getSelected();
String qName = selectedClass == null ? null : JVMNameUtil.getNonAnonymousClassName(selectedClass);
if (qName != null && qName.length() > 0) {
breakpoint = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager()
.addExceptionBreakpoint(qName, ((PsiClassOwner)selectedClass.getContainingFile()).getPackageName());
}
return breakpoint;
}
}
@@ -25,6 +25,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import org.jdom.Element;
@@ -73,7 +74,7 @@ public class FieldBreakpointFactory extends BreakpointFactory{
protected BreakpointPanelAction[] createBreakpointPanelActions(final Project project, final DialogWrapper parentDialog) {
return new BreakpointPanelAction[] {
new SwitchViewAction(),
new AddFieldBreakpointAction(project),
new AddAction(this, project),
new GotoSourceAction(project) {
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
@@ -91,65 +92,61 @@ public class FieldBreakpointFactory extends BreakpointFactory{
return FieldBreakpoint.CATEGORY;
}
private static class AddFieldBreakpointAction extends AddAction {
private final Project myProject;
public AddFieldBreakpointAction(Project project) {
myProject = project;
}
public void actionPerformed(ActionEvent e) {
AddFieldBreakpointDialog dialog = new AddFieldBreakpointDialog(myProject) {
protected boolean validateData() {
String className = getClassName();
if (className.length() == 0) {
Messages.showMessageDialog(myProject, DebuggerBundle.message("error.field.breakpoint.class.name.not.specified"),
DebuggerBundle.message("add.field.breakpoint.dialog.title"), Messages.getErrorIcon());
return false;
}
String fieldName = getFieldName();
if (fieldName.length() == 0) {
Messages.showMessageDialog(myProject, DebuggerBundle.message("error.field.breakpoint.field.name.not.specified"),
DebuggerBundle.message("add.field.breakpoint.dialog.title"), Messages.getErrorIcon());
return false;
}
PsiClass psiClass = JavaPsiFacade.getInstance(myProject).findClass(className, GlobalSearchScope.allScope(myProject));
if (psiClass != null) {
PsiFile psiFile = psiClass.getContainingFile();
Document document = PsiDocumentManager.getInstance(myProject).getDocument(psiFile);
if(document != null) {
PsiField field = psiClass.findFieldByName(fieldName, true);
if(field != null) {
int line = document.getLineNumber(field.getTextOffset());
FieldBreakpoint fieldBreakpoint = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().addFieldBreakpoint(document, line, fieldName);
if (fieldBreakpoint != null) {
getPanel().addBreakpoint(fieldBreakpoint);
return true;
}
}
else {
Messages.showMessageDialog(
myProject,
DebuggerBundle.message("error.field.breakpoint.field.not.found", className, fieldName, fieldName),
CommonBundle.getErrorTitle(),
Messages.getErrorIcon()
);
}
}
} else {
Messages.showMessageDialog(
myProject,
DebuggerBundle.message("error.field.breakpoint.class.sources.not.found", className, fieldName, className),
CommonBundle.getErrorTitle(),
Messages.getErrorIcon()
);
}
@Override
public Breakpoint addBreakpoint(final Project project) {
final Ref<Breakpoint> result = Ref.create(null);
AddFieldBreakpointDialog dialog = new AddFieldBreakpointDialog(project) {
protected boolean validateData() {
String className = getClassName();
if (className.length() == 0) {
Messages.showMessageDialog(project, DebuggerBundle.message("error.field.breakpoint.class.name.not.specified"),
DebuggerBundle.message("add.field.breakpoint.dialog.title"), Messages.getErrorIcon());
return false;
}
};
dialog.show();
}
String fieldName = getFieldName();
if (fieldName.length() == 0) {
Messages.showMessageDialog(project, DebuggerBundle.message("error.field.breakpoint.field.name.not.specified"),
DebuggerBundle.message("add.field.breakpoint.dialog.title"), Messages.getErrorIcon());
return false;
}
PsiClass psiClass = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project));
if (psiClass != null) {
PsiFile psiFile = psiClass.getContainingFile();
Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
if(document != null) {
PsiField field = psiClass.findFieldByName(fieldName, true);
if(field != null) {
int line = document.getLineNumber(field.getTextOffset());
FieldBreakpoint fieldBreakpoint = DebuggerManagerEx.getInstanceEx(project).getBreakpointManager().addFieldBreakpoint(document, line, fieldName);
if (fieldBreakpoint != null) {
result.set(fieldBreakpoint);
return true;
}
}
else {
Messages.showMessageDialog(project,
DebuggerBundle.message("error.field.breakpoint.field.not.found", className, fieldName, fieldName),
CommonBundle.getErrorTitle(),
Messages.getErrorIcon()
);
}
}
} else {
Messages.showMessageDialog(project,
DebuggerBundle.message("error.field.breakpoint.class.sources.not.found", className, fieldName, className),
CommonBundle.getErrorTitle(),
Messages.getErrorIcon()
);
}
return false;
}
};
dialog.show();
return result.get();
}
@Override
public boolean canAddBreakpoints() {
return true;
}
}
@@ -0,0 +1,128 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.ui.breakpoints;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.SourcePosition;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.popup.util.DetailView;
import com.intellij.xdebugger.breakpoints.ui.BreakpointItem;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: intendia
* Date: 10.05.12
* Time: 3:16
* To change this template use File | Settings | File Templates.
*/
class JavaBreakpointItem implements BreakpointItem {
private final Breakpoint myBreakpoint;
private BreakpointFactory myBreakpointFactory;
public JavaBreakpointItem(BreakpointFactory breakpointFactory, Breakpoint breakpoint) {
myBreakpointFactory = breakpointFactory;
myBreakpoint = breakpoint;
}
@Override
public void setupRenderer(ColoredListCellRenderer renderer, Project project, boolean selected) {
renderer.setIcon(myBreakpoint.getIcon());
renderer.append(myBreakpoint.getShortName());
}
@Override
public void updateMnemonicLabel(JLabel label) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void execute(Project project, JBPopup popup) {
if (myBreakpoint instanceof BreakpointWithHighlighter) {
final SourcePosition position = ((BreakpointWithHighlighter)myBreakpoint).getSourcePosition();
if (position != null) {
position.navigate(true);
popup.cancel();
}
}
}
@Override
public String speedSearchText() {
return myBreakpoint.getDisplayName();
}
@Override
public String footerText() {
return myBreakpoint.getDisplayName();
}
@Override
public void updateDetailView(DetailView panel) {
BreakpointPropertiesPanel breakpointPropertiesPanel = myBreakpointFactory
.createBreakpointPropertiesPanel(myBreakpoint.getProject(), false);
if (breakpointPropertiesPanel != null) {
breakpointPropertiesPanel.setSaveOnRemove(true);
}
if (breakpointPropertiesPanel != null) {
breakpointPropertiesPanel.initFrom(myBreakpoint, true);
final JPanel mainPanel = breakpointPropertiesPanel.getPanel();
panel.setDetailPanel(mainPanel);
}
else {
panel.setDetailPanel(null);
}
if (myBreakpoint instanceof BreakpointWithHighlighter) {
SourcePosition sourcePosition = ((BreakpointWithHighlighter)myBreakpoint).getSourcePosition();
VirtualFile virtualFile = sourcePosition.getFile().getVirtualFile();
panel.navigateInPreviewEditor(virtualFile, new LogicalPosition(sourcePosition.getLine(), 0));
} else {
panel.clearEditor();
}
}
@Override
public boolean allowedToRemove() {
return myBreakpointFactory.breakpointCanBeRemoved(myBreakpoint);
}
@Override
public void removed(Project project) {
DebuggerManagerEx.getInstanceEx(project).getBreakpointManager().removeBreakpoint(myBreakpoint);
}
@Override
public Object getBreakpoint() {
return myBreakpoint;
}
@Override
public boolean isEnabled() {
return myBreakpoint.ENABLED;
}
@Override
public void setEnabled(boolean state) {
myBreakpoint.ENABLED = state;
}
}
@@ -131,28 +131,17 @@ public class LineBreakpoint extends BreakpointWithHighlighter {
}
try {
List<Location> locs = debugProcess.getPositionManager().locationsOfLine(classType, getSourcePosition());
if (locs.size() > 0) {
Location minLocation = null;
for (final Location loc : locs) {
if (minLocation == null) {
minLocation = loc;
if (!locs.isEmpty()) {
for (Location loc : locs) {
if (LOG.isDebugEnabled()) {
LOG.debug("Found location [codeIndex=" + loc.codeIndex() +"] for reference type " + classType.name() + " at line " + getLineIndex() + "; isObsolete: " + (debugProcess.getVirtualMachineProxy().versionHigher("1.4") && loc.method().isObsolete()));
}
else if (loc.codeIndex() < minLocation.codeIndex()) {
minLocation = loc;
BreakpointRequest request = debugProcess.getRequestsManager().createBreakpointRequest(LineBreakpoint.this, loc);
debugProcess.getRequestsManager().enableRequest(request);
if (LOG.isDebugEnabled()) {
LOG.debug("Created breakpoint request for reference type " + classType.name() + " at line " + getLineIndex() + "; codeIndex=" + loc.codeIndex());
}
}
assert minLocation != null;
if (LOG.isDebugEnabled()) {
LOG.debug("Found location for reference type " + classType.name() + " at line " + getLineIndex() + "; isObsolete: " + (debugProcess.getVirtualMachineProxy().versionHigher("1.4") && minLocation
.method().isObsolete()));
}
BreakpointRequest request = debugProcess.getRequestsManager().createBreakpointRequest(LineBreakpoint.this, minLocation);
debugProcess.getRequestsManager().enableRequest(request);
if (LOG.isDebugEnabled()) {
LOG.debug("Created breakpoint request for reference type " + classType.name() + " at line " + getLineIndex());
}
}
else {
// there's no executable code in this class
@@ -63,7 +63,7 @@ public class MethodBreakpointFactory extends BreakpointFactory{
protected BreakpointPanelAction[] createBreakpointPanelActions(Project project, final DialogWrapper parentDialog) {
return new BreakpointPanelAction[]{
new SwitchViewAction(),
new AddWildcardBreakpointAction(project),
new AddAction(this, project),
new GotoSourceAction(project) {
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
@@ -87,23 +87,19 @@ public class MethodBreakpointFactory extends BreakpointFactory{
return MethodBreakpoint.CATEGORY;
}
private static class AddWildcardBreakpointAction extends AddAction {
private final Project myProject;
@Override
public boolean canAddBreakpoints() {
return true;
}
public AddWildcardBreakpointAction(Project project) {
myProject = project;
}
public void actionPerformed(ActionEvent e) {
AddWildcardBreakpointDialog dialog = new AddWildcardBreakpointDialog(myProject);
dialog.show();
if (!dialog.isOK()) {
return;
}
final WildcardMethodBreakpoint methodBreakpoint = DebuggerManagerEx.getInstanceEx(myProject).getBreakpointManager().addMethodBreakpoint(dialog.getClassPattern(), dialog.getMethodName());
if (methodBreakpoint != null) {
getPanel().addBreakpoint(methodBreakpoint);
}
}
public WildcardMethodBreakpoint addBreakpoint(Project project) {
AddWildcardBreakpointDialog dialog = new AddWildcardBreakpointDialog(project);
dialog.show();
WildcardMethodBreakpoint methodBreakpoint;
methodBreakpoint = !dialog.isOK()
? null
: DebuggerManagerEx.getInstanceEx(project).getBreakpointManager()
.addMethodBreakpoint(dialog.getClassPattern(), dialog.getMethodName());
return methodBreakpoint;
}
}
@@ -15,18 +15,28 @@
*/
package com.intellij.debugger.ui.breakpoints.actions;
import com.intellij.debugger.ui.breakpoints.Breakpoint;
import com.intellij.debugger.ui.breakpoints.BreakpointFactory;
import com.intellij.debugger.ui.breakpoints.BreakpointPanel;
import com.intellij.ide.IdeBundle;
import com.intellij.openapi.project.Project;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/**
* @author Eugene Zhuravlev
* Date: May 25, 2005
*/public abstract class AddAction extends BreakpointPanelAction {
protected AddAction() {
*/
public class AddAction extends BreakpointPanelAction {
protected final Project myProject;
protected BreakpointFactory myBreakpointFactory;
public AddAction(BreakpointFactory breakpointFactory, Project project) {
super(IdeBundle.message("button.add"));
myProject = project;
this.myBreakpointFactory = breakpointFactory;
}
public void setPanel(BreakpointPanel panel) {
@@ -36,4 +46,11 @@ import java.awt.event.KeyEvent;
public void update() {
}
public void actionPerformed(ActionEvent e) {
Breakpoint breakpoint = myBreakpointFactory.addBreakpoint(myProject);
if (breakpoint != null) {
getPanel().addBreakpoint(breakpoint);
}
}
}
@@ -220,6 +220,7 @@ public class JavaDocCompletionContributor extends CompletionContributor {
if (context.getCompletionChar() == Lookup.REPLACE_SELECT_CHAR) {
final PsiDocTagValue valueElement = tag.getValueElement();
endOffset = valueElement.getTextRange().getEndOffset();
context.setTailOffset(endOffset);
}
editor.getDocument().deleteString(afterSharp, endOffset);
editor.getCaretModel().moveToOffset(signatureOffset);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,8 @@ package com.intellij.codeInsight.daemon.impl.quickfix;
import com.intellij.codeInsight.*;
import com.intellij.codeInsight.completion.proc.VariablesProcessor;
import com.intellij.codeInsight.daemon.QuickFixBundle;
import com.intellij.codeInsight.generation.OverrideImplementUtil;
import com.intellij.codeInsight.generation.PsiGenerationInfo;
import com.intellij.codeInsight.intention.impl.CreateClassDialog;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
@@ -129,7 +131,7 @@ public class CreateFromUsageUtils {
returnType = PsiType.VOID;
}
PsiElementFactory factory = JavaPsiFacade.getInstance(method.getProject()).getElementFactory();
JVMElementFactory factory = JVMElementFactories.getFactory(aClass.getLanguage(), aClass.getProject());
LOG.assertTrue(!aClass.isInterface(), "Interface bodies should be already set up");
@@ -190,7 +192,7 @@ public class CreateFromUsageUtils {
PsiElement r = PsiTreeUtil.skipSiblingsBackward(body.getRBrace(), PsiWhiteSpace.class);
if (l != null && r != null) {
int start = l.getTextRange().getStartOffset();
int end = r.getTextRange().getEndOffset();
int end = r.getTextRange().getEndOffset();
newEditor.getCaretModel().moveToOffset(Math.max(start, end));
if (end < start) {
newEditor.getCaretModel().moveToOffset(end + 1);
@@ -200,8 +202,12 @@ public class CreateFromUsageUtils {
PsiDocumentManager manager = PsiDocumentManager.getInstance(method.getProject());
manager.doPostponedOperationsAndUnblockDocument(manager.getDocument(containingFile));
EditorModificationUtil.insertStringAtCaret(newEditor, lineIndent);
} else {
newEditor.getSelectionModel().setSelection(Math.min(start, end), Math.max(start, end));
EditorModificationUtil.insertStringAtCaret(newEditor, "\n", false, false);
}
else {
//correct position caret for groovy and java methods
final PsiGenerationInfo<PsiMethod> info = OverrideImplementUtil.createGenerationInfo(method);
info.positionCaret(newEditor, true);
}
newEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
@@ -225,13 +231,13 @@ public class CreateFromUsageUtils {
final PsiSubstitutor substitutor, final List<Pair<PsiExpression, PsiType>> arguments)
throws IncorrectOperationException {
PsiManager psiManager = method.getManager();
PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
JVMElementFactory factory = JVMElementFactories.getFactory(method.getLanguage(), method.getProject());
PsiParameterList parameterList = method.getParameterList();
GlobalSearchScope resolveScope = method.getResolveScope();
GuessTypeParameters guesser = new GuessTypeParameters(factory);
GuessTypeParameters guesser = new GuessTypeParameters(JavaPsiFacade.getElementFactory(method.getProject()));
final PsiClass containingClass = method.getContainingClass();
final boolean isInterface = containingClass != null && containingClass.isInterface();
@@ -943,6 +949,7 @@ public class CreateFromUsageUtils {
@Nullable
private static String getQualifiedName(final PsiClass aClass) {
return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
@Nullable
@Override
public String compute() {
return aClass.getQualifiedName();
@@ -993,7 +1000,16 @@ public class CreateFromUsageUtils {
assert file != null;
PsiElement elementAt = file.findElementAt(offset);
PsiParameterList parameterList = PsiTreeUtil.getParentOfType(elementAt, PsiParameterList.class);
if (parameterList == null) return LookupElement.EMPTY_ARRAY;
if (parameterList == null) {
if (elementAt == null) return LookupElement.EMPTY_ARRAY;
final PsiElement parent = elementAt.getParent();
if (parent instanceof PsiMethod) {
parameterList = ((PsiMethod)parent).getParameterList();
}
else {
return LookupElement.EMPTY_ARRAY;
}
}
PsiParameter parameter = PsiTreeUtil.getParentOfType(elementAt, PsiParameter.class);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -142,7 +142,10 @@ public class CreateMethodFromUsageFix extends CreateFromUsageBaseFix {
String methodName = ref.getReferenceName();
LOG.assertTrue(methodName != null);
PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
JVMElementFactory factory = JVMElementFactories.getFactory(targetClass.getLanguage(), project);
if (factory == null) {
return;
}
PsiMethod method = factory.createMethod(methodName, PsiType.VOID);
@@ -251,7 +254,13 @@ public class CreateMethodFromUsageFix extends CreateFromUsageBaseFix {
if (typeParameters.length > 0) {
for (PsiTypeParameter typeParameter : typeParameters) {
if (checkTypeParam( method, typeParameter)) {
method.getTypeParameterList().add(typeParameter);
final JVMElementFactory factory = JVMElementFactories.getFactory(method.getLanguage(), method.getProject());
PsiTypeParameterList list = method.getTypeParameterList();
if (list == null) {
PsiTypeParameterList newList = factory.createTypeParameterList();
list = (PsiTypeParameterList)method.addAfter(newList, method.getModifierList());
}
list.add(factory.createTypeParameter(typeParameter.getName(),typeParameter.getExtendsList().getReferencedTypes()));
}
}
}
@@ -276,32 +285,59 @@ public class CreateMethodFromUsageFix extends CreateFromUsageBaseFix {
}
}
private static boolean checkTypeParam(final PsiElement typeElement,
final PsiTypeParameter typeParameter) {
public static boolean checkTypeParam(final PsiMethod method, final PsiTypeParameter typeParameter) {
final String typeParameterName = typeParameter.getName();
final boolean[] found = new boolean[] {false};
typeElement.accept(new JavaRecursiveElementWalkingVisitor(){
final PsiTypeVisitor<Boolean> visitor = new PsiTypeVisitor<Boolean>() {
@Override
public void visitElement(PsiElement element) {
if (found[0]) return;
super.visitElement(element);
}
@Override
public void visitTypeElement(PsiTypeElement type) {
super.visitTypeElement(type);
final PsiClass psiClass = PsiUtil.resolveClassInType(type.getType());
public Boolean visitClassType(PsiClassType classType) {
final PsiClass psiClass = classType.resolve();
if (psiClass instanceof PsiTypeParameter &&
PsiTreeUtil.isAncestor(((PsiTypeParameter)psiClass).getOwner(), typeElement, true)) {
return;
PsiTreeUtil.isAncestor(((PsiTypeParameter)psiClass).getOwner(), method, true)) {
return false;
}
if (Comparing.strEqual(typeParameterName, type.getText())) {
found[0] = true;
if (Comparing.strEqual(typeParameterName, classType.getCanonicalText())) {
return true;
}
for (PsiType p : classType.getParameters()) {
if (p.accept(this)) return true;
}
return false;
}
});
return found[0];
@Override
public Boolean visitPrimitiveType(PsiPrimitiveType primitiveType) {
return false;
}
@Override
public Boolean visitArrayType(PsiArrayType arrayType) {
return arrayType.getComponentType().accept(this);
}
@Override
public Boolean visitWildcardType(PsiWildcardType wildcardType) {
final PsiType bound = wildcardType.getBound();
if (bound != null) {
return bound.accept(this);
}
return false;
}
};
final PsiTypeElement rElement = method.getReturnTypeElement();
if (rElement != null) {
if (rElement.getType().accept(visitor)) return true;
}
for (PsiParameter parameter : method.getParameterList().getParameters()) {
final PsiTypeElement element = parameter.getTypeElement();
if (element != null) {
if (element.getType().accept(visitor)) return true;
}
}
return false;
}
protected boolean shouldBeAbstract(PsiClass targetClass) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,11 +54,15 @@ public class JavaTemplateUtil {
PsiMethod method = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
if (method != null) {
PsiTypeParameterList paramList = method.getTypeParameterList();
PsiTypeParameter[] params = paramList.getTypeParameters();
PsiTypeParameter[] params = paramList != null ? paramList.getTypeParameters() : PsiTypeParameter.EMPTY_ARRAY;
for (PsiTypeParameter param : params) {
if (param.getName().equals(aClass.getName())) return;
}
try {
if (paramList == null) {
final PsiTypeParameterList newList = JVMElementFactories.getFactory(method.getLanguage(), project).createTypeParameterList();
paramList = (PsiTypeParameterList)method.addAfter(newList, method.getModifierList());
}
paramList.add(aClass.copy());
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -128,5 +128,12 @@ public interface JVMElementFactory {
@NotNull
PsiElement createExpressionFromText(@NotNull @NonNls String text, @Nullable PsiElement context) throws IncorrectOperationException;
@NotNull
PsiElement createReferenceElementByType(PsiClassType type);
@NotNull
PsiTypeParameterList createTypeParameterList();
@NotNull
PsiTypeParameter createTypeParameter(String name, PsiClassType[] superTypes);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -169,6 +169,34 @@ public class PsiElementFactoryImpl extends PsiJavaParserFacadeImpl implements Ps
return new LightClassReference(myManager, type.getPresentableText(), refClass, resolveResult.getSubstitutor());
}
@NotNull
@Override
public PsiTypeParameterList createTypeParameterList() {
return createMethodFromText("void foo()", null).getTypeParameterList();
}
@NotNull
@Override
public PsiTypeParameter createTypeParameter(String name, PsiClassType[] superTypes) {
StringBuilder builder = new StringBuilder();
builder.append("public <").append(name);
if (superTypes.length > 0) {
builder.append(" extends ");
for (PsiClassType type : superTypes) {
builder.append(type.getCanonicalText()).append(',');
}
builder.delete(builder.length() - 1, builder.length());
}
builder.append("> void foo(){}");
try {
return createMethodFromText(builder.toString(), null).getTypeParameters()[0];
}
catch (RuntimeException e) {
throw new IncorrectOperationException("type parameter text: " + builder.toString());
}
}
@NotNull
@Override
public PsiField createField(@NotNull final String name, @NotNull final PsiType type) throws IncorrectOperationException {
@@ -381,18 +381,6 @@ public class PsiDocMethodOrFieldRef extends CompositePsiElement implements PsiDo
if (nextSibling != null) {
final int startOffset = nextSibling.getTextRange().getStartOffset() - getTextRange().getStartOffset();
int endOffset = nextSibling.getTextRange().getEndOffset() - getTextRange().getStartOffset();
final PsiElement nextParSibling = nextSibling.getNextSibling();
if (nextParSibling != null && "(".equals(nextParSibling.getText())) {
endOffset++;
PsiElement nextElement = nextParSibling.getNextSibling();
if (nextElement != null && SourceTreeToPsiMap.psiToTreeNotNull(nextElement).getElementType() == DOC_TAG_VALUE_TOKEN) {
endOffset += nextElement.getTextLength();
nextElement = nextElement.getNextSibling();
}
if (nextElement != null && ")".equals(nextElement.getText())) {
endOffset++;
}
}
return new TextRange(startOffset, endOffset);
}
return new TextRange(getTextLength(), getTextLength());
@@ -2,7 +2,7 @@ class Test {
public void i(int ppp) {}
/**
* {@link #<error>foo(int)</error>}
* {@link #<error descr="Cannot resolve symbol 'foo(int)'">foo</error>(int)}
* {@link #foo()}
* {@link #i(int)}
*/
@@ -1,6 +1,6 @@
class Test {
/**
* @see #<error>perform(int)</error>
* @see #<error descr="Cannot resolve symbol 'perform(int)'">perform</error>(int)
*/
public void i() {}
@@ -1,7 +1,7 @@
public class Test {
/**
* @see Test#test(String, int...)
* @see Test#<error>test(String, long...)</error>
* @see Test#<error descr="Cannot resolve symbol 'test(String, long...)'">test</error>(String, long...)
**/
void foo() {}
@@ -1,10 +1,10 @@
package pkg;
/**
* @see #<error descr="Cannot resolve symbol 'method(B1.C)'">method(B1.C)</error>
* @see #<error descr="Cannot resolve symbol 'method(B1.C[][])'">method(B1.C[][])</error>
* @see #<error descr="Cannot resolve symbol 'method(B1.C..)'">method(<error descr="Cannot resolve symbol 'B1.C.'">B1.C.</error>.)</error>
* @see #<error descr="Cannot resolve symbol 'method(B1.C[)'">method(B1.C[)</error>
* @see #<error descr="Cannot resolve symbol 'method(B1.C)'">method</error>(B1.C)
* @see #<error descr="Cannot resolve symbol 'method(B1.C[][])'">method</error>(B1.C[][])
* @see #<error descr="Cannot resolve symbol 'method(B1.C..)'">method</error>(<error descr="Cannot resolve symbol 'B1.C.'">B1.C.</error>.)
* @see #<error descr="Cannot resolve symbol 'method(B1.C[)'">method</error>(B1.C[)
*/
class A1 {
public void method(B1.C[] c) { }
@@ -1,7 +1,7 @@
// "Add Method Body" "true"
class a {
void f() {
<selection>//To change body of created methods use File | Settings | File Templates.</selection><caret>
<caret><selection>//To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -1,7 +1,7 @@
// "Add Method Body" "true"
class a {
String f() {
<selection>return null; //To change body of created methods use File | Settings | File Templates.</selection><caret>
<caret><selection>return null; //To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -1,7 +1,7 @@
// "Add Method Body" "true"
class a {
a() {
<selection>//To change body of created methods use File | Settings | File Templates.</selection><caret>
<caret><selection>//To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -1,7 +1,7 @@
// "Add Method Body" "true"
class a {
String f() {
<selection>return null; //To change body of created methods use File | Settings | File Templates.</selection><caret>
<caret><selection>return null; //To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -7,7 +7,7 @@ class Test {
class Inner {
public Inner(String a) {
<selection>//To change body of created methods use File | Settings | File Templates.</selection><caret>
<caret><selection>//To change body of created methods use File | Settings | File Templates.</selection>
}
}
}
@@ -5,6 +5,6 @@ public class Test {
}
private void test() {
<selection>//To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>//To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -5,6 +5,6 @@ public class Test {
}
private void test() {
<selection>//To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>//To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -5,6 +5,6 @@ public class Test {
}
private void test() {
<selection>//To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>//To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -6,6 +6,6 @@ public class Test {
}
private void test() {
<selection>//To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>//To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -5,6 +5,6 @@ public class Test {
}
private <T extends String> void bar(T t1, T t2) {
<selection>//To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>//To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -5,6 +5,6 @@ public class Test {
}
private boolean test() {
<selection>return false; //To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>return false; //To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -6,6 +6,6 @@ class A {
}
private String bar() {
<selection>return null; //To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>return null; //To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -8,7 +8,7 @@ public class Test {
}
private boolean someMethod(Object o) {
<selection>return false; //To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>return false; //To change body of created methods use File | Settings | File Templates.</selection>
}
};
}
@@ -10,6 +10,6 @@ class A {
}
class B {
public static void f(Runnable runnable) {
<selection>//To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>//To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -5,7 +5,7 @@ public class A {
}
private static int f() {
<selection>return 0; //To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>return 0; //To change body of created methods use File | Settings | File Templates.</selection>
}
public A(int i) {
@@ -1,7 +1,7 @@
// "Create Method 'get'" "true"
class Generic<T> {
public T get() {
<selection>return null; //To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>return null; //To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -4,7 +4,7 @@ interface Int<T> {
class A1<T> implements Int<T> {
public void foo(Int<T> c) {
<selection>//To change body of created methods use File | Settings | File Templates.</selection><caret>
<caret><selection>//To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -8,7 +8,7 @@ class R implements Comparable<R> {
class A1<T> {
public T foo() {
<selection>return null; //To change body of created methods use File | Settings | File Templates.<caret></selection>
<caret><selection>return null; //To change body of created methods use File | Settings | File Templates.</selection>
}
}
@@ -0,0 +1,11 @@
public class RefactorBug {
public static void som<caret>ething(int a, float b) {
}
/**
* @see #something(int, float)
*/
public static void somethingElse() {
}
}
@@ -0,0 +1,11 @@
public class RefactorBug {
public static void bar(int a, float b) {
}
/**
* @see #bar(int, float)
*/
public static void somethingElse() {
}
}
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight;
@@ -14,7 +29,7 @@ xxx<caret>
}
public void testEmpty() {
doTest '<caret>', "txt", '\n<caret>'
doTest '<caret>', "txt", '<caret>'
}
private void doTest(String before, @NonNls String ext, String after) {
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.daemon;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
@@ -11,17 +26,13 @@ import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.openapi.extensions.ExtensionPoint;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.impl.source.tree.injected.JavaConcatenationInjectorManager;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.fixtures.impl.CodeInsightTestFixtureImpl;
import com.intellij.util.ThrowableRunnable;
import org.jetbrains.annotations.NonNls;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class LightAdvHighlightingPerformanceTest extends LightDaemonAnalyzerTestCase {
@@ -74,9 +85,12 @@ public class LightAdvHighlightingPerformanceTest extends LightDaemonAnalyzerTest
}
}
private String getFilePath(final String suffix) {
return LightAdvHighlightingTest.BASE_PATH + "/" + getTestName(true) + suffix + ".java";
}
private List<HighlightInfo> doTest(final int maxMillis) throws Exception {
@NonNls String filePath = LightAdvHighlightingTest.BASE_PATH + "/" + getTestName(false) + ".java";
configureByFile(filePath);
configureByFile(getFilePath(""));
PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
getFile().getText(); //to load text
@@ -92,32 +106,23 @@ public class LightAdvHighlightingPerformanceTest extends LightDaemonAnalyzerTest
infos.addAll(h);
}
}).cpuBound().usesAllCPUCores().assertTiming();
return DaemonAnalyzerTestCase.filter(infos, HighlightSeverity.ERROR);
}
public void testaThinlet() throws Exception {
public void testAThinlet() throws Exception {
List<HighlightInfo> errors = doTest(Math.max(10000, 24000 - JobSchedulerImpl.CORES_COUNT * 1000));
dump("thinlet", errors);
assertEquals(1230, errors.size());
if (1226 != errors.size()) {
doTest(getFilePath("_hl"), false, false);
fail("Actual: " + errors.size());
}
}
private static void dump(String msg, List<HighlightInfo> errors) {
if (true) return;
Collections.sort(errors, new Comparator<HighlightInfo>() {
@Override
public int compare(HighlightInfo o1, HighlightInfo o2) {
return o1.toString().compareTo(o2.toString());
}
});
final String s = StringUtil.join(errors, StringUtil.createToStringFunction(HighlightInfo.class), "\n");
System.out.println(msg+":\n-----------------------------------------");
System.out.println(s);
System.out.println("\n--------------------------------------------");
}
public void testaClassLoader() throws Exception {
public void testAClassLoader() throws Exception {
List<HighlightInfo> errors = doTest(Math.max(1000, 10000 - JobSchedulerImpl.CORES_COUNT * 1000));
dump("classloader", errors);
assertEquals(178, errors.size());
if (173 != errors.size()) {
doTest(getFilePath("_hl"), false, false);
fail("Actual: " + errors.size());
}
}
}
@@ -53,6 +53,10 @@ public class RenameMembersInplaceTest extends LightCodeInsightTestCase {
public void testClassWithMultipleConstructors() throws Exception {
doTestInplaceRename("Bar");
}
public void testMethodWithJavadocRef() throws Exception {
doTestInplaceRename("bar");
}
public void testConflictingMethodName() throws Exception {
try {
@@ -82,7 +82,7 @@ public abstract class LightDaemonAnalyzerTestCase extends LightCodeInsightTestCa
protected void doTestConfiguredFile(boolean checkWarnings, boolean checkInfos, @Nullable String filePath) {
getJavaFacade().setAssertOnFileLoadingFilter(VirtualFileFilter.NONE);
ExpectedHighlightingData data = new ExpectedHighlightingData(getEditor().getDocument(),checkWarnings, checkInfos);
ExpectedHighlightingData data = new ExpectedHighlightingData(getEditor().getDocument(), checkWarnings, checkInfos);
checkHighlighting(data, composeLocalPath(filePath));
}
@@ -1,5 +1,6 @@
package org.jetbrains.jps.incremental;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.jps.idea.OwnServiceLoader;
import java.util.*;
@@ -65,6 +66,10 @@ public class BuilderRegistry {
return Collections.unmodifiableList(myModuleLevelBuilders.get(category)); // todo
}
public List<ModuleLevelBuilder> getAllModuleLevelBuilders() {
return ContainerUtil.concat(myModuleLevelBuilders.values());
}
public List<ProjectLevelBuilder> getProjectLevelBuilders() {
return myProjectLevelBuilders;
}
@@ -0,0 +1,109 @@
package org.jetbrains.jps.incremental;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.jps.Module;
import org.jetbrains.jps.ModuleChunk;
import org.jetbrains.jps.incremental.fs.RootDescriptor;
import java.io.File;
import java.util.*;
/**
* @author nik
*/
public class CompilerEncodingConfiguration {
private final Map<String, String> myFilePathToCharset;
private final ModuleRootsIndex myRootsIndex;
private Map<String, Set<String>> myModuleCharsetMap;
public CompilerEncodingConfiguration(Map<String, String> filePathToCharset, ModuleRootsIndex rootsIndex) {
myFilePathToCharset = filePathToCharset;
myRootsIndex = rootsIndex;
}
public Map<String, Set<String>> getModuleCharsetMap() {
if (myModuleCharsetMap == null) {
myModuleCharsetMap = computeModuleCharsetMap();
}
return myModuleCharsetMap;
}
private Map<String, Set<String>> computeModuleCharsetMap() {
final Map<String, Set<String>> map = new THashMap<String, Set<String>>();
final List<ModuleLevelBuilder> builders = BuilderRegistry.getInstance().getAllModuleLevelBuilders();
for (Map.Entry<String, String> entry : myFilePathToCharset.entrySet()) {
final String filePath = entry.getKey();
final String charset = entry.getValue();
File file = new File(FileUtil.toSystemDependentName(filePath));
if (charset == null || (!file.isDirectory() && !shouldHonorEncodingForCompilation(builders, file))) continue;
final RootDescriptor rootDescriptor = myRootsIndex.getModuleAndRoot(file);
if (rootDescriptor == null) continue;
final String module = rootDescriptor.module;
Set<String> set = map.get(module);
if (set == null) {
set = new LinkedHashSet<String>();
map.put(module, set);
final File sourceRoot = rootDescriptor.root;
File current = FileUtil.getParentFile(file);
String parentCharset = null;
while (current != null) {
final String currentCharset = myFilePathToCharset.get(FileUtil.toSystemIndependentName(current.getAbsolutePath()));
if (currentCharset != null) {
parentCharset = currentCharset;
}
if (FileUtil.filesEqual(current, sourceRoot)) {
break;
}
current = FileUtil.getParentFile(current);
}
if (parentCharset != null) {
set.add(parentCharset);
}
}
set.add(charset);
}
return map;
}
private static boolean shouldHonorEncodingForCompilation(List<ModuleLevelBuilder> builders, File file) {
for (ModuleLevelBuilder builder : builders) {
if (builder.shouldHonorFileEncodingForCompilation(file)) {
return true;
}
}
return false;
}
@Nullable
public String getPreferredModuleChunkEncoding(@NotNull ModuleChunk moduleChunk) {
for (Module module : moduleChunk.getModules()) {
final Set<String> encodings = getModuleCharsetMap().get(module.getName());
final String encoding = ContainerUtil.getFirstItem(encodings, null);
if (encoding != null) {
return encoding;
}
}
return moduleChunk.getProject().getProjectCharset();
}
@NotNull
public Set<String> getAllModuleChunkEncodings(@NotNull ModuleChunk moduleChunk) {
final Map<String, Set<String>> map = getModuleCharsetMap();
Set<String> encodings = new HashSet<String>();
for (Module module : moduleChunk.getModules()) {
final Set<String> moduleEncodings = map.get(module.getName());
if (moduleEncodings != null) {
encodings.addAll(moduleEncodings);
}
}
return encodings;
}
}
@@ -221,31 +221,6 @@ public class IncProjectBuilder {
context.processMessage(new ProgressMessage("Running 'after' tasks"));
runTasks(context, myBuilderRegistry.getAfterTasks());
final JavaBuilderLogger logger = context.getLoggingManager().getJavaBuilderLogger();
if (logger.isEnabled()) {
final File flag = new File(Utils.getSystemRoot() + File.separator + "dumpSnapshot");
if (flag.exists()) {
final Mappings mappings = myProjectDescriptor.dataManager.getMappings();
final String fileName =
Utils.getSystemRoot() + File.separator + "snapshot-" + new SimpleDateFormat("dd-MM-yy(hh:mm:ss)").format(new Date()) + ".log";
try {
final PrintStream stream = new PrintStream(fileName);
stream.println("Mappings:");
mappings.toStream(stream);
stream.println("End Of Mappings");
stream.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
context.processMessage(new ProgressMessage("Finished, saving caches..."));
}
@@ -41,6 +41,10 @@ public abstract class ModuleLevelBuilder extends Builder {
public abstract ExitCode build(CompileContext context, ModuleChunk chunk) throws ProjectBuildException;
public boolean shouldHonorFileEncodingForCompilation(File file) {
return false;
}
public final BuilderCategory getCategory() {
return myCategory;
}
@@ -38,7 +38,8 @@ import org.jetbrains.jps.incremental.storage.BuildDataManager;
import org.jetbrains.jps.incremental.storage.SourceToFormMapping;
import org.jetbrains.jps.javac.*;
import javax.tools.*;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
import java.io.*;
import java.net.MalformedURLException;
import java.net.ServerSocket;
@@ -223,6 +224,11 @@ public class JavaBuilder extends ModuleLevelBuilder {
}
}
@Override
public boolean shouldHonorFileEncodingForCompilation(File file) {
return JAVA_SOURCES_FILTER.accept(file) || FORM_SOURCES_FILTER.accept(file);
}
@Nullable
private static File getBoundSource(File srcRoot, File formFile) throws IOException {
final String boundClassName = FormsParsing.readBoundClassName(formFile);
@@ -484,20 +490,22 @@ public class JavaBuilder extends ModuleLevelBuilder {
}
private static int convertToNumber(final String ver) {
final String prefix = "1.";
if (ver.startsWith(prefix)) {
final String versionNumberString;
final int dotIndex = ver.indexOf(".", prefix.length());
if (dotIndex > 0) {
versionNumberString = ver.substring(prefix.length(), dotIndex);
}
else {
versionNumberString = ver.substring(prefix.length());
}
try {
return Integer.parseInt(versionNumberString);
}
catch (NumberFormatException ignored) {
if (ver != null) {
final String prefix = "1.";
if (ver.startsWith(prefix)) {
final String versionNumberString;
final int dotIndex = ver.indexOf(".", prefix.length());
if (dotIndex > 0) {
versionNumberString = ver.substring(prefix.length(), dotIndex);
}
else {
versionNumberString = ver.substring(prefix.length());
}
try {
return Integer.parseInt(versionNumberString);
}
catch (NumberFormatException ignored) {
}
}
}
return 0;
@@ -579,7 +587,7 @@ public class JavaBuilder extends ModuleLevelBuilder {
private static List<String> getCompilationVMOptions(CompileContext context) {
List<String> cached = JAVAC_VM_OPTIONS.get(context);
if (cached == null) {
loadJavacOptions(context);
loadCommonJavacOptions(context);
cached = JAVAC_VM_OPTIONS.get(context);
}
return cached;
@@ -588,10 +596,28 @@ public class JavaBuilder extends ModuleLevelBuilder {
private static List<String> getCompilationOptions(CompileContext context, ModuleChunk chunk) {
List<String> cached = JAVAC_OPTIONS.get(context);
if (cached == null) {
loadJavacOptions(context);
loadCommonJavacOptions(context);
cached = JAVAC_OPTIONS.get(context);
}
final List<String> options = new ArrayList<String>(cached);
if (!isEncodingSet(options)) {
final CompilerEncodingConfiguration config = context.getProjectDescriptor().getEncodingConfiguration();
final String encoding = config.getPreferredModuleChunkEncoding(chunk);
if (config.getAllModuleChunkEncodings(chunk).size() > 1) {
final StringBuilder msgBuilder = new StringBuilder();
msgBuilder.append("Multiple encodings set for module chunk ").append(getChunkPresentableName(chunk));
if (encoding != null) {
msgBuilder.append("\n\"").append(encoding).append("\" will be used by compiler");
}
context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.INFO, msgBuilder.toString()));
}
if (encoding != null) {
options.add("-encoding");
options.add(encoding);
}
}
final String langlevel = chunk.getModules().iterator().next().getLanguageLevel();
if (!StringUtil.isEmpty(langlevel)) {
options.add("-source");
@@ -639,6 +665,16 @@ public class JavaBuilder extends ModuleLevelBuilder {
return options;
}
private static boolean isEncodingSet(List<String> options) {
for (String option : options) {
if ("-encoding".equals(option)) {
return true;
}
}
return false;
}
private static int getCompilerSdkVersion(CompileContext context) {
final Integer cached = JAVA_COMPILER_VERSION_KEY.get(context);
if (cached != null) {
@@ -668,7 +704,7 @@ public class JavaBuilder extends ModuleLevelBuilder {
return config.getProjectBytecodeTarget();
}
private static void loadJavacOptions(CompileContext context) {
private static void loadCommonJavacOptions(CompileContext context) {
final List<String> options = new ArrayList<String>();
final List<String> vmOptions = new ArrayList<String>();
@@ -689,7 +725,6 @@ public class JavaBuilder extends ModuleLevelBuilder {
}
final String customArgs = javacOpts.get("ADDITIONAL_OPTIONS_STRING");
boolean isEncodingSet = false;
if (customArgs != null) {
final StringTokenizer tokenizer = new StringTokenizer(customArgs, " \t\r\n");
while (tokenizer.hasMoreTokens()) {
@@ -703,17 +738,9 @@ public class JavaBuilder extends ModuleLevelBuilder {
else {
options.add(token);
}
if ("-encoding".equals(token)) {
isEncodingSet = true;
}
}
}
if (!isEncodingSet && !StringUtil.isEmpty(project.getProjectCharset())) {
options.add("-encoding");
options.add(project.getProjectCharset());
}
JAVAC_OPTIONS.set(context, options);
JAVAC_VM_OPTIONS.set(context, vmOptions);
}
@@ -5,6 +5,7 @@ import org.jetbrains.jps.Module;
import org.jetbrains.jps.Project;
import org.jetbrains.jps.Sdk;
import org.jetbrains.jps.incremental.BuildLoggingManager;
import org.jetbrains.jps.incremental.CompilerEncodingConfiguration;
import org.jetbrains.jps.incremental.ModuleRootsIndex;
import org.jetbrains.jps.incremental.fs.BuildFSState;
import org.jetbrains.jps.incremental.storage.BuildDataManager;
@@ -27,6 +28,7 @@ public final class ProjectDescriptor {
public ModuleRootsIndex rootsIndex;
private int myUseCounter = 1;
private Set<JavaSdk> myProjectJavaSdks;
private CompilerEncodingConfiguration myEncodingConfiguration;
public ProjectDescriptor(Project project,
BuildFSState fsState,
@@ -40,6 +42,7 @@ public final class ProjectDescriptor {
myLoggingManager = loggingManager;
this.rootsIndex = new ModuleRootsIndex(project);
myProjectJavaSdks = new HashSet<JavaSdk>();
myEncodingConfiguration = new CompilerEncodingConfiguration(project.getFilePathToCharset(), rootsIndex);
for (Module module : project.getModules().values()) {
final Sdk sdk = module.getSdk();
if (sdk instanceof JavaSdk && !myProjectJavaSdks.contains(sdk)) {
@@ -51,6 +54,10 @@ public final class ProjectDescriptor {
}
}
public CompilerEncodingConfiguration getEncodingConfiguration() {
return myEncodingConfiguration;
}
public Set<JavaSdk> getProjectJavaSdks() {
return myProjectJavaSdks;
}
@@ -22,6 +22,7 @@ class Project {
final IgnoredFilePatterns ignoredFilePatterns = new IgnoredFilePatterns()
String projectCharset; // contains project charset, if not specified default charset will be used (used by compilers)
Map<String, String> filePathToCharset = [:];
def Project() {
}
@@ -30,7 +30,7 @@ class FacetLoader {
}
}
private static FacetTypeService findFacetType(String typeId) {
private static synchronized FacetTypeService findFacetType(String typeId) {
if (facetTypes == null) {
facetTypes = [:]
facetTypeLoader.each {FacetTypeService type ->
@@ -340,6 +340,10 @@ public class IdeaProjectLoader {
if ("PROJECT".equals(url)) {
project.projectCharset = charset;
}
else {
def path = projectMacroExpander.expandMacros(IdeaProjectLoadingUtil.pathFromUrl(url));
project.filePathToCharset[path] = charset;
}
}
}
@@ -24,6 +24,7 @@ import com.intellij.openapi.extensions.PluginDescriptor;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressIndicatorProvider;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.UserDataHolderBase;
@@ -40,8 +41,8 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.picocontainer.*;
import org.picocontainer.defaults.*;
import org.picocontainer.defaults.CachingComponentAdapter;
import org.picocontainer.defaults.ConstructorInjectionComponentAdapter;
import java.lang.reflect.Array;
import java.util.ArrayList;
@@ -443,13 +444,14 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements
try {
final Class<?> interfaceClass = Class.forName(config.getInterfaceClass(), true, loader);
final Class<?> implementationClass = Class.forName(config.getImplementationClass(), true, loader);
final Class<?> implementationClass = Comparing.equal(config.getInterfaceClass(), config.getImplementationClass()) ?
interfaceClass : Class.forName(config.getImplementationClass(), true, loader);
if (myInterfaceToClassMap.get(interfaceClass) != null) {
throw new Error("ComponentSetup for component " + interfaceClass.getName() + " already registered");
}
getPicoContainer().registerComponent(new ComponentConfigComponentAdapter(config));
getPicoContainer().registerComponent(new ComponentConfigComponentAdapter(config, implementationClass));
myInterfaceToClassMap.put(interfaceClass, implementationClass);
myComponentClassToConfig.put(implementationClass, config);
myComponentInterfaces.add(interfaceClass);
@@ -559,12 +561,57 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements
private class ComponentConfigComponentAdapter implements ComponentAdapter {
private final ComponentConfig myConfig;
private ComponentAdapter myDelegate;
private final ComponentAdapter myDelegate;
private boolean myInitialized = false;
private boolean myInitializing = false;
public ComponentConfigComponentAdapter(final ComponentConfig config) {
public ComponentConfigComponentAdapter(final ComponentConfig config, Class<?> implementationClass) {
myConfig = config;
final String componentKey = config.getInterfaceClass();
myDelegate = new CachingComponentAdapter(new ConstructorInjectionComponentAdapter(componentKey, implementationClass, null, true)) {
@Override
public Object getComponentInstance(PicoContainer picoContainer) throws PicoInitializationException, PicoIntrospectionException {
Object componentInstance = null;
try {
long startTime = myInitialized ? 0 : System.nanoTime();
componentInstance = super.getComponentInstance(picoContainer);
if (!myInitialized) {
if (myInitializing) {
if (myConfig.pluginDescriptor != null) {
LOG.error(new PluginException("Cyclic component initialization: " + componentKey, myConfig.pluginDescriptor.getPluginId()));
}
else {
LOG.error(new Throwable("Cyclic component initialization: " + componentKey));
}
}
myInitializing = true;
myComponentsRegistry.registerComponentInstance(componentInstance);
initComponent(componentInstance);
long endTime = System.nanoTime();
long ms = (endTime - startTime) / 1000000;
if (ms > 10) {
if (logSlowComponents()) {
LOG.info(componentInstance.getClass().getName() + " initialized in " + ms + " ms");
}
}
myInitializing = false;
myInitialized = true;
}
}
catch (ProcessCanceledException e) {
throw e;
}
catch (StateStorageException e) {
throw e;
}
catch (Throwable t) {
handleInitComponentError(t, componentInstance == null, componentKey);
}
return componentInstance;
}
};
}
@Override
@@ -594,92 +641,7 @@ public abstract class ComponentManagerImpl extends UserDataHolderBase implements
}
private ComponentAdapter getDelegate() {
if (myDelegate == null) {
final Object componentKey = getComponentKey();
ClassLoader loader = myConfig.getClassLoader();
Class<?> implementationClass = null;
try {
implementationClass = Class.forName(myConfig.getImplementationClass(), true, loader);
}
catch (Exception e) {
@NonNls final String message = "Error while registering component: " + myConfig;
if (myConfig.pluginDescriptor != null) {
LOG.error(message, new PluginException(e, myConfig.pluginDescriptor.getPluginId()));
}
else {
LOG.error(message, e);
}
}
catch (Error e) {
if (myConfig.pluginDescriptor != null) {
LOG.error(new PluginException(e, myConfig.pluginDescriptor.getPluginId()));
}
else {
throw e;
}
}
assert implementationClass != null;
myDelegate = new CachingComponentAdapter(new ConstructorInjectionComponentAdapter(componentKey, implementationClass, null, true)) {
@Override
public Object getComponentInstance(PicoContainer picoContainer) throws PicoInitializationException, PicoIntrospectionException {
Object componentInstance = null;
try {
long startTime = myInitialized ? 0 : System.nanoTime();
componentInstance = super.getComponentInstance(picoContainer);
if (!myInitialized) {
if (myInitializing) {
if (myConfig.pluginDescriptor != null) {
LOG.error(new PluginException("Cyclic component initialization: " + componentKey, myConfig.pluginDescriptor.getPluginId()));
}
else {
LOG.error(new Throwable("Cyclic component initialization: " + componentKey));
}
}
myInitializing = true;
myComponentsRegistry.registerComponentInstance(componentInstance);
initComponent(componentInstance);
long endTime = System.nanoTime();
long ms = (endTime - startTime) / 1000000;
if (ms > 10) {
if (logSlowComponents()) {
LOG.info(componentInstance.getClass().getName() + " initialized in " + ms + " ms");
}
}
myInitializing = false;
myInitialized = true;
}
}
catch (ProcessCanceledException e) {
throw e;
}
catch (StateStorageException e) {
throw e;
}
catch (Throwable t) {
handleInitComponentError(t, componentInstance == null, componentKey.toString());
}
return componentInstance;
}
};
}
return myDelegate;
}
}
public final int hashCode() {
return super.hashCode();
}
@SuppressWarnings({"EqualsWhichDoesntCheckParameterClass"})
public final boolean equals(Object obj) {
return super.equals(obj);
}
}
@@ -0,0 +1,44 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.popup.util;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: zajac
* Date: 5/9/12
* Time: 5:34 AM
* To change this template use File | Settings | File Templates.
*/
public interface DetailView {
void updateWithItem(ItemWrapper wrapper);
Editor getEditor();
void navigateInPreviewEditor(VirtualFile file, LogicalPosition positionToNavigate);
JPanel getDetailPanel();
void setDetailPanel(@Nullable JPanel panel);
void clearEditor();
}
@@ -0,0 +1,48 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.popup.util;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.ui.ColoredListCellRenderer;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: zajac
* Date: 5/6/12
* Time: 2:05 AM
* To change this template use File | Settings | File Templates.
*/
public interface ItemWrapper {
void setupRenderer(ColoredListCellRenderer renderer, Project project, boolean selected);
void updateMnemonicLabel(JLabel label);
void execute(Project project, JBPopup popup);
String speedSearchText();
@Nullable
String footerText();
void updateDetailView(DetailView panel);
boolean allowedToRemove();
void removed(Project project);
}
@@ -0,0 +1,82 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.popup.util;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.ui.ColoredListCellRenderer;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: zajac
* Date: 11.05.12
* Time: 21:55
* To change this template use File | Settings | File Templates.
*/
public class SplitterItem implements ItemWrapper {
private String myText;
public SplitterItem(String text) {
myText = text;
}
public String getText() {
return myText;
}
@Override
public void setupRenderer(ColoredListCellRenderer renderer, Project project, boolean selected) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void updateMnemonicLabel(JLabel label) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void execute(Project project, JBPopup popup) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String speedSearchText() {
return ""; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String footerText() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void updateDetailView(DetailView panel) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean allowedToRemove() {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void removed(Project project) {
//To change body of implemented methods use File | Settings | File Templates.
}
}
@@ -90,7 +90,7 @@ public class BaseAnalysisActionDialog extends DialogWrapper {
myAnalysisOptions.ANALYZE_TEST_SOURCES = scope.isAnalyzeTestsByDefault();
}
myProject = project;
myFileName = scope.getShortenName();
myFileName = scope.getScopeType() == AnalysisScope.PROJECT || scope.getScopeType() == AnalysisScope.MODULE ? null : scope.getShortenName();
myModuleName = moduleName;
myRememberScope = rememberScope;
myAnalysisNoon = analysisNoon;
@@ -141,8 +141,12 @@ public class BaseAnalysisActionDialog extends DialogWrapper {
myChangeLists.setVisible(hasVCS);
//file/package/directory/module scope
myFileButton.setText(myFileName);
myFileButton.setMnemonic(myFileName.charAt(getSelectedScopeMnemonic()));
if (myFileName != null) {
myFileButton.setText(myFileName);
myFileButton.setMnemonic(myFileName.charAt(getSelectedScopeMnemonic()));
} else {
myFileButton.setVisible(false);
}
VirtualFile file = PsiUtilBase.getVirtualFile(myContext);
ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
@@ -165,9 +169,10 @@ public class BaseAnalysisActionDialog extends DialogWrapper {
myScopeCombo.init(myProject, searchInLib, true, preselect);
//correct selection
myProjectButton.setSelected(myRememberScope && myAnalysisOptions.SCOPE_TYPE == AnalysisScope.PROJECT);
myFileButton.setSelected(!myRememberScope ||
myAnalysisOptions.SCOPE_TYPE != AnalysisScope.PROJECT && !useModuleScope && myAnalysisOptions.SCOPE_TYPE != AnalysisScope.CUSTOM && !useUncommitedFiles);
myProjectButton.setSelected(myRememberScope && myAnalysisOptions.SCOPE_TYPE == AnalysisScope.PROJECT || myFileName == null);
myFileButton.setSelected(myFileName != null &&
(!myRememberScope ||
myAnalysisOptions.SCOPE_TYPE != AnalysisScope.PROJECT && !useModuleScope && myAnalysisOptions.SCOPE_TYPE != AnalysisScope.CUSTOM && !useUncommitedFiles));
myScopeCombo.setEnabled(myCustomScopeButton.isSelected());
@@ -165,7 +165,7 @@ public class InitialConfigurationDialog extends DialogWrapper {
private void createUIComponents() {
myColorPreviewPanel = new AbstractTitledSeparatorWithIcon(IconLoader.getIcon("/general/comboArrowRight.png"),
IconLoader.getIcon("/general/comboArrowDown.png"),
"Click to preview", true, false) {
"Click to preview") {
private int myAddedWidth;
@@ -65,6 +65,8 @@ public abstract class RunManagerEx extends RunManager {
@NotNull
public abstract List<BeforeRunTask> getBeforeRunTasks(RunConfiguration settings);
public abstract void setBeforeRunTasks(RunConfiguration runConfiguration, List<BeforeRunTask> tasks, boolean addEnabledTemplateTasksIfAbsent);
@NotNull
public abstract <T extends BeforeRunTask> List<T> getBeforeRunTasks(RunConfiguration settings, Key<T> taskProviderID);
@@ -256,7 +256,6 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable,
checkRecentsLimit();
mySharedConfigurations.put(newId, shared);
getTemplateBeforeRunTask(configuration);
setBeforeRunTasks(configuration, tasks, addEnabledTemplateTasksIfAbsent);
if (existingSettings == settings) {
@@ -830,10 +829,10 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable,
if (tasks != null) {
return getCopies(tasks);
}
return getTemplateBeforeRunTask(settings);
return getTemplateBeforeRunTasks(settings);
}
private List<BeforeRunTask> getTemplateBeforeRunTask(RunConfiguration settings) {
private List<BeforeRunTask> getTemplateBeforeRunTasks(RunConfiguration settings) {
final RunnerAndConfigurationSettings template = getConfigurationTemplate(settings.getFactory());
final List<BeforeRunTask> templateTasks = myConfigurationToBeforeTasksMap.get(template.getConfiguration());
if (templateTasks != null) {
@@ -879,7 +878,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable,
public final void setBeforeRunTasks(final RunConfiguration runConfiguration, @NotNull List<BeforeRunTask> tasks, boolean addEnabledTemplateTasksIfAbsent) {
List<BeforeRunTask> result = new ArrayList<BeforeRunTask>(tasks);
if (addEnabledTemplateTasksIfAbsent) {
List<BeforeRunTask> templates = getTemplateBeforeRunTask(runConfiguration);
List<BeforeRunTask> templates = getTemplateBeforeRunTasks(runConfiguration);
Set<Key<BeforeRunTask>> idsToSet = new HashSet<Key<BeforeRunTask>>();
for (BeforeRunTask task : tasks) {
idsToSet.add(task.getProviderId());
@@ -902,7 +901,7 @@ public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable,
}
public void addConfiguration(final RunnerAndConfigurationSettings settings, final boolean isShared) {
addConfiguration(settings, isShared, new ArrayList<BeforeRunTask>(), false);
addConfiguration(settings, isShared, getTemplateBeforeRunTasks(settings.getConfiguration()), false);
}
public static RunManagerImpl getInstanceImpl(final Project project) {
@@ -53,10 +53,6 @@ public class
@Override
protected void paintLastGhost(Graphics2D g2d) {}
public boolean isGhostsAlwaysVisible() {
return false;
}
protected void doPaintInactive(Graphics2D g2d,
boolean leftGhostExists,
TabLabel label,
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -258,7 +258,10 @@ public class RunnerContentUi implements ContentUI, Disposable, CellTransform.Fac
Disposer.register((Disposable)myRunnerUi, manager);
manager.getComponent();
} else {
DockManager.getInstance(myProject).register(this);
final DockManager dockManager = DockManager.getInstance(myProject);
if (dockManager != null) { //default project
dockManager.register(this);
}
}
}
@@ -0,0 +1,131 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.bookmarks;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.FileColorManager;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.popup.util.DetailView;
import com.intellij.ui.popup.util.ItemWrapper;
import javax.swing.*;
import java.awt.*;
/**
* Created with IntelliJ IDEA.
* User: zajac
* Date: 5/6/12
* Time: 2:06 AM
* To change this template use File | Settings | File Templates.
*/
public class BookmarkItem implements ItemWrapper {
private final Bookmark myBookmark;
public BookmarkItem(Bookmark bookmark) {
myBookmark = bookmark;
}
public Bookmark getBookmark() {
return myBookmark;
}
public void setupRenderer(ColoredListCellRenderer renderer, Project project, boolean selected) {
VirtualFile file = myBookmark.getFile();
PsiManager psiManager = PsiManager.getInstance(project);
PsiElement fileOrDir = file.isDirectory() ? psiManager.findDirectory(file) : psiManager.findFile(file);
if (fileOrDir != null) {
renderer.setIcon(fileOrDir.getIcon(Iconable.ICON_FLAG_CLOSED));
}
FileStatus fileStatus = FileStatusManager.getInstance(project).getStatus(file);
TextAttributes attributes = new TextAttributes(fileStatus.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN);
renderer.append(file.getName(), SimpleTextAttributes.fromTextAttributes(attributes));
if (myBookmark.getLine() >= 0) {
renderer.append(":", SimpleTextAttributes.GRAYED_ATTRIBUTES);
renderer.append(String.valueOf(myBookmark.getLine() + 1), SimpleTextAttributes.GRAYED_ATTRIBUTES);
}
if (!selected) {
FileColorManager colorManager = FileColorManager.getInstance(project);
if (fileOrDir instanceof PsiFile) {
Color color = colorManager.getRendererBackground((PsiFile)fileOrDir);
if (color != null) {
renderer.setBackground(color);
}
}
}
String description = myBookmark.getDescription();
if (description != null) {
renderer.append(" " + description, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
}
}
public void updateMnemonicLabel(JLabel label) {
final char mnemonic = myBookmark.getMnemonic();
if (mnemonic != 0) {
label.setText(Character.toString(mnemonic) + '.');
}
else {
label.setText("");
}
}
public String speedSearchText() {
return myBookmark.getFile().getName() + " " + myBookmark.getDescription();
}
public void execute(Project project, JBPopup popup) {
myBookmark.navigate();
}
public String footerText() {
return myBookmark.getFile().getPresentableUrl();
}
@Override
public void updateDetailView(final DetailView panel) {
VirtualFile file = myBookmark.getFile();
LogicalPosition positionToNavigate = new LogicalPosition(myBookmark.getLine(), 0);
panel.navigateInPreviewEditor(file, positionToNavigate);
}
@Override
public boolean allowedToRemove() {
return true;
}
@Override
public void removed(Project project) {
BookmarkManager.getInstance(project).removeBookmark(getBookmark());
}
}
@@ -20,58 +20,30 @@
package com.intellij.ide.bookmarks.actions;
import com.intellij.ide.bookmarks.Bookmark;
import com.intellij.ide.bookmarks.BookmarkItem;
import com.intellij.ide.bookmarks.BookmarkManager;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.Iconable;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.vcs.FileStatus;
import com.intellij.openapi.vcs.FileStatusManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.ui.*;
import com.intellij.ui.components.JBList;
import com.intellij.ui.popup.util.MasterDetailPopupBuilder;
import com.intellij.ui.speedSearch.FilteringListModel;
import com.intellij.util.Alarm;
import com.intellij.util.Function;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
// TODO: remove duplication with BaseShowRecentFilesAction, there's quite a bit of it
public class BookmarksAction extends AnAction implements DumbAware {
private static final Color BORDER_COLOR = Gray._135;
private final Alarm myPreviewUpdateAlarm = new Alarm();
public class BookmarksAction extends AnAction implements DumbAware, MasterDetailPopupBuilder.Delegate {
@Override
public void update(AnActionEvent e) {
@@ -89,177 +61,44 @@ public class BookmarksAction extends AnAction implements DumbAware {
final DefaultListModel model = buildModel(project);
final JLabel pathLabel = new JLabel(" ");
pathLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final Font font = pathLabel.getFont();
pathLabel.setFont(font.deriveFont((float)10));
final JBList list = new JBList(model);
list.getEmptyText().setText("No Bookmarks");
final PreviewPanel previewPanel = new PreviewPanel(project);
list.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
private String getTitle2Text(String fullText) {
int labelWidth = pathLabel.getWidth();
if (fullText == null || fullText.length() == 0) return " ";
while (pathLabel.getFontMetrics(pathLabel.getFont()).stringWidth(fullText) > labelWidth) {
int sep = fullText.indexOf(File.separatorChar, 4);
if (sep < 0) return fullText;
fullText = "..." + fullText.substring(sep);
}
return fullText;
}
public void valueChanged(final ListSelectionEvent e) {
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updatePathLabel();
}
});
}
private void updatePreviewPanel(final ItemWrapper wrapper) {
myPreviewUpdateAlarm.cancelAllRequests();
myPreviewUpdateAlarm.addRequest(new Runnable() {
public void run() {
previewPanel.updateWithItem(wrapper);
}
}, 300);
}
private void updatePathLabel() {
final Object[] values = list.getSelectedValues();
if (values != null && values.length == 1) {
ItemWrapper wrapper = (ItemWrapper)values[0];
pathLabel.setText(getTitle2Text(wrapper.footerText()));
updatePreviewPanel(wrapper);
}
else {
updatePreviewPanel(null);
pathLabel.setText(" ");
}
}
});
Runnable runnable = new Runnable() {
public void run() {
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() {
public void run() {
Object[] values = list.getSelectedValues();
if (values.length == 1) {
((ItemWrapper)values[0]).execute(project);
}
else {
for (Object value : values) {
if (value instanceof BookmarkItem) {
((BookmarkItem)value).execute(project);
}
}
}
}
});
}
};
if (list.getModel().getSize() == 0) {
list.clearSelection();
}
list.setCellRenderer(new ItemRenderer(project));
JPanel footerPanel = new JPanel(new BorderLayout()) {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(BORDER_COLOR);
g.drawLine(0, 0, getWidth(), 0);
}
};
footerPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
footerPanel.add(pathLabel);
DefaultActionGroup actions = new DefaultActionGroup();
EditBookmarkDescriptionAction editDescriptionAction = new EditBookmarkDescriptionAction(project, list);
DefaultActionGroup actions = new DefaultActionGroup();
actions.add(editDescriptionAction);
actions.add(new DeleteBookmarkAction(project, list));
actions.add(new MoveBookmarkUpAction(project, list));
actions.add(new MoveBookmarkDownAction(project, list));
ActionToolbar actionToolbar = ActionManager.getInstance().createActionToolbar("", actions, true);
actionToolbar.setReservePlaceAutoPopupIcon(false);
actionToolbar.setMinimumButtonSize(new Dimension(20, 20));
final JComponent toolBar = actionToolbar.getComponent();
toolBar.setOpaque(false);
final JBPopup popup = new PopupChooserBuilder(list).
setTitle("Bookmarks").
setMovable(true).
setAutoselectOnMouseMove(false).
setSettingButton(toolBar).
setSouthComponent(footerPanel).
setEastComponent(previewPanel).
setItemChoosenCallback(runnable).
setMayBeParent(true).
setFilteringEnabled(new Function<Object, String>() {
public String fun(Object o) {
return ((ItemWrapper)o).speedSearchText();
}
}).createPopup();
list.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
int index = list.getSelectedIndex();
if (index == -1 || index >= list.getModel().getSize()) {
return;
}
Object[] values = list.getSelectedValues();
for (Object value : values) {
if (value instanceof BookmarkItem) {
BookmarkItem item = (BookmarkItem)value;
model.removeElement(item);
if (model.getSize() > 0) {
if (model.getSize() == index) {
list.setSelectedIndex(model.getSize() - 1);
}
else if (model.getSize() > index) {
list.setSelectedIndex(index);
}
}
else {
list.clearSelection();
}
BookmarkManager.getInstance(project).removeBookmark(item.myBookmark);
}
}
}
else if (e.getModifiersEx() == 0) {
char mnemonic = e.getKeyChar();
final Bookmark bookmark = BookmarkManager.getInstance(project).findBookmarkForMnemonic(mnemonic);
if (bookmark != null) {
popup.cancel();
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() {
public void run() {
bookmark.navigate();
}
});
}
}
}
});
final JBPopup popup = new MasterDetailPopupBuilder(project).
setActionsGroup(actions).
setList(list).
setDelegate(this).createMasterDetailPopup();
editDescriptionAction.setPopup(popup);
popup.showCenteredInCurrentWindow(project);
}
@Override
public String getTitle() {
return "Bookmarks";
}
@Override
public void handleMnemonic(KeyEvent e, Project project, JBPopup popup) {
char mnemonic = e.getKeyChar();
final Bookmark bookmark = BookmarkManager.getInstance(project).findBookmarkForMnemonic(mnemonic);
if (bookmark != null) {
popup.cancel();
IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() {
public void run() {
bookmark.navigate();
}
});
}
}
private static DefaultListModel buildModel(Project project) {
final DefaultListModel model = new DefaultListModel();
@@ -270,157 +109,8 @@ public class BookmarksAction extends AnAction implements DumbAware {
return model;
}
private interface ItemWrapper {
void setupRenderer(ColoredListCellRenderer renderer, Project project, boolean selected);
void updateMnemonicLabel(JLabel label);
void execute(Project project);
String speedSearchText();
@Nullable
String footerText();
void updatePreviewPanel(PreviewPanel panel);
}
private static class BookmarkItem implements ItemWrapper {
private final Bookmark myBookmark;
private BookmarkItem(Bookmark bookmark) {
myBookmark = bookmark;
}
public void setupRenderer(ColoredListCellRenderer renderer, Project project, boolean selected) {
VirtualFile file = myBookmark.getFile();
PsiManager psiManager = PsiManager.getInstance(project);
PsiElement fileOrDir = file.isDirectory() ? psiManager.findDirectory(file) : psiManager.findFile(file);
if (fileOrDir != null) {
renderer.setIcon(fileOrDir.getIcon(Iconable.ICON_FLAG_CLOSED));
}
FileStatus fileStatus = FileStatusManager.getInstance(project).getStatus(file);
TextAttributes attributes = new TextAttributes(fileStatus.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN);
renderer.append(file.getName(), SimpleTextAttributes.fromTextAttributes(attributes));
if (myBookmark.getLine() >= 0) {
renderer.append(":", SimpleTextAttributes.GRAYED_ATTRIBUTES);
renderer.append(String.valueOf(myBookmark.getLine() + 1), SimpleTextAttributes.GRAYED_ATTRIBUTES);
}
if (!selected) {
FileColorManager colorManager = FileColorManager.getInstance(project);
if (fileOrDir instanceof PsiFile) {
Color color = colorManager.getRendererBackground((PsiFile)fileOrDir);
if (color != null) {
renderer.setBackground(color);
}
}
}
String description = myBookmark.getDescription();
if (description != null) {
renderer.append(" " + description, SimpleTextAttributes.REGULAR_BOLD_ATTRIBUTES);
}
}
public void updateMnemonicLabel(JLabel label) {
final char mnemonic = myBookmark.getMnemonic();
if (mnemonic != 0) {
label.setText(Character.toString(mnemonic) + '.');
}
else {
label.setText("");
}
}
public String speedSearchText() {
return myBookmark.getFile().getName() + " " + myBookmark.getDescription();
}
public void execute(Project project) {
myBookmark.navigate();
}
public String footerText() {
return myBookmark.getFile().getPresentableUrl();
}
public void updatePreviewPanel(final PreviewPanel panel) {
VirtualFile file = myBookmark.getFile();
Document document = FileDocumentManager.getInstance().getDocument(file);
Project project = panel.myProject;
if (document != null) {
if (panel.myEditor == null || panel.myEditor.getDocument() != document) {
panel.cleanup();
panel.myEditor = EditorFactory.getInstance().createViewer(document, project);
EditorHighlighter highlighter = EditorHighlighterFactory.getInstance()
.createEditorHighlighter(file, EditorColorsManager.getInstance().getGlobalScheme(), project);
((EditorEx)panel.myEditor).setHighlighter(highlighter);
((EditorEx)panel.myEditor).setFile(file);
panel.myEditor.getSettings().setAnimatedScrolling(false);
panel.myEditor.getSettings().setRefrainFromScrolling(false);
panel.myEditor.getSettings().setLineNumbersShown(true);
panel.myEditor.getSettings().setFoldingOutlineShown(false);
panel.add(panel.myEditor.getComponent(), BorderLayout.CENTER);
}
panel.myEditor.getCaretModel().moveToLogicalPosition(new LogicalPosition(myBookmark.getLine(), 0));
panel.validate();
panel.myEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER);
}
else {
panel.cleanup();
JLabel label = new JLabel("Navigate to selected " + (file.isDirectory() ? "directory " : "file ") + "in Project View");
label.setHorizontalAlignment(JLabel.CENTER);
panel.add(label);
}
}
}
private static class ItemRenderer extends JPanel implements ListCellRenderer {
private final Project myProject;
private final ColoredListCellRenderer myRenderer;
private ItemRenderer(Project project) {
super(new BorderLayout());
myProject = project;
setBackground(UIUtil.getListBackground());
final JLabel label = new JLabel();
label.setFont(Bookmark.MNEMONIC_FONT);
label.setPreferredSize(new JLabel("W.").getPreferredSize());
label.setOpaque(false);
if (BookmarkManager.getInstance(project).hasBookmarksWithMnemonics()) {
add(label, BorderLayout.WEST);
}
myRenderer = new ColoredListCellRenderer() {
@Override
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
if (value instanceof ItemWrapper) {
final ItemWrapper wrapper = (ItemWrapper)value;
wrapper.setupRenderer(this, myProject, selected);
wrapper.updateMnemonicLabel(label);
}
}
};
add(myRenderer, BorderLayout.CENTER);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
myRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
return this;
}
public boolean hasItemsWithMnemonic(Project project) {
return BookmarkManager.getInstance(project).hasBookmarksWithMnemonics();
}
protected static class BookmarkInContextInfo {
@@ -476,53 +166,12 @@ public class BookmarksAction extends AnAction implements DumbAware {
}
}
private static class PreviewPanel extends JPanel {
private final Project myProject;
private Editor myEditor;
private ItemWrapper myWrapper;
public PreviewPanel(Project project) {
super(new BorderLayout());
myProject = project;
setPreferredSize(new Dimension(600, 400));
}
public void updateWithItem(ItemWrapper wrapper) {
if (myWrapper != wrapper) {
myWrapper = wrapper;
if (wrapper != null) {
wrapper.updatePreviewPanel(this);
}
else {
cleanup();
repaint();
}
revalidate();
}
}
private void cleanup() {
removeAll();
if (myEditor != null) {
EditorFactory.getInstance().releaseEditor(myEditor);
myEditor = null;
}
}
@Override
public void removeNotify() {
super.removeNotify();
cleanup();
}
}
private static List<Bookmark> getSelectedBookmarks(JList list) {
static List<Bookmark> getSelectedBookmarks(JList list) {
List<Bookmark> answer = new ArrayList<Bookmark>();
for (Object value : list.getSelectedValues()) {
if (value instanceof BookmarkItem) {
answer.add(((BookmarkItem)value).myBookmark);
answer.add(((BookmarkItem)value).getBookmark());
}
else {
return Collections.emptyList();
@@ -532,135 +181,10 @@ public class BookmarksAction extends AnAction implements DumbAware {
return answer;
}
private static class EditBookmarkDescriptionAction extends AnAction {
private final JList myList;
private final Project myProject;
private JBPopup myPopup;
private EditBookmarkDescriptionAction(Project project, JList list) {
super("Edit Description", "Assign short description for the bookmark to be shown along the file name", IconLoader.getIcon("/actions/properties.png"));
myProject = project;
myList = list;
registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(SystemInfo.isMac ? "meta ENTER" : "control ENTER")), list);
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(getSelectedBookmarks(myList).size() == 1);
}
@Override
public void actionPerformed(AnActionEvent e) {
Bookmark b = getSelectedBookmarks(myList).get(0);
myPopup.setUiVisible(false);
String description = Messages
.showInputDialog(myProject, "Enter short bookmark description", "Bookmark Description", Messages.getQuestionIcon(), b.getDescription(),
new InputValidator() {
public boolean checkInput(String inputString) {
return true;
}
public boolean canClose(String inputString) {
return true;
}
});
BookmarkManager.getInstance(myProject).setDescription(b, description);
myPopup.setUiVisible(true);
myPopup.setSize(myPopup.getContent().getPreferredSize());
}
public void setPopup(JBPopup popup) {
myPopup = popup;
}
}
private static class DeleteBookmarkAction extends AnAction {
private final Project myProject;
private final JList myList;
private DeleteBookmarkAction(Project project, JList list) {
super("Delete", "Delete current bookmark", IconLoader.getIcon("/general/remove.png"));
myProject = project;
myList = list;
registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke("DELETE")), list);
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(getSelectedBookmarks(myList).size() > 0);
}
@Override
public void actionPerformed(AnActionEvent e) {
List<Bookmark> bookmarks = getSelectedBookmarks(myList);
ListUtil.removeSelectedItems(myList);
for (Bookmark bookmark : bookmarks) {
BookmarkManager.getInstance(myProject).removeBookmark(bookmark);
}
}
}
private static boolean notFiltered(JList list) {
static boolean notFiltered(JList list) {
if (!(list.getModel() instanceof FilteringListModel)) return true;
final FilteringListModel model = (FilteringListModel)list.getModel();
return model.getOriginalModel().getSize() == model.getSize();
}
private static class MoveBookmarkUpAction extends AnAction {
private final Project myProject;
private final JList myList;
private MoveBookmarkUpAction(Project project, JList list) {
super("Up", "Move current bookmark up", IconLoader.getIcon("/actions/previousOccurence.png"));
myProject = project;
myList = list;
registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(SystemInfo.isMac ? "meta UP" : "control UP")), list);
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(notFiltered(myList) && getSelectedBookmarks(myList).size() == 1 && myList.getSelectedIndex() > 0);
}
@Override
public void actionPerformed(AnActionEvent e) {
ListUtil.moveSelectedItemsUp(myList);
BookmarkManager.getInstance(myProject).moveBookmarkUp(getSelectedBookmarks(myList).get(0));
}
}
private static class MoveBookmarkDownAction extends AnAction {
private final Project myProject;
private final JList myList;
private MoveBookmarkDownAction(Project project, JList list) {
super("Down", "Move current bookmark down", IconLoader.getIcon("/actions/nextOccurence.png"));
myProject = project;
myList = list;
registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(SystemInfo.isMac ? "meta DOWN" : "control DOWN")), list);
}
@Override
public void update(AnActionEvent e) {
int modelSize = myList.getModel().getSize();
if (modelSize == 0 || !notFiltered(myList)) {
e.getPresentation().setEnabled(false);
}
else {
int lastIndex = modelSize - 1;
if (!(myList.getModel().getElementAt(lastIndex) instanceof BookmarkItem)) lastIndex--;
e.getPresentation().setEnabled(getSelectedBookmarks(myList).size() == 1 && myList.getSelectedIndex() < lastIndex);
}
}
@Override
public void actionPerformed(AnActionEvent e) {
ListUtil.moveSelectedItemsDown(myList);
BookmarkManager.getInstance(myProject).moveBookmarkDown(getSelectedBookmarks(myList).get(0));
}
}
}
@@ -0,0 +1,62 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.bookmarks.actions;
import com.intellij.ide.bookmarks.Bookmark;
import com.intellij.ide.bookmarks.BookmarkManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.ui.ListUtil;
import javax.swing.*;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: zajac
* Date: 5/6/12
* Time: 2:09 AM
* To change this template use File | Settings | File Templates.
*/
class DeleteBookmarkAction extends AnAction {
private final Project myProject;
private final JList myList;
DeleteBookmarkAction(Project project, JList list) {
super("Delete", "Delete current bookmark", IconLoader.getIcon("/general/remove.png"));
myProject = project;
myList = list;
registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke("DELETE")), list);
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(BookmarksAction.getSelectedBookmarks(myList).size() > 0);
}
@Override
public void actionPerformed(AnActionEvent e) {
List<Bookmark> bookmarks = BookmarksAction.getSelectedBookmarks(myList);
ListUtil.removeSelectedItems(myList);
for (Bookmark bookmark : bookmarks) {
BookmarkManager.getInstance(myProject).removeBookmark(bookmark);
}
}
}
@@ -0,0 +1,83 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.bookmarks.actions;
import com.intellij.ide.bookmarks.Bookmark;
import com.intellij.ide.bookmarks.BookmarkManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: zajac
* Date: 5/6/12
* Time: 2:08 AM
* To change this template use File | Settings | File Templates.
*/
class EditBookmarkDescriptionAction extends AnAction {
private final JList myList;
private final Project myProject;
private JBPopup myPopup;
EditBookmarkDescriptionAction(Project project, JList list) {
super("Edit Description", "Assign short description for the bookmark to be shown along the file name", IconLoader
.getIcon("/actions/properties.png"));
myProject = project;
myList = list;
registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(SystemInfo.isMac ? "meta ENTER" : "control ENTER")), list);
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(BookmarksAction.getSelectedBookmarks(myList).size() == 1);
}
@Override
public void actionPerformed(AnActionEvent e) {
Bookmark b = BookmarksAction.getSelectedBookmarks(myList).get(0);
myPopup.setUiVisible(false);
String description = Messages
.showInputDialog(myProject, "Enter short bookmark description", "Bookmark Description", Messages.getQuestionIcon(),
b.getDescription(), new InputValidator() {
public boolean checkInput(String inputString) {
return true;
}
public boolean canClose(String inputString) {
return true;
}
});
BookmarkManager.getInstance(myProject).setDescription(b, description);
myPopup.setUiVisible(true);
myPopup.setSize(myPopup.getContent().getPreferredSize());
}
public void setPopup(JBPopup popup) {
myPopup = popup;
}
}
@@ -0,0 +1,66 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.bookmarks.actions;
import com.intellij.ide.bookmarks.BookmarkItem;
import com.intellij.ide.bookmarks.BookmarkManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.ListUtil;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: zajac
* Date: 5/6/12
* Time: 2:09 AM
* To change this template use File | Settings | File Templates.
*/
class MoveBookmarkDownAction extends AnAction {
private final Project myProject;
private final JList myList;
MoveBookmarkDownAction(Project project, JList list) {
super("Down", "Move current bookmark down", IconLoader.getIcon("/actions/nextOccurence.png"));
myProject = project;
myList = list;
registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(SystemInfo.isMac ? "meta DOWN" : "control DOWN")), list);
}
@Override
public void update(AnActionEvent e) {
int modelSize = myList.getModel().getSize();
if (modelSize == 0 || !BookmarksAction.notFiltered(myList)) {
e.getPresentation().setEnabled(false);
}
else {
int lastIndex = modelSize - 1;
if (!(myList.getModel().getElementAt(lastIndex) instanceof BookmarkItem)) lastIndex--;
e.getPresentation().setEnabled(BookmarksAction.getSelectedBookmarks(myList).size() == 1 && myList.getSelectedIndex() < lastIndex);
}
}
@Override
public void actionPerformed(AnActionEvent e) {
ListUtil.moveSelectedItemsDown(myList);
BookmarkManager.getInstance(myProject).moveBookmarkDown(BookmarksAction.getSelectedBookmarks(myList).get(0));
}
}
@@ -0,0 +1,58 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ide.bookmarks.actions;
import com.intellij.ide.bookmarks.BookmarkManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.ui.ListUtil;
import javax.swing.*;
/**
* Created with IntelliJ IDEA.
* User: zajac
* Date: 5/6/12
* Time: 2:09 AM
* To change this template use File | Settings | File Templates.
*/
class MoveBookmarkUpAction extends AnAction {
private final Project myProject;
private final JList myList;
MoveBookmarkUpAction(Project project, JList list) {
super("Up", "Move current bookmark up", IconLoader.getIcon("/actions/previousOccurence.png"));
myProject = project;
myList = list;
registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(SystemInfo.isMac ? "meta UP" : "control UP")), list);
}
@Override
public void update(AnActionEvent e) {
e.getPresentation().setEnabled(
BookmarksAction.notFiltered(myList) && BookmarksAction.getSelectedBookmarks(myList).size() == 1 && myList.getSelectedIndex() > 0);
}
@Override
public void actionPerformed(AnActionEvent e) {
ListUtil.moveSelectedItemsUp(myList);
BookmarkManager.getInstance(myProject).moveBookmarkUp(BookmarksAction.getSelectedBookmarks(myList).get(0));
}
}
@@ -252,11 +252,9 @@ public abstract class InplaceRefactoring {
if (oldDocument != myEditor.getDocument()) {
final int exitCode = Messages.showYesNoCancelDialog(myProject, e.getMessage(), getCommandName(),
"Navigate to Started", "Cancel Started", "Cancel", Messages.getErrorIcon());
if (exitCode == -1 || exitCode == Messages.CANCEL) return true;
//todo ann: //if (exitCode == Messages.YES ) {
navigateToAlreadyStarted(oldDocument, exitCode);
return true;
//}
if (exitCode == Messages.CANCEL) return true;
navigateToAlreadyStarted(oldDocument, exitCode);
return true;
}
else {
revertState();
@@ -57,7 +57,7 @@ public class MemberInplaceRenameHandler extends VariableInplaceRenameHandler {
final RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(elementToRename);
if (processor.isInplaceRenameSupported()) {
final StartMarkAction startMarkAction = StartMarkAction.canStart(elementToRename.getProject());
if (startMarkAction == null) {
if (startMarkAction == null || processor.substituteElementToRename(elementToRename, editor) == elementToRename) {
processor.substituteElementToRename(elementToRename, editor, new Pass<PsiElement>() {
@Override
public void pass(PsiElement element) {
@@ -24,6 +24,7 @@ import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.extensions.Extensions;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
@@ -237,7 +238,10 @@ public class MemberInplaceRenamer extends VariableInplaceRenamer {
@Override
protected void revertStateOnFinish() {
((EditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).startDumb();
final Editor editor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
if (editor == FileEditorManager.getInstance(myProject).getSelectedTextEditor()) {
((EditorImpl)editor).startDumb();
}
revertState();
}
@@ -44,7 +44,6 @@ import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.TextOccurrencesUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewUtil;
import com.intellij.util.PairProcessor;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
@@ -260,8 +259,7 @@ public class VariableInplaceRenamer extends InplaceRefactoring {
LOG.error(myElementToRename);
return "Rename";
}
return RefactoringBundle.message("renaming.0.1.to.2", UsageViewUtil.getType(variable), UsageViewUtil.getDescriptiveName(variable),
variable.getName());
return RefactoringBundle.message("renaming.command.name", myInitialName);
}
@Override
@@ -0,0 +1,171 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.popup.util;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.highlighter.EditorHighlighter;
import com.intellij.openapi.editor.highlighter.EditorHighlighterFactory;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.components.JBScrollPane;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
/**
* Created with IntelliJ IDEA.
* User: zajac
* Date: 5/6/12
* Time: 2:04 AM
* To change this template use File | Settings | File Templates.
*/
public class DetailViewImpl extends JPanel implements DetailView {
private final Project myProject;
private Editor myEditor;
private ItemWrapper myWrapper;
private JPanel myDetailPanel;
private JBScrollPane myDetailScrollPanel;
private JPanel myDetailPanelWrapper;
private JLabel myNothingToShow = new JLabel("Nothing to show");
private JLabel myNothingToShowInEditor = new JLabel("Nothing to show");
public DetailViewImpl(Project project) {
super(new BorderLayout());
myProject = project;
setPreferredSize(new Dimension(600, 400));
myNothingToShow.setHorizontalAlignment(JLabel.CENTER);
myNothingToShowInEditor.setHorizontalAlignment(JLabel.CENTER);
}
@Override
public void updateWithItem(ItemWrapper wrapper) {
if (myWrapper != wrapper) {
myWrapper = wrapper;
if (wrapper != null) {
wrapper.updateDetailView(this);
}
else {
clearEditor();
repaint();
}
revalidate();
}
}
@Override
public void clearEditor() {
if (getEditor() != null) {
remove(getEditor().getComponent());
EditorFactory.getInstance().releaseEditor(getEditor());
setEditor(null);
add(myNothingToShowInEditor, BorderLayout.CENTER);
repaint();
}
}
@Override
public void removeNotify() {
super.removeNotify();
clearEditor();
}
@Override
public Editor getEditor() {
return myEditor;
}
public void setEditor(Editor editor) {
myEditor = editor;
}
@Override
public void navigateInPreviewEditor(VirtualFile file, LogicalPosition positionToNavigate) {
Document document = FileDocumentManager.getInstance().getDocument(file);
Project project = myProject;
if (document != null) {
if (getEditor() == null || getEditor().getDocument() != document) {
clearEditor();
remove(myNothingToShowInEditor);
setEditor(EditorFactory.getInstance().createViewer(document, project));
EditorHighlighter highlighter = EditorHighlighterFactory.getInstance()
.createEditorHighlighter(file, EditorColorsManager.getInstance().getGlobalScheme(), project);
((EditorEx)getEditor()).setHighlighter(highlighter);
((EditorEx)getEditor()).setFile(file);
getEditor().getSettings().setAnimatedScrolling(false);
getEditor().getSettings().setRefrainFromScrolling(false);
getEditor().getSettings().setLineNumbersShown(true);
getEditor().getSettings().setFoldingOutlineShown(false);
add(getEditor().getComponent(), BorderLayout.CENTER);
}
getEditor().getCaretModel().moveToLogicalPosition(positionToNavigate);
validate();
getEditor().getScrollingModel().scrollToCaret(ScrollType.CENTER);
}
else {
clearEditor();
JLabel label = new JLabel("Navigate to selected " + (file.isDirectory() ? "directory " : "file ") + "in Project View");
label.setHorizontalAlignment(JLabel.CENTER);
add(label);
}
}
@Override
public JPanel getDetailPanel() {
return myDetailPanel;
}
@Override
public void setDetailPanel(@Nullable final JPanel panel) {
if (panel == myDetailPanel) return;
if (panel != null) {
if (myDetailScrollPanel == null) {
myDetailPanelWrapper = new JPanel(new GridLayout(1, 1));
myDetailPanelWrapper.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
myDetailPanelWrapper.add(panel);
myDetailScrollPanel =
new JBScrollPane(myDetailPanelWrapper, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) {
@Override
public Dimension getPreferredSize() {
final Dimension size = panel.getPreferredSize();
return new Dimension(size.width, size.height + 10);
}
};
add(myDetailScrollPanel, BorderLayout.SOUTH);
} else {
myDetailPanelWrapper.removeAll();
myDetailPanelWrapper.add(panel);
}
}
else {
myDetailPanelWrapper.removeAll();
myDetailPanelWrapper.add(myNothingToShow);
}
myDetailPanel = panel;
}
}
@@ -0,0 +1,356 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.popup.util;
import com.intellij.ide.bookmarks.Bookmark;
import com.intellij.ide.bookmarks.BookmarkItem;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.ui.ColoredListCellRenderer;
import com.intellij.ui.Gray;
import com.intellij.ui.TitledSeparator;
import com.intellij.ui.components.JBList;
import com.intellij.ui.speedSearch.FilteringListModel;
import com.intellij.util.Alarm;
import com.intellij.util.Function;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
/**
* Created with IntelliJ IDEA.
* User: zajac
* Date: 5/6/12
* Time: 2:06 PM
* To change this template use File | Settings | File Templates.
*/
public class MasterDetailPopupBuilder {
private static final Color BORDER_COLOR = Gray._135;
private Project myProject;
private ActionGroup myActions;
private JBList myList;
private Delegate myDelegate;
private boolean myCloseOnEnter;
public ActionToolbar getActionToolbar() {
return myActionToolbar;
}
private ActionToolbar myActionToolbar;
public MasterDetailPopupBuilder(Project project) {
myProject = project;
}
public JBPopup createMasterDetailPopup() {
final JLabel pathLabel = new JLabel(" ");
pathLabel.setHorizontalAlignment(SwingConstants.RIGHT);
final Font font = pathLabel.getFont();
pathLabel.setFont(font.deriveFont((float)10));
final Alarm updateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
final DetailViewImpl detailView = new DetailViewImpl(myProject);
myList.setCellRenderer(new ItemRenderer(myProject));
final ListSelectionModel selectionModel = myList.getSelectionModel();
selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final boolean directionUp[] = new boolean[1];
selectionModel.addListSelectionListener(new ListSelectionListener() {
private String getTitle2Text(String fullText) {
int labelWidth = pathLabel.getWidth();
if (fullText == null || fullText.length() == 0) return " ";
while (pathLabel.getFontMetrics(pathLabel.getFont()).stringWidth(fullText) > labelWidth) {
int sep = fullText.indexOf(File.separatorChar, 4);
if (sep < 0) return fullText;
fullText = "..." + fullText.substring(sep);
}
return fullText;
}
public void valueChanged(final ListSelectionEvent e) {
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
public void run() {
updatePathLabel();
}
});
}
private void updatePreviewPanel(final ItemWrapper wrapper) {
updateAlarm.cancelAllRequests();
updateAlarm.addRequest(new Runnable() {
public void run() {
detailView.updateWithItem(wrapper);
}
}, 100);
}
private void updatePathLabel() {
final Object[] values = myList.getSelectedValues();
ItemWrapper wrapper = null;
if (values != null && values.length == 1) {
wrapper = (ItemWrapper)values[0];
if (wrapper instanceof SplitterItem) {
if (!directionUp[0]) {
final int index = myList.getSelectedIndex();
if (myList.getItemsCount() >= index + 1) {
myList.setSelectedIndex(index + 1);
}
else {
myList.setSelectedIndex(0);
}
}
else {
final int index = myList.getSelectedIndex();
if (index - 1 > 0) {
myList.setSelectedIndex(index - 1);
}
else {
myList.setSelectedIndex(myList.getItemsCount() - 1);
}
}
}
pathLabel.setText(getTitle2Text(wrapper.footerText()));
}
else {
pathLabel.setText(" ");
}
updatePreviewPanel(wrapper);
}
});
final Ref<JBPopup> popupRef = Ref.create(null);
Runnable runnable = new Runnable() {
public void run() {
IdeFocusManager.getInstance(myProject).doWhenFocusSettlesDown(new Runnable() {
public void run() {
Object[] values = myList.getSelectedValues();
if (values.length == 1) {
((ItemWrapper)values[0]).execute(myProject, popupRef.get());
}
else {
for (Object value : values) {
if (value instanceof BookmarkItem) {
((ItemWrapper)value).execute(myProject, popupRef.get());
}
}
}
}
});
}
};
if (myList.getModel().getSize() == 0) {
myList.clearSelection();
}
JPanel footerPanel = new JPanel(new BorderLayout()) {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(BORDER_COLOR);
g.drawLine(0, 0, getWidth(), 0);
}
};
footerPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
footerPanel.add(pathLabel);
myActionToolbar = ActionManager.getInstance().createActionToolbar("", myActions, true);
myActionToolbar.setReservePlaceAutoPopupIcon(false);
myActionToolbar.setMinimumButtonSize(new Dimension(20, 20));
final JComponent toolBar = myActionToolbar.getComponent();
toolBar.setOpaque(false);
final JBPopup popup = new PopupChooserBuilder(myList).
setTitle(myDelegate.getTitle()).
setMovable(true).
setResizable(true).
setAutoselectOnMouseMove(false).
setSettingButton(toolBar).
setSouthComponent(footerPanel).
setEastComponent(detailView).
setItemChoosenCallback(runnable).
setCloseOnEnter(myCloseOnEnter).
setMayBeParent(true).
setMinSize(new Dimension(-1, 700)).
setFilteringEnabled(new Function<Object, String>() {
public String fun(Object o) {
return ((ItemWrapper)o).speedSearchText();
}
}).createPopup();
popupRef.set(popup);
myList.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_DELETE) {
removeSelectedItems(MasterDetailPopupBuilder.this.myList, MasterDetailPopupBuilder.this.myProject);
}
else if (e.getKeyCode() == KeyEvent.VK_UP) {
directionUp[0] = true;
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
directionUp[0] = false;
}
else if (e.getModifiersEx() == 0) {
myDelegate.handleMnemonic(e, myProject, popup);
}
}
});
return popup;
}
public static boolean allowedToRemoveSelectedItem(JBList list, Project project) {
Object[] values = list.getSelectedValues();
for (Object value : values) {
ItemWrapper item = (ItemWrapper)value;
if (!item.allowedToRemove()) {
return false;
}
}
return values.length > 0;
}
public static void removeSelectedItems(JBList list, Project project) {
int index = list.getSelectedIndex();
if (index == -1 || index >= list.getModel().getSize()) {
return;
}
Object[] values = list.getSelectedValues();
for (Object value : values) {
ItemWrapper item = (ItemWrapper)value;
DefaultListModel model = list.getModel() instanceof DefaultListModel
? (DefaultListModel)list.getModel()
: (DefaultListModel)((FilteringListModel)list.getModel()).getOriginalModel();
if (item.allowedToRemove()) {
model.removeElement(item);
if (model.getSize() > 0) {
if (model.getSize() == index) {
list.setSelectedIndex(model.getSize() - 1);
}
else if (model.getSize() > index) {
list.setSelectedIndex(index);
}
}
else {
list.clearSelection();
}
item.removed(project);
}
}
}
public MasterDetailPopupBuilder setActionsGroup(ActionGroup actions) {
myActions = actions;
return this;
}
public MasterDetailPopupBuilder setList(JBList list) {
myList = list;
return this;
}
public MasterDetailPopupBuilder setDelegate(Delegate delegate) {
myDelegate = delegate;
return this;
}
public MasterDetailPopupBuilder setCloseOnEnter(boolean closeOnEnter) {
myCloseOnEnter = closeOnEnter;
return this;
}
public interface Delegate {
String getTitle();
void handleMnemonic(KeyEvent e, Project project, JBPopup popup);
boolean hasItemsWithMnemonic(Project project);
}
public class ItemRenderer extends JPanel implements ListCellRenderer {
private final Project myProject;
private final ColoredListCellRenderer myRenderer;
private ItemRenderer(Project project) {
super(new BorderLayout());
myProject = project;
setBackground(UIUtil.getListBackground());
final JLabel mnemonicLabel = new JLabel();
mnemonicLabel.setFont(Bookmark.MNEMONIC_FONT);
mnemonicLabel.setPreferredSize(new JLabel("W.").getPreferredSize());
mnemonicLabel.setOpaque(false);
final boolean hasMnemonics = myDelegate.hasItemsWithMnemonic(project);
if (hasMnemonics) {
add(mnemonicLabel, BorderLayout.WEST);
}
myRenderer = new ColoredListCellRenderer() {
@Override
protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
if (value instanceof ItemWrapper) {
final ItemWrapper wrapper = (ItemWrapper)value;
wrapper.setupRenderer(this, myProject, selected);
if (hasMnemonics) {
wrapper.updateMnemonicLabel(mnemonicLabel);
}
}
}
};
add(myRenderer, BorderLayout.CENTER);
}
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
if (value instanceof SplitterItem) {
String label = ((SplitterItem)value).getText();
final TitledSeparator separator = new TitledSeparator(label);
separator.setBackground(UIUtil.getListBackground());
separator.setForeground(UIUtil.getListForeground());
return separator;
}
myRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
myRenderer.revalidate();
return this;
}
}
}
@@ -394,7 +394,7 @@ public class RevisionsList {
@Override
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
Graphics2D g2d = (Graphics2D)g.create();
g2d.setColor(UIUtil.getBorderSeparatorColor());
g2d.setColor(UIUtil.getBorderColor());
g2d.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{1}, 1));
g2d.drawLine(x, y, x + width, y);
if (isLast) {
@@ -334,9 +334,11 @@ public class ParametersList implements Cloneable {
final Application application = ApplicationManager.getApplication();
if (application != null) {
final PathMacros pathMacros = PathMacros.getInstance();
final Set<String> names = pathMacros.getAllMacroNames();
for (String name : names) {
myMacroMap.put("${" + name + "}", pathMacros.getValue(name));
for (String name : pathMacros.getUserMacroNames()) {
final String value = pathMacros.getValue(name);
if (value != null) {
myMacroMap.put("${" + name + "}", value);
}
}
final Map<String, String> env = EnvironmentUtil.getEnviromentProperties();
for (String name : env.keySet()) {
@@ -16,6 +16,7 @@
package com.intellij.openapi.diff;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.vfs.VirtualFile;
/**
@@ -41,7 +42,7 @@ public class MergeApplication extends ApplicationStarterBase {
MergeRequest request = DiffRequestFactory.getInstance()
.createMergeRequest(getText(left), getText(right), getText(middle), result,
null,
ProjectManager.getInstance().getDefaultProject(),
ActionButtonPresentation.APPLY,
ActionButtonPresentation.CANCEL_WITH_PROMPT);
request.addHint(DiffTool.HINT_SHOW_MODAL_DIALOG);
@@ -18,7 +18,6 @@ package com.intellij.openapi.ui;
import com.intellij.openapi.actionSystem.ActionToolbar;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.actionSystem.Separator;
import com.intellij.openapi.util.Ref;
import com.intellij.ui.switcher.QuickActionProvider;
import com.intellij.util.ui.AwtVisitor;
@@ -28,8 +27,8 @@ import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.event.ContainerAdapter;
import java.awt.event.ContainerEvent;
import java.util.List;
public class SimpleToolWindowPanel extends JPanel implements QuickActionProvider, DataProvider {
@@ -145,7 +144,7 @@ public class SimpleToolWindowPanel extends JPanel implements QuickActionProvider
super.paintComponent(g);
if (myToolbar != null && myToolbar.getParent() == this && myContent != null && myContent.getParent() == this) {
g.setColor(UIUtil.getBorderSeparatorColor());
g.setColor(UIUtil.getBorderColor());
if (myVertical) {
final int y = (int)myToolbar.getBounds().getMaxY();
g.drawLine(0, y, getWidth(), y);
@@ -81,6 +81,7 @@ public class PopupChooserBuilder {
private boolean myMayBeParent;
private int myAdAlignment = SwingUtilities.LEFT;
private boolean myModalContext;
private boolean myCloseOnEnter = true;
public PopupChooserBuilder(@NotNull JList list) {
myChooserComponent = list;
@@ -205,13 +206,28 @@ public class PopupChooserBuilder {
@Override
public void mouseReleased(MouseEvent e) {
if (UIUtil.isActionClick(e, MouseEvent.MOUSE_RELEASED) && !UIUtil.isSelectionButtonDown(e) && !e.isConsumed()) {
closePopup(true, e, true);
if (myCloseOnEnter) {
closePopup(true, e, true);
}
else {
myItemChosenRunnable.run();
}
}
}
});
registerClosePopupKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), false);
registerClosePopupKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), true);
if (myCloseOnEnter) {
registerClosePopupKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), true);
}
else {
registerKeyboardAction(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
myItemChosenRunnable.run();
}
});
}
for (KeyStroke keystroke : myAdditionalKeystrokes) {
registerClosePopupKeyboardAction(keystroke, true);
}
@@ -295,14 +311,18 @@ public class PopupChooserBuilder {
}
private void registerClosePopupKeyboardAction(final KeyStroke keyStroke, final boolean shouldPerformAction) {
myChooserComponent.registerKeyboardAction(new AbstractAction() {
registerPopupKeyboardAction(keyStroke, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
if (!shouldPerformAction && myChooserComponent instanceof ListWithFilter) {
if (((ListWithFilter)myChooserComponent).resetFilter()) return;
}
closePopup(shouldPerformAction, null, shouldPerformAction);
}
}, keyStroke, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
});
}
private void registerPopupKeyboardAction(final KeyStroke keyStroke, AbstractAction action) {
myChooserComponent.registerKeyboardAction(action, keyStroke, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
}
private void closePopup(boolean shouldPerformAction, MouseEvent e, boolean isOk) {
@@ -419,6 +439,11 @@ public class PopupChooserBuilder {
return this;
}
public PopupChooserBuilder setCloseOnEnter(boolean closeOnEnter) {
myCloseOnEnter = closeOnEnter;
return this;
}
private class MyListWrapper extends JBScrollPane implements DataProvider {
@SuppressWarnings({"FieldAccessedSynchronizedAndUnsynchronized"})
private final JList myList;
@@ -40,7 +40,7 @@ public class TitledSeparator extends JPanel {
public TitledSeparator(String text) {
setLayout(new GridBagLayout());
add(myLabel, new GridBagConstraints(0, 0, 1, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
add(myLabel, new GridBagConstraints(0, 0, 1, 1, 0, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(0, 3, 0, 0), 0, 0));
add(mySeparator,
new GridBagConstraints(1, 0, GridBagConstraints.REMAINDER, 1, 1, 1, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
new Insets(2, SEPARATOR_LEFT_INSET, 0, SEPARATOR_RIGHT_INSET), 0, 0));
@@ -54,7 +54,7 @@ public class TitledSeparator extends JPanel {
public void updateUI() {
super.updateUI();
if (myLabel != null) {
myLabel.setFont(UIUtil.getBorderFont(UIUtil.FontSize.SMALL, false));
myLabel.setFont(UIUtil.getTitledBorderFont());
}
}
@@ -81,22 +81,4 @@ public class TitledSeparator extends JPanel {
public JSeparator getSeparator() {
return mySeparator;
}
@Deprecated
public boolean isBoldFont() {
return false;
}
@Deprecated
public boolean isSmallFont() {
return true;
}
@Deprecated
public void setBoldFont(boolean boldFont) {
}
@Deprecated
public void setSmallFont(boolean smallFont) {
}
}
@@ -53,6 +53,7 @@ public class NonOpaquePanel extends Wrapper {
@Override
public void setOpaque(boolean isOpaque) {
super.setOpaque(isOpaque);
setDoubleBuffered(false);
if (!isOpaque && UIUtil.isUnderNimbusLookAndFeel()) {
if (UIUtil.isUnderNimbusLookAndFeel()) {
@@ -19,7 +19,6 @@ import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.DataProvider;
import com.intellij.openapi.util.ActionCallback;
import com.intellij.openapi.util.ActiveRunnable;
import com.intellij.openapi.util.Getter;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.switcher.SwitchProvider;
import org.jetbrains.annotations.NotNull;
@@ -29,8 +28,6 @@ import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Comparator;
import java.util.List;
public interface JBTabs extends SwitchProvider {
@@ -42,21 +39,10 @@ public interface JBTabs extends SwitchProvider {
ActionCallback removeTab(@Nullable TabInfo info);
ActionCallback removeTab(@Nullable TabInfo info, @Nullable TabInfo forcedSelectionTranfer);
ActionCallback removeTab(@Nullable TabInfo info, @Nullable TabInfo forcedSelectionTranfer, boolean transferFocus);
void removeAllTabs();
@Nullable
ActionGroup getPopupGroup();
@Nullable
String getPopupPlace();
JBTabs setPopupGroup(@NotNull ActionGroup popupGroup, @NotNull String place, final boolean addNavigationGroup);
JBTabs setPopupGroup(@NotNull Getter<ActionGroup> popupGroup, @NotNull String place, final boolean addNavigationGroup);
ActionCallback select(@NotNull TabInfo info, boolean requestFocus);
@Nullable
@@ -65,9 +51,6 @@ public interface JBTabs extends SwitchProvider {
@NotNull
TabInfo getTabAt(int tabIndex);
@NotNull
List<TabInfo> getTabs();
int getTabCount();
@NotNull
@@ -76,31 +59,19 @@ public interface JBTabs extends SwitchProvider {
@Nullable
DataProvider getDataProvider();
JBTabs setDataProvider(@NotNull DataProvider dataProvider);
@Nullable
TabInfo getTargetInfo();
@NotNull
JBTabs addTabMouseListener(@NotNull MouseListener listener);
@NotNull
JBTabs removeTabMouseListener(@NotNull MouseListener listener);
JBTabs addListener(@NotNull TabsListener listener);
JBTabs removeListener(@NotNull TabsListener listener);
JBTabs setSelectionChangeHandler(SelectionChangeHandler handler);
@NotNull
JComponent getComponent();
void updateTabActions(boolean validateNow);
@Nullable
TabInfo findInfo(Component component);
@Nullable
TabInfo findInfo(MouseEvent event);
@@ -109,11 +80,7 @@ public interface JBTabs extends SwitchProvider {
int getIndexOf(@Nullable final TabInfo tabInfo);
void sortTabs(Comparator<TabInfo> comparator);
void requestFocus();
boolean isEditorTabs();
JBTabs setNavigationActionBinding(String prevActiobId, String nextActionId);
JBTabs setNavigationActionsEnabled(boolean enabled);
@@ -122,16 +89,10 @@ public interface JBTabs extends SwitchProvider {
JBTabs setAdditionalSwitchProviderWhenOriginal(SwitchProvider delegate);
Image getComponentImage(TabInfo info);
void resetDropOver(TabInfo tabInfo);
Image startDropOver(TabInfo tabInfo, RelativePoint point);
void processDropOver(TabInfo over, RelativePoint point);
boolean isEmptyVisible();
int getInterTabSpaceLength();
interface SelectionChangeHandler {
ActionCallback execute(final TabInfo info, final boolean requestFocus, ActiveRunnable doChangeSelection);
}
@@ -30,14 +30,10 @@ public interface JBTabsPresentation {
JBTabsPresentation setPaintBorder(int top, int left, int right, int bottom);
JBTabsPresentation setTabSidePaintBorder(int size);
boolean isPaintFocus();
JBTabsPresentation setPaintFocus(boolean paintFocus);
JBTabsPresentation setStealthTabMode(boolean stealthTabMode);
boolean isStealthTabMode();
JBTabsPresentation setSideComponentVertical(boolean vertical);
JBTabsPresentation setSideComponentOnTabs(boolean onTabs);
@@ -46,35 +42,18 @@ public interface JBTabsPresentation {
boolean isSingleRow();
boolean isSideComponentVertical();
boolean isSideComponentOnTabs();
JBTabsPresentation setUiDecorator(@Nullable UiDecorator decorator);
boolean isRequestFocusOnLastFocusedComponent();
JBTabsPresentation setRequestFocusOnLastFocusedComponent(boolean request);
void setPaintBlocked(boolean blocked, final boolean takeSnapshot);
void setFocused(boolean focused);
JBTabsPresentation setInnerInsets(Insets innerInsets);
Insets getInnerInsets();
JBTabsPresentation setGhostsAlwaysVisible(boolean visible);
boolean isGhostsAlwaysVisible();
@NotNull
JBTabsPresentation setAdjustBorders(boolean adjust);
JBTabsPresentation setFocusCycle(final boolean root);
boolean isToDrawBorderIfTabsHidden();
@NotNull
JBTabsPresentation setToDrawBorderIfTabsHidden(boolean draw);
@@ -96,9 +75,7 @@ public interface JBTabsPresentation {
JBTabsPosition getTabsPosition();
JBTabsPresentation setTabDraggingEnabled(boolean enabled);
boolean isTabDraggingEnabled();
JBTabsPresentation setProvideSwitchTargets(boolean provide);
}
}
@@ -127,10 +127,6 @@ class ActionButton extends IconButton implements ActionListener {
}
}
public boolean isAutoHide() {
return myAutoHide;
}
public void toggleShowActions(boolean show) {
if (myAutoHide) {
myButton.setPainting(show);
@@ -37,15 +37,13 @@ public class ActionPanel extends NonOpaquePanel {
private boolean myAutoHide;
private boolean myActionsIsVisible = false;
private final int myGap = 2;
public ActionPanel(JBTabsImpl tabs, TabInfo tabInfo, Pass<MouseEvent> pass) {
myTabs = tabs;
ActionGroup group = tabInfo.getTabLabelActions() != null ? tabInfo.getTabLabelActions() : new DefaultActionGroup();
AnAction[] children = group.getChildren(null);
final NonOpaquePanel wrapper = new NonOpaquePanel(new BorderLayout());
wrapper.add(Box.createHorizontalStrut(myGap), BorderLayout.WEST);
wrapper.add(Box.createHorizontalStrut(2), BorderLayout.WEST);
NonOpaquePanel inner = new NonOpaquePanel();
inner.setLayout(new BoxLayout(inner, BoxLayout.X_AXIS));
wrapper.add(inner, BorderLayout.CENTER);
@@ -29,12 +29,12 @@ import java.awt.event.MouseEvent;
class DragHelper extends MouseDragHelper {
JBTabsImpl myTabs;
TabInfo myDragSource;
Rectangle myDragOriginalRec;
private final JBTabsImpl myTabs;
private TabInfo myDragSource;
private Rectangle myDragOriginalRec;
Rectangle myDragRec;
Dimension myHoldDelta;
private Dimension myHoldDelta;
private TabInfo myDragOutSource;
private TabLabel myPressedTabLabel;
@@ -147,7 +147,7 @@ class DragHelper extends MouseDragHelper {
if (targetLabel != null) {
Rectangle saved = myDragRec;
myDragRec = null;
myTabs.reallocate(myDragSource, targetLabel.getInfo(), true);
myTabs.reallocate(myDragSource, targetLabel.getInfo());
myDragOriginalRec = myTabs.myInfo2Label.get(myDragSource).getBounds();
myDragRec = saved;
myTabs.moveDraggedTabLabel();
@@ -251,4 +251,4 @@ class DragHelper extends MouseDragHelper {
public TabInfo getDragSource() {
return myDragSource;
}
}
}
@@ -19,12 +19,12 @@ import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ModalityState;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.openapi.ui.Queryable;
import com.intellij.openapi.ui.ShadowAction;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.wm.*;
import com.intellij.openapi.ui.GraphicsConfig;
import com.intellij.ui.CaptionPanel;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.Gray;
@@ -65,12 +65,11 @@ import java.util.concurrent.CopyOnWriteArrayList;
public class JBTabsImpl extends JComponent
implements JBTabs, PropertyChangeListener, TimerListener, DataProvider, PopupMenuListener, Disposable, JBTabsPresentation, Queryable, QuickActionProvider {
public static DataKey<JBTabsImpl> NAVIGATION_ACTIONS_KEY = DataKey.create("JBTabs");
public static final DataKey<JBTabsImpl> NAVIGATION_ACTIONS_KEY = DataKey.create("JBTabs");
public static final String EDITOR_TABS = "main.editor.tabs";
public static final Color MAC_AQUA_BG_COLOR = Gray._200;
ActionManager myActionManager;
final ActionManager myActionManager;
private final List<TabInfo> myVisibleInfos = new ArrayList<TabInfo>();
private final Map<TabInfo, Integer> myHiddenInfos = new HashMap<TabInfo, Integer>();
@@ -83,15 +82,15 @@ public class JBTabsImpl extends JComponent
private final List<EventListener> myTabMouseListeners = new CopyOnWriteArrayList<EventListener>();
private final List<TabsListener> myTabListeners = new CopyOnWriteArrayList<TabsListener>();
public boolean myFocused;
private boolean myFocused;
private Getter<ActionGroup> myPopupGroup;
private String myPopupPlace;
TabInfo myPopupInfo;
DefaultActionGroup myNavigationActions;
final DefaultActionGroup myNavigationActions;
PopupMenuListener myPopupListener;
final PopupMenuListener myPopupListener;
JPopupMenu myActivePopup;
public boolean myHorizontalSide = true;
@@ -130,7 +129,7 @@ public class JBTabsImpl extends JComponent
private boolean myPaintBlocked;
private BufferedImage myImage;
private IdeFocusManager myFocusManager;
private boolean myAdjustBorders = true;
private final boolean myAdjustBorders = true;
boolean myAddNavigationGroup = true;
@@ -177,7 +176,7 @@ public class JBTabsImpl extends JComponent
this(project, project);
}
public JBTabsImpl(@NotNull Project project, @NotNull Disposable parent) {
private JBTabsImpl(@NotNull Project project, @NotNull Disposable parent) {
this(project, ActionManager.getInstance(), IdeFocusManager.getInstance(project), parent);
}
@@ -331,8 +330,7 @@ public class JBTabsImpl extends JComponent
return this;
}
@Override
public Image getComponentImage(TabInfo info) {
public static Image getComponentImage(TabInfo info) {
JComponent cmp = info.getComponent();
BufferedImage img;
@@ -461,7 +459,7 @@ public class JBTabsImpl extends JComponent
return myDropInfo != null && myDropInfo == info;
}
public void setDropInfoIndex(int dropInfoIndex) {
protected void setDropInfoIndex(int dropInfoIndex) {
myDropInfoIndex = dropInfoIndex;
}
@@ -474,8 +472,7 @@ public class JBTabsImpl extends JComponent
public void mouseMoved(final MouseEvent e) {
if (!myTabLabelActionsAutoHide) return;
final Point point = SwingUtilities.convertPoint(e.getComponent(), e.getX(), e.getY(), JBTabsImpl.this);
myLastOverPoint = point;
myLastOverPoint = SwingUtilities.convertPoint(e.getComponent(), e.getX(), e.getY(), JBTabsImpl.this);
processMouseOver();
}
@@ -590,6 +587,7 @@ public class JBTabsImpl extends JComponent
}
@Nullable
private JComponent getToFocus() {
final TabInfo info = getSelectedInfo();
@@ -637,18 +635,6 @@ public class JBTabsImpl extends JComponent
}
}
private JBTabsImpl findTabs(Component c) {
Component eachParent = c;
while (eachParent != null) {
if (eachParent instanceof JBTabsImpl) {
return (JBTabsImpl)eachParent;
}
eachParent = eachParent.getParent();
}
return null;
}
@NotNull
public TabInfo addTab(TabInfo info, int index) {
@@ -669,10 +655,7 @@ public class JBTabsImpl extends JComponent
myInfo2Label.put(info, label);
if (!isDropTarget) {
if (index < 0) {
myVisibleInfos.add(info);
}
else if (index > myVisibleInfos.size() - 1) {
if (index < 0 || index > myVisibleInfos.size() - 1) {
myVisibleInfos.add(info);
}
else {
@@ -719,6 +702,7 @@ public class JBTabsImpl extends JComponent
return addTab(info, -1);
}
@Nullable
public ActionGroup getPopupGroup() {
return myPopupGroup != null ? myPopupGroup.get() : null;
}
@@ -847,7 +831,7 @@ public class JBTabsImpl extends JComponent
}
}
private void fireBeforeSelectionChanged(TabInfo oldInfo, TabInfo newInfo) {
private void fireBeforeSelectionChanged(@Nullable TabInfo oldInfo, TabInfo newInfo) {
if (oldInfo != newInfo) {
myOldSelection = oldInfo;
try {
@@ -861,7 +845,7 @@ public class JBTabsImpl extends JComponent
}
}
private void fireSelectionChanged(TabInfo oldInfo, TabInfo newInfo) {
private void fireSelectionChanged(@Nullable TabInfo oldInfo, TabInfo newInfo) {
if (oldInfo != newInfo) {
for (TabsListener eachListener : myTabListeners) {
if (eachListener != null) {
@@ -956,19 +940,6 @@ public class JBTabsImpl extends JComponent
myDeferredToRemove.clear();
}
private void printRemoveInfo(final Component each) {
TabInfo removingInfo = null;
final List<TabInfo> all = getTabs();
for (TabInfo eachInfo : all) {
if (eachInfo.getComponent() == each) {
removingInfo = eachInfo;
break;
}
}
//System.out.println(" - removing " + (removingInfo != null ? " component for " + removingInfo : each));
}
public void propertyChange(final PropertyChangeEvent evt) {
final TabInfo tabInfo = (TabInfo)evt.getSource();
if (TabInfo.ACTION_GROUP.equals(evt.getPropertyName())) {
@@ -1322,7 +1293,7 @@ public class JBTabsImpl extends JComponent
}
}
public boolean isToDrawBorderIfTabsHidden() {
private boolean isToDrawBorderIfTabsHidden() {
return myToDrawBorderIfTabsHidden;
}
@@ -1339,11 +1310,9 @@ public class JBTabsImpl extends JComponent
public static class Toolbar extends JPanel {
private final JBTabsImpl myTabs;
private final TabInfo myInfo;
public Toolbar(JBTabsImpl tabs, TabInfo info) {
myTabs = tabs;
myInfo = info;
setLayout(new BorderLayout());
@@ -1489,7 +1458,7 @@ public class JBTabsImpl extends JComponent
return this;
}
public Insets getInnerInsets() {
private Insets getInnerInsets() {
return myInnerInsets;
}
@@ -1542,15 +1511,15 @@ public class JBTabsImpl extends JComponent
}
protected int getArcSize() {
private static int getArcSize() {
return 4;
}
protected int getEdgeArcSize() {
private static int getEdgeArcSize() {
return 3;
}
public int getGhostTabLength() {
public static int getGhostTabLength() {
return 15;
}
@@ -1622,7 +1591,8 @@ public class JBTabsImpl extends JComponent
config.restore();
}
protected Color getActiveTabColor(final Color c) {
@Nullable
protected Color getActiveTabColor(@Nullable final Color c) {
final TabInfo info = getSelectedInfo();
if (info == null) {
return c;
@@ -1857,10 +1827,6 @@ public class JBTabsImpl extends JComponent
g2d.drawLine(bottomX - path.deltaX(1), topY + path.deltaY(getArcSize()), bottomX - path.deltaX(1), bottomY - path.deltaY(1));
}
protected SingleRowLayout getSingleRowLayout() {
return mySingleRowLayout;
}
protected void paintLastGhost(Graphics2D g2d) {
final ShapeTransform path = getEffectiveLayout().createShapeTransform(mySingleRowLayout.myLastSingRowLayout.lastGhost);
@@ -1887,25 +1853,21 @@ public class JBTabsImpl extends JComponent
g2d.drawLine(topX, topY + path.deltaY(1), bottomX - path.deltaX(getCurveArc()), topY + path.deltaY(1));
}
protected int getCurveArc() {
private static int getCurveArc() {
return 2;
}
protected Color getBoundsColor() {
private static Color getBoundsColor() {
return Color.gray;
}
protected Color getRightBlockColor() {
private static Color getRightBlockColor() {
return Color.lightGray;
}
protected Color getTopBlockColor() {
private static Color getTopBlockColor() {
return Color.white;
}
protected boolean shouldPaintFocus() {
return myPaintFocus;
}
private void paintNonSelectedTabs(final Graphics2D g2d, final boolean leftGhostExists, final boolean rightGhostExists) {
TabInfo selected = getSelectedInfo();
@@ -1976,18 +1938,6 @@ public class JBTabsImpl extends JComponent
protected LayoutPassInfo getLastLayoutPass() {
return myLastLayoutPass;
}
protected TabLabel getInfoForLabel(TabInfo info) {
return myInfo2Label.get(info);
}
protected TableLayout getTableLayout() {
return myTableLayout;
}
protected DragHelper getDragHelper() {
return myDragHelper;
}
@Override
public Color getBackground() {
@@ -2035,8 +1985,7 @@ public class JBTabsImpl extends JComponent
boolean leftFromSelection = selected != null && tabIndex == myVisibleInfos.indexOf(selected) - 1;
Rectangle originalBounds = effectiveBounds;
final ShapeTransform shape = getEffectiveLayout().createShapeTransform(originalBounds);
final ShapeTransform shape = getEffectiveLayout().createShapeTransform(effectiveBounds);
int leftX = firstShowing ? shape.getX() : shape.getX() - shape.deltaX(arc + 1);
int topY = shape.getY() + shape.deltaY(selectionTabVShift);
@@ -2115,7 +2064,7 @@ public class JBTabsImpl extends JComponent
g2d.draw(shape.getShape());
}
public int getSelectionTabVShift() {
public static int getSelectionTabVShift() {
return 2;
}
@@ -2189,7 +2138,7 @@ public class JBTabsImpl extends JComponent
}
public boolean isStealthModeEffective() {
protected boolean isStealthModeEffective() {
return myStealthTabMode && getTabCount() == 1 &&
(isSideComponentVertical() || !isSideComponentOnTabs()) &&
getTabsPosition() == JBTabsPosition.top;
@@ -2358,16 +2307,8 @@ public class JBTabsImpl extends JComponent
return this;
}
public ActionCallback removeTab(final JComponent component) {
return removeTab(findInfo(component));
}
public ActionCallback removeTab(final TabInfo info) {
return removeTab(info, null);
}
public ActionCallback removeTab(final TabInfo info, @Nullable TabInfo forcedSelectionTransfer) {
return removeTab(info, forcedSelectionTransfer, true);
return removeTab(info, null, true);
}
public ActionCallback removeTab(final TabInfo info, @Nullable TabInfo forcedSelectionTransfer, boolean transferFocus) {
@@ -2442,6 +2383,7 @@ public class JBTabsImpl extends JComponent
myLastPaintedSelection = null;
}
@Nullable
public TabInfo findInfo(Component component) {
for (TabInfo each : getTabs()) {
if (each.getComponent() == component) return each;
@@ -2450,20 +2392,11 @@ public class JBTabsImpl extends JComponent
return null;
}
public TabInfo findInfo(String text) {
if (text == null) return null;
for (TabInfo each : getTabs()) {
if (text.equals(each.getText())) return each;
}
return null;
}
public TabInfo findInfo(MouseEvent event) {
return findInfo(event, false);
}
@Nullable
private TabInfo findInfo(final MouseEvent event, final boolean labelsOnly) {
final Point point = SwingUtilities.convertPoint(event.getComponent(), event.getPoint(), this);
return _findInfo(point, labelsOnly);
@@ -2478,10 +2411,6 @@ public class JBTabsImpl extends JComponent
return null;
}
public TabInfo findTabLabelBy(final Point point) {
return _findInfo(point, true);
}
@Nullable
private TabInfo _findInfo(final Point point, boolean labelsOnly) {
Component component = findComponentAt(point);
@@ -2509,8 +2438,8 @@ public class JBTabsImpl extends JComponent
private static class Max {
Dimension myLabel = new Dimension();
Dimension myToolbar = new Dimension();
final Dimension myLabel = new Dimension();
final Dimension myToolbar = new Dimension();
}
private void updateContainer(boolean forced, final boolean layoutNow) {
@@ -2539,7 +2468,7 @@ public class JBTabsImpl extends JComponent
}
}
mySingleRowLayout.scrollSelectionInView(myVisibleInfos);
mySingleRowLayout.scrollSelectionInView();
relayout(forced, layoutNow);
}
@@ -2569,14 +2498,6 @@ public class JBTabsImpl extends JComponent
return myBorder;
}
@NotNull
public JBTabs addTabMouseMotionListener(@NotNull MouseMotionListener listener) {
removeListeners();
myTabMouseListeners.add(listener);
addListeners();
return this;
}
@NotNull
public JBTabs addTabMouseListener(@NotNull MouseListener listener) {
removeListeners();
@@ -2594,14 +2515,6 @@ public class JBTabsImpl extends JComponent
return false;
}
@NotNull
public JBTabs removeTabMouseListener(@NotNull MouseListener listener) {
removeListeners();
myTabMouseListeners.remove(listener);
addListeners();
return this;
}
private void addListeners() {
for (TabInfo eachInfo : myVisibleInfos) {
final TabLabel label = myInfo2Label.get(eachInfo);
@@ -2646,20 +2559,12 @@ public class JBTabsImpl extends JComponent
return this;
}
public JBTabs removeListener(@NotNull final TabsListener listener) {
myTabListeners.remove(listener);
return this;
}
@Override
public JBTabs setSelectionChangeHandler(SelectionChangeHandler handler) {
mySelectionChangeHandler = handler;
return this;
}
protected void onPopup(final TabInfo popupInfo) {
}
public void setFocused(final boolean focused) {
if (myFocused == focused) return;
@@ -2698,16 +2603,10 @@ public class JBTabsImpl extends JComponent
return size == -1 ? 1 : size;
}
public boolean isPaintFocus() {
private boolean isPaintFocus() {
return myPaintFocus;
}
@NotNull
public JBTabsPresentation setAdjustBorders(final boolean adjust) {
myAdjustBorders = adjust;
return this;
}
@NotNull
public JBTabsPresentation setActiveTabFillIn(@Nullable final Color color) {
if (!isChanged(myActiveTabFillIn, color)) return this;
@@ -2732,7 +2631,7 @@ public class JBTabsImpl extends JComponent
}
@Nullable
public Color getActiveTabFillIn() {
protected Color getActiveTabFillIn() {
return myActiveTabFillIn;
}
@@ -2915,7 +2814,6 @@ public class JBTabsImpl extends JComponent
return !myHorizontalSide;
}
@Override
public boolean isSideComponentOnTabs() {
return mySideComponentOnTabs;
}
@@ -2975,7 +2873,7 @@ public class JBTabsImpl extends JComponent
relayout(true, false);
}
public boolean isRequestFocusOnLastFocusedComponent() {
private boolean isRequestFocusOnLastFocusedComponent() {
return myRequestFocusOnLastFocusedComponent;
}
@@ -3028,7 +2926,7 @@ public class JBTabsImpl extends JComponent
}
public boolean isSelectionClick(final MouseEvent e, boolean canBeQuick) {
public static boolean isSelectionClick(final MouseEvent e, boolean canBeQuick) {
if (e.getClickCount() == 1 || canBeQuick) {
if (!e.isPopupTrigger()) {
return e.getButton() == MouseEvent.BUTTON1 && !e.isControlDown() && !e.isAltDown() && !e.isMetaDown();
@@ -3120,25 +3018,16 @@ public class JBTabsImpl extends JComponent
return this;
}
void reallocate(TabInfo source, TabInfo target, boolean before) {
void reallocate(TabInfo source, TabInfo target) {
if (source == target || source == null || target == null) return;
final int targetIndex = myVisibleInfos.indexOf(target);
final int sourceIndex = myVisibleInfos.indexOf(source);
boolean needsValidation = false;
myVisibleInfos.remove(source);
myVisibleInfos.add(targetIndex, source);
needsValidation = true;
//if (before && targetIndex < sourceIndex || !before && targetIndex > sourceIndex) {
//}
if (needsValidation) {
invalidate();
relayout(true, true);
}
invalidate();
relayout(true, true);
}
boolean isHorizontalTabs() {
@@ -3152,10 +3041,6 @@ public class JBTabsImpl extends JComponent
}
}
public boolean isUseBufferedPaint() {
return myUseBufferedPaint;
}
public void setUseBufferedPaint(boolean useBufferedPaint) {
myUseBufferedPaint = useBufferedPaint;
revalidate();
@@ -3280,13 +3165,11 @@ public class JBTabsImpl extends JComponent
return myDropInfoIndex;
}
@Override
public boolean isEmptyVisible() {
return myVisibleInfos.isEmpty();
}
@Override
public int getInterTabSpaceLength() {
public static int getInterTabSpaceLength() {
return 1;
}
@@ -23,7 +23,7 @@ import java.util.List;
public abstract class LayoutPassInfo {
public List<TabInfo> myVisibleInfos;
public final List<TabInfo> myVisibleInfos;
protected LayoutPassInfo(List<TabInfo> visibleInfos) {
myVisibleInfos = visibleInfos;
@@ -27,23 +27,18 @@ public abstract class ShapeTransform {
private Rectangle myShapeRect;
protected int myXTransform;
protected int myYTransform;
private boolean mySwap;
private final int myXTransform;
private final int myYTransform;
private final boolean mySwap;
public ShapeTransform(Rectangle shapeRect, int xTransform, int yTransform, boolean swap) {
protected ShapeTransform(Rectangle shapeRect, int xTransform, int yTransform, boolean swap) {
myShapeRect = shapeRect;
myXTransform = xTransform;
myYTransform = yTransform;
mySwap = swap;
}
public ShapeTransform(int XTranform, int YTranform) {
myXTransform = XTranform;
myYTransform = YTranform;
}
public final Rectangle getShapeRect() {
protected final Rectangle getShapeRect() {
return myShapeRect;
}
@@ -63,22 +58,10 @@ public abstract class ShapeTransform {
return deltaY * myYTransform;
}
public final <T> T transformX1(T o1, T o2) {
return (mySwap ? myYTransform : myXTransform) == 1 ? o1: o2;
}
public final <T> T transformX2(T o1, T o2) {
return (mySwap ? myYTransform : myXTransform) == 1 ? o2: o1;
}
public final <T> T transformY1(T o1, T o2) {
return (mySwap ? myXTransform : myYTransform) == 1 ? o1: o2;
}
public final <T> T transformY2(T o1, T o2) {
return (mySwap ? myXTransform : myYTransform) == 1 ? o2: o1;
}
public abstract Insets transformInsets(Insets insets);
public abstract Line2D.Float transformLine(int x1, int y1, int x2, int y2);
@@ -136,7 +119,7 @@ public abstract class ShapeTransform {
return reset(null);
}
public final ShapeTransform reset(Rectangle shapeRec) {
protected final ShapeTransform reset(Rectangle shapeRec) {
myPath = new GeneralPath();
if (shapeRec != null) {
myShapeRect = shapeRec;
@@ -58,16 +58,15 @@ public class TabLabel extends JPanel {
protected ActionPanel myActionPanel;
private boolean myCentered;
private final Wrapper myLabelPlaceholder = new Wrapper();
private final Wrapper myLabelPlaceholder = new Wrapper(false);
private final JBTabsImpl myTabs;
private BufferedImage myImage;
private BufferedImage myInactiveStateImage;
private Rectangle myLastPaintedInactiveImageBounds;
private boolean myStretchedByWidth;
public TabLabel(JBTabsImpl tabs, final TabInfo info) {
super(false);
myTabs = tabs;
myInfo = info;
myLabel.setOpaque(false);
@@ -87,7 +86,7 @@ public class TabLabel extends JPanel {
addMouseListener(new MouseAdapter() {
public void mousePressed(final MouseEvent e) {
if (myTabs.isSelectionClick(e, false) && myInfo.isEnabled()) {
if (JBTabsImpl.isSelectionClick(e, false) && myInfo.isEnabled()) {
final TabInfo selectedInfo = myTabs.getSelectedInfo();
if (selectedInfo != myInfo) {
myInfo.setPreviousSelection(selectedInfo);
@@ -148,29 +147,29 @@ public class TabLabel extends JPanel {
if (myTabs.isDropTarget(myInfo)) return;
if (myTabs.getSelectedInfo() != myInfo) {
myImage = null;
doPaint(g);
} else if (!SystemInfo.isMac) {
myImage = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_ARGB);
final Graphics2D lg = myImage.createGraphics();
doPaint(lg);
lg.dispose();
}
}
@Override
public void setBounds(Rectangle r) {
super.setBounds(r);
}
@Override
public void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, height);
}
public void paintImage(Graphics g) {
final Rectangle b = getBounds();
if (myImage != null) {
g.drawImage(myImage, b.x, b.y, getWidth(), getHeight(), null);
} else {
final Graphics lG = g.create(b.x, b.y, b.width, b.height);
try {
lG.setColor(Color.red);
doPaint(lG);
}
finally {
lG.dispose();
}
final Graphics lG = g.create(b.x, b.y, b.width, b.height);
try {
lG.setColor(Color.red);
doPaint(lG);
}
finally {
lG.dispose();
}
}
@@ -291,7 +290,6 @@ public class TabLabel extends JPanel {
myTabs.myActivePopup.addPopupMenuListener(myTabs);
myTabs.myActivePopup.show(e.getComponent(), e.getX(), e.getY());
myTabs.onPopup(myTabs.myPopupInfo);
}
@@ -350,7 +348,7 @@ public class TabLabel extends JPanel {
return hasIcons;
}
private void setIcon(final Icon icon, int layer) {
private void setIcon(@Nullable final Icon icon, int layer) {
LayeredIcon layeredIcon = getLayeredIcon();
layeredIcon.setIcon(icon, layer);
if (hasIcons()) {
@@ -366,14 +364,6 @@ public class TabLabel extends JPanel {
return myIcon;
}
public void setAttraction(boolean enabled) {
getLayeredIcon().setLayerEnabled(1, enabled);
}
public boolean isAttractionEnabled() {
return getLayeredIcon().isLayerEnabled(1);
}
public TabInfo getInfo() {
return myInfo;
}
@@ -418,10 +408,6 @@ public class TabLabel extends JPanel {
myTabs.revalidateAndRepaint(false);
}
@Override
protected void processMouseEvent(final MouseEvent e) {
super.processMouseEvent(e);
}
private void removeOldActionPanel() {
if (myActionPanel != null) {
@@ -435,7 +421,7 @@ public class TabLabel extends JPanel {
}
private void setAttractionIcon(Icon icon) {
private void setAttractionIcon(@Nullable Icon icon) {
if (myIcon.getIcon(0) == null) {
setIcon(null, 1);
myOverlayedIcon = icon;
@@ -21,7 +21,6 @@ import org.jetbrains.annotations.NotNull;
import java.awt.*;
public abstract class TabLayout {
private Rectangle myHeaderRect;
public ShapeTransform createShapeTransform(Dimension dimension) {
return createShapeTransform(new Rectangle(0, 0, dimension.width, dimension.height));

Some files were not shown because too many files have changed in this diff Show More