Merge remote-tracking branch 'origin/master'

This commit is contained in:
irengrig
2015-08-26 17:59:53 +02:00
255 changed files with 4600 additions and 2483 deletions
+1
View File
@@ -54,6 +54,7 @@
<module name="junit_rt" target="1.3" />
<module name="maven-jps-plugin" target="1.6" />
<module name="remote-servers-agent-rt" target="1.5" />
<module name="settings-repository-tests" target="1.8" />
<module name="svn4idea-tests" target="1.8" />
<module name="tasks-tests" target="1.8" />
<module name="testng_rt" target="1.5" />
+6 -1
View File
@@ -852,10 +852,15 @@ skip_properties:
; set the current time for installation files under $INSTDIR\bin
ExecCmd::exec 'copy "$INSTDIR\bin\*.*s" +,,'
call winVersion
${If} $0 == "1"
${If} $0 == "1"
;ExecCmd::exec 'icacls "$INSTDIR" /grant %username%:F /T >"$INSTDIR"\installation_log.txt 2>"$INSTDIR"\installation_error.txt'
AccessControl::GrantOnFile \
"$INSTDIR" "(S-1-5-32-545)" "GenericRead + GenericExecute"
AccessControl::GrantOnFile \
"$INSTDIR\bin\${PRODUCT_EXE_FILE}.vmoptions" "(S-1-5-32-545)" "GenericRead + GenericWrite"
${StrRep} $0 ${PRODUCT_EXE_FILE} ".exe" "64.exe.vmoptions"
AccessControl::GrantOnFile \
"$INSTDIR\bin\$0" "(S-1-5-32-545)" "GenericRead + GenericWrite"
${EndIf}
SectionEnd
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -27,6 +27,7 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.MultiLineLabelUI;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.IdeBorderFactory;
import com.intellij.ui.ScrollPaneFactory;
import com.intellij.util.ArrayUtil;
@@ -129,19 +130,13 @@ public class GenerateAntBuildDialog extends DialogWrapper {
private void saveSettings() {
final PropertiesComponent properties = PropertiesComponent.getInstance(myProject);
properties.setValue(SINGLE_FILE_PROPERTY, Boolean.toString(myRbGenerateSingleFileBuild.isSelected()));
properties.setValue(UI_FORM_PROPERTY, Boolean.toString(myCbEnableUIFormsCompilation.isSelected()));
properties.setValue(FORCE_TARGET_JDK_PROPERTY, Boolean.toString(myCbForceTargetJdk.isSelected()));
properties.setValue(BACKUP_FILES_PROPERTY, Boolean.toString(myRbBackupFiles.isSelected()));
properties.setValue(INLINE_RUNTIME_CLASSPATH_PROPERTY, Boolean.toString(myCbInlineRuntimeClasspath.isSelected()));
properties.setValue(GENERATE_IDEA_HOME_PROPERTY, Boolean.toString(myGenerateIdeaHomeProperty.isSelected()));
final String outputFileName = getOutputFileName();
if (outputFileName.length() > 0) {
properties.setValue(OUTPUT_FILE_NAME_PROPERTY, outputFileName);
}
else {
properties.unsetValue(OUTPUT_FILE_NAME_PROPERTY);
}
properties.setValue(SINGLE_FILE_PROPERTY, myRbGenerateSingleFileBuild.isSelected());
properties.setValue(UI_FORM_PROPERTY, myCbEnableUIFormsCompilation.isSelected());
properties.setValue(FORCE_TARGET_JDK_PROPERTY, myCbForceTargetJdk.isSelected());
properties.setValue(BACKUP_FILES_PROPERTY, myRbBackupFiles.isSelected());
properties.setValue(INLINE_RUNTIME_CLASSPATH_PROPERTY, myCbInlineRuntimeClasspath.isSelected());
properties.setValue(GENERATE_IDEA_HOME_PROPERTY, myGenerateIdeaHomeProperty.isSelected());
properties.setValue(OUTPUT_FILE_NAME_PROPERTY, StringUtil.nullize(getOutputFileName()));
}
public void dispose() {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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,8 +18,8 @@ package com.intellij.compiler.classFilesIndex.chainsSearch.completion.lookup;
import com.intellij.codeInsight.completion.InsertionContext;
import com.intellij.codeInsight.completion.JavaMethodCallElement;
import com.intellij.codeInsight.completion.StaticallyImportable;
import com.intellij.compiler.classFilesIndex.chainsSearch.completion.lookup.sub.SubLookupElement;
import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
import com.intellij.compiler.classFilesIndex.chainsSearch.completion.lookup.sub.SubLookupElement;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.psi.PsiClass;
@@ -64,7 +64,7 @@ public class ChainCompletionMethodCallLookupElement extends JavaMethodCallElemen
private void configureAutoCompletionPolicy() {
if (ApplicationManager.getApplication().isUnitTestMode()) {
if (PropertiesComponent.getInstance(myMethod.getProject()).getBoolean(PROP_METHODS_CHAIN_COMPLETION_AUTO_COMPLETION, false)) {
if (PropertiesComponent.getInstance(myMethod.getProject()).getBoolean(PROP_METHODS_CHAIN_COMPLETION_AUTO_COMPLETION)) {
setAutoCompletionPolicy(AutoCompletionPolicy.GIVE_CHANCE_TO_OVERWRITE);
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -31,6 +31,7 @@ import java.awt.*;
*/
public class ObjectMarkupPropertiesDialog extends ValueMarkerPresentationDialogBase {
@NonNls private static final String MARK_ALL_REFERENCED_VALUES_KEY = "debugger.mark.all.referenced.values";
private static final boolean MARK_ALL_REFERENCED_VALUES_DEFAULT_VALUE = true;
private JCheckBox myCbMarkAdditionalFields;
private final boolean mySuggestAdditionalMarkup;
private JPanel myAdditionalPropertiesPanel;
@@ -41,14 +42,14 @@ public class ObjectMarkupPropertiesDialog extends ValueMarkerPresentationDialogB
mySuggestAdditionalMarkup = suggestAdditionalMarkup;
myDescriptionLabel.setText("If the value is referenced by a constant field of an abstract class,\n" +
"IDEA could additionally mark all values referenced from this class with the names of referencing fields.");
myCbMarkAdditionalFields.setSelected(PropertiesComponent.getInstance().getBoolean(MARK_ALL_REFERENCED_VALUES_KEY, true));
myCbMarkAdditionalFields.setSelected(PropertiesComponent.getInstance().getBoolean(MARK_ALL_REFERENCED_VALUES_KEY, MARK_ALL_REFERENCED_VALUES_DEFAULT_VALUE));
init();
}
@Override
protected void doOKAction() {
if (mySuggestAdditionalMarkup) {
PropertiesComponent.getInstance().setValue(MARK_ALL_REFERENCED_VALUES_KEY, Boolean.toString(myCbMarkAdditionalFields.isSelected()));
PropertiesComponent.getInstance().setValue(MARK_ALL_REFERENCED_VALUES_KEY, myCbMarkAdditionalFields.isSelected(), MARK_ALL_REFERENCED_VALUES_DEFAULT_VALUE);
}
super.doOKAction();
}
@@ -26,7 +26,6 @@ import com.intellij.openapi.options.ShowSettingsUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.util.text.StringUtilRt;
import com.intellij.ui.PortField;
import com.intellij.xdebugger.impl.settings.DebuggerConfigurable;
import org.jetbrains.annotations.NotNull;
@@ -40,7 +39,7 @@ public class GenericDebuggerParametersRunnerConfigurable extends SettingsEditor<
private JTextField myAddressField;
private JPanel myShMemPanel;
private JPanel myPortPanel;
private PortField myPortField;
private JTextField myPortField;
private boolean myIsLocal = false;
private JButton myDebuggerSettings;
private JRadioButton mySocketTransport;
@@ -94,7 +93,6 @@ public class GenericDebuggerParametersRunnerConfigurable extends SettingsEditor<
myPortPanel.setVisible(isSocket());
myShMemPanel.setVisible(!isSocket());
myAddressField.setEditable(!myIsLocal);
myPortField.setEditable(!myIsLocal);
mySocketTransport.setEnabled(!myIsLocal);
myShmemTransport.setEnabled(!myIsLocal);
}
@@ -142,7 +140,7 @@ public class GenericDebuggerParametersRunnerConfigurable extends SettingsEditor<
private String getPort() {
if (isSocket()) {
return String.valueOf(myPortField.getNumber());
return String.valueOf(myPortField.getText());
}
else {
return myAddressField.getText();
@@ -150,10 +148,18 @@ public class GenericDebuggerParametersRunnerConfigurable extends SettingsEditor<
}
private void checkPort() throws ConfigurationException {
if (isSocket() && !myPortField.isSpecified()) {
if (isSocket() && parsePort() == 0) {
throw new ConfigurationException(DebuggerBundle.message("error.text.invalid.port"));
}
}
private int parsePort() {
try {
return Math.max(0, Integer.parseInt(myPortField.getText()));
}
catch (NumberFormatException e) {
return 0;
}
}
private void setTransport(int transport) {
mySocketTransport.setSelected(transport == DebuggerSettings.SOCKET_TRANSPORT);
@@ -168,7 +174,7 @@ public class GenericDebuggerParametersRunnerConfigurable extends SettingsEditor<
private void setPort(String port) {
if (isSocket()) {
myPortField.setNumber(StringUtilRt.parseInt(port, 0));
myPortField.setText(String.valueOf(StringUtilRt.parseInt(port, 0)));
}
else {
myAddressField.setText(port);
@@ -52,11 +52,13 @@
<text resource-bundle="messages/DebuggerBundle" key="label.generic.debugger.parameters.patcher.configurable.port"/>
</properties>
</component>
<component id="5ffe7" class="com.intellij.ui.PortField" binding="myPortField">
<component id="3f860" class="javax.swing.JTextField" binding="myPortField">
<constraints>
<grid row="0" column="1" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<properties>
<columns value="5"/>
</properties>
</component>
</children>
</grid>
@@ -35,9 +35,9 @@ public class ApplicationRunLineMarkerProvider extends RunLineMarkerContributor {
if (e instanceof PsiIdentifier) {
PsiElement element = e.getParent();
if (element instanceof PsiClass && PsiMethodUtil.findMainInClass((PsiClass)element) != null)
return new Info(ApplicationConfigurationType.getInstance().getIcon(), null, ExecutorAction.ACTIONS);
return new Info(ApplicationConfigurationType.getInstance().getIcon(), null, ExecutorAction.ACTIONS(0));
if (element instanceof PsiMethod && "main".equals(((PsiMethod)element).getName()) && PsiMethodUtil.isMainMethod((PsiMethod)element))
return new Info(ApplicationConfigurationType.getInstance().getIcon(), null, ExecutorAction.ACTIONS);
return new Info(ApplicationConfigurationType.getInstance().getIcon(), null, ExecutorAction.ACTIONS(0));
}
return null;
}
@@ -182,7 +182,7 @@ public class LibraryEditingUtil {
@Override
public Icon getIconFor(LibraryType aValue) {
return aValue != null ? aValue.getIcon() : PlatformIcons.LIBRARY_ICON;
return aValue != null ? aValue.getIcon(null) : PlatformIcons.LIBRARY_ICON;
}
@Override
@@ -38,6 +38,31 @@ import java.util.*;
public class LibraryPresentationManagerImpl extends LibraryPresentationManager {
private Map<LibraryKind, LibraryPresentationProvider<?>> myPresentationProviders;
public static List<LibraryKind> getLibraryKinds(@NotNull Library library, @Nullable StructureConfigurableContext context) {
final List<LibraryKind> result = new SmartList<LibraryKind>();
final LibraryKind kind = ((LibraryEx)library).getKind();
if (kind != null) {
result.add(kind);
}
final VirtualFile[] files = getLibraryFiles(library, context);
LibraryDetectionManager.getInstance().processProperties(Arrays.asList(files), new LibraryDetectionManager.LibraryPropertiesProcessor() {
@Override
public <P extends LibraryProperties> boolean processProperties(@NotNull LibraryKind kind, @NotNull P properties) {
result.add(kind);
return true;
}
});
return result;
}
@NotNull
private static VirtualFile[] getLibraryFiles(@NotNull Library library, @Nullable StructureConfigurableContext context) {
if (((LibraryEx)library).isDisposed()) {
return VirtualFile.EMPTY_ARRAY;
}
return context != null ? context.getLibraryFiles(library, OrderRootType.CLASSES) : library.getFiles(OrderRootType.CLASSES);
}
private <P extends LibraryProperties> LibraryPresentationProvider<P> getPresentationProvider(LibraryKind kind) {
if (myPresentationProviders == null) {
final Map<LibraryKind, LibraryPresentationProvider<?>> providers = new HashMap<LibraryKind, LibraryPresentationProvider<?>>();
@@ -62,9 +87,10 @@ public class LibraryPresentationManagerImpl extends LibraryPresentationManager {
@Override
public Icon getCustomIcon(@NotNull Library library, StructureConfigurableContext context) {
final LibraryKind kind = ((LibraryEx)library).getKind();
LibraryEx libraryEx = (LibraryEx)library;
final LibraryKind kind = libraryEx.getKind();
if (kind != null) {
return LibraryType.findByKind(kind).getIcon();
return LibraryType.findByKind(kind).getIcon(libraryEx.getProperties());
}
final List<Icon> icons = getCustomIcons(library, context);
if (icons.size() == 1) {
@@ -83,7 +109,7 @@ public class LibraryPresentationManagerImpl extends LibraryPresentationManager {
public <P extends LibraryProperties> boolean processProperties(@NotNull LibraryKind kind, @NotNull P properties) {
final LibraryPresentationProvider<P> provider = getPresentationProvider(kind);
if (provider != null) {
ContainerUtil.addIfNotNull(icons, provider.getIcon());
ContainerUtil.addIfNotNull(icons, provider.getIcon(properties));
}
return true;
}
@@ -117,23 +143,6 @@ public class LibraryPresentationManagerImpl extends LibraryPresentationManager {
});
}
public static List<LibraryKind> getLibraryKinds(@NotNull Library library, @Nullable StructureConfigurableContext context) {
final List<LibraryKind> result = new SmartList<LibraryKind>();
final LibraryKind kind = ((LibraryEx)library).getKind();
if (kind != null) {
result.add(kind);
}
final VirtualFile[] files = getLibraryFiles(library, context);
LibraryDetectionManager.getInstance().processProperties(Arrays.asList(files), new LibraryDetectionManager.LibraryPropertiesProcessor() {
@Override
public <P extends LibraryProperties> boolean processProperties(@NotNull LibraryKind kind, @NotNull P properties) {
result.add(kind);
return true;
}
});
return result;
}
@NotNull
@Override
public List<String> getDescriptions(@NotNull Library library, StructureConfigurableContext context) {
@@ -141,14 +150,6 @@ public class LibraryPresentationManagerImpl extends LibraryPresentationManager {
return getDescriptions(files, Collections.<LibraryKind>emptySet());
}
@NotNull
private static VirtualFile[] getLibraryFiles(@NotNull Library library, @Nullable StructureConfigurableContext context) {
if (((LibraryEx)library).isDisposed()) {
return VirtualFile.EMPTY_ARRAY;
}
return context != null ? context.getLibraryFiles(library, OrderRootType.CLASSES) : library.getFiles(OrderRootType.CLASSES);
}
@NotNull
@Override
public List<String> getDescriptions(@NotNull VirtualFile[] classRoots, final Set<LibraryKind> excludedKinds) {
@@ -61,20 +61,6 @@ public class CreateNewLibraryAction extends DumbAwareAction {
myProject = project;
}
@Override
public void actionPerformed(AnActionEvent e) {
Library library =
createLibrary(myType, myLibrariesConfigurable.getTree(), myProject, myLibrariesConfigurable.getModelProvider().getModifiableModel());
if (library == null) return;
final BaseLibrariesConfigurable rootConfigurable = ProjectStructureConfigurable.getInstance(myProject).getConfigurableFor(library);
final DefaultMutableTreeNode
libraryNode = MasterDetailsComponent.findNodeByObject((TreeNode)rootConfigurable.getTree().getModel().getRoot(), library);
rootConfigurable.selectNodeInTree(libraryNode);
LibraryEditingUtil.showDialogAndAddLibraryToDependencies(library, myProject, true);
}
@Nullable
public static Library createLibrary(@Nullable final LibraryType type, @NotNull final JComponent parentComponent,
@NotNull final Project project, @NotNull final LibrariesModifiableModel modifiableModel) {
@@ -82,7 +68,8 @@ public class CreateNewLibraryAction extends DumbAwareAction {
if (configuration == null) return null;
final LibraryType<?> libraryType = configuration.getLibraryType();
final Library library = modifiableModel.createLibrary(
LibraryEditingUtil.suggestNewLibraryName(modifiableModel, configuration.getDefaultLibraryName()), libraryType != null ? libraryType.getKind() : null);
LibraryEditingUtil.suggestNewLibraryName(modifiableModel, configuration.getDefaultLibraryName()),
libraryType != null ? libraryType.getKind() : null);
final NewLibraryEditor editor = new NewLibraryEditor(libraryType, configuration.getProperties());
configuration.addRoots(editor);
@@ -136,9 +123,22 @@ public class CreateNewLibraryAction extends DumbAwareAction {
for (LibraryType<?> type : suitableTypes) {
final String actionName = type.getCreateActionName();
if (actionName != null) {
actions.add(new CreateNewLibraryAction(actionName, type.getIcon(), type, librariesConfigurable, project));
actions.add(new CreateNewLibraryAction(actionName, type.getIcon(null), type, librariesConfigurable, project));
}
}
return actions.toArray(new AnAction[actions.size()]);
}
@Override
public void actionPerformed(AnActionEvent e) {
Library library =
createLibrary(myType, myLibrariesConfigurable.getTree(), myProject, myLibrariesConfigurable.getModelProvider().getModifiableModel());
if (library == null) return;
final BaseLibrariesConfigurable rootConfigurable = ProjectStructureConfigurable.getInstance(myProject).getConfigurableFor(library);
final DefaultMutableTreeNode
libraryNode = MasterDetailsComponent.findNodeByObject((TreeNode)rootConfigurable.getTree().getModel().getRoot(), library);
rootConfigurable.selectNodeInTree(libraryNode);
LibraryEditingUtil.showDialogAndAddLibraryToDependencies(library, myProject, true);
}
}
@@ -19,6 +19,8 @@ import com.intellij.codeInsight.FileModificationService;
import com.intellij.codeInsight.daemon.GroupNames;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Condition;
import com.intellij.openapi.util.Conditions;
import com.intellij.pom.java.LanguageLevel;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
@@ -217,7 +219,26 @@ public class LambdaCanBeMethodReferenceInspection extends BaseJavaBatchLocalInsp
}
private static boolean checkQualifier(PsiElement qualifier) {
return !(qualifier instanceof PsiCallExpression);
if (qualifier == null) {
return true;
}
final Condition<PsiElement> callExpressionCondition = Conditions.instanceOf(PsiCallExpression.class);
final Condition<PsiElement> nonFinalFieldRefCondition = new Condition<PsiElement>() {
@Override
public boolean value(PsiElement expression) {
if (expression instanceof PsiReferenceExpression) {
PsiElement element = ((PsiReferenceExpression)expression).resolve();
if (element instanceof PsiField && !((PsiField)element).hasModifierProperty(PsiModifier.FINAL)) {
return true;
}
}
return false;
}
};
return SyntaxTraverser
.psiTraverser()
.withRoot(qualifier)
.filter(Conditions.or(callExpressionCondition, nonFinalFieldRefCondition)).toList().isEmpty();
}
@Nullable
@@ -26,11 +26,9 @@ import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
import org.jetbrains.annotations.NotNull;
public class DefaultInsertHandler extends TemplateInsertHandler implements Cloneable {
public class DefaultInsertHandler implements InsertHandler {
public static final DefaultInsertHandler NO_TAIL_HANDLER = new DefaultInsertHandler(){
@Override
@@ -40,13 +38,9 @@ public class DefaultInsertHandler extends TemplateInsertHandler implements Clone
};
@Override
public void handleInsert(final InsertionContext context, LookupElement item) {
super.handleInsert(context, item);
handleInsertInner(context, (LookupItem)item, context.getCompletionChar());
}
private void handleInsertInner(InsertionContext context, LookupItem item, final char completionChar) {
public void handleInsert(final InsertionContext context, LookupElement lookupElement) {
LookupItem item = (LookupItem)lookupElement;
char completionChar = context.getCompletionChar();
final Project project = context.getProject();
final Editor editor = context.getEditor();
final Document document = editor.getDocument();
@@ -170,11 +164,6 @@ public class DefaultInsertHandler extends TemplateInsertHandler implements Clone
return editor.getCaretModel().getOffset();
}
@Override
protected void populateInsertMap(@NotNull final PsiFile file, @NotNull final OffsetMap offsetMap) {
JavaCompletionUtil.initOffsets(file, offsetMap);
}
public static class InsertHandlerState{
int tailOffset;
int caretOffset;
@@ -250,7 +250,6 @@ public class JavaMethodCallElement extends LookupItem<PsiMethod> implements Type
presentation.setIcon(DefaultLookupItemRenderer.getRawIcon(this, presentation.isReal()));
presentation.setStrikeout(JavaElementLookupRenderer.isToStrikeout(this));
presentation.setItemTextBold(getAttribute(HIGHLIGHTED_ATTR) != null);
MemberLookupHelper helper = myHelper != null ? myHelper : new MemberLookupHelper(myMethod, myContainingClass, false, false);
final Boolean qualify = getAttribute(FORCE_QUALIFY) != null ? Boolean.TRUE : myHelper == null ? Boolean.FALSE : null;
@@ -147,11 +147,9 @@ public class JavaPsiClassReferenceElement extends LookupItem<Object> {
presentation.setIcon(DefaultLookupItemRenderer.getRawIcon(item, presentation.isReal()));
}
final boolean bold = item.getAttribute(LookupItem.HIGHLIGHTED_ATTR) != null;
boolean strikeout = JavaElementLookupRenderer.isToStrikeout(item);
presentation.setItemText(getName(psiClass, item, diamond));
presentation.setStrikeout(strikeout);
presentation.setItemTextBold(bold);
String tailText = getLocationString(item);
PsiSubstitutor substitutor = (PsiSubstitutor)item.getAttribute(LookupItem.SUBSTITUTOR);
@@ -1,32 +1,29 @@
package com.intellij.codeInsight.completion;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.TypedLookupItem;
import com.intellij.codeInsight.template.Template;
import com.intellij.codeInsight.template.impl.LiveTemplateLookupElementImpl;
import com.intellij.codeInsight.template.impl.TemplateImpl;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiType;
import com.intellij.util.IncorrectOperationException;
import org.jetbrains.annotations.NonNls;
/**
* @author peter
*/
public class SmartCompletionTemplateItem extends LookupItem<Template> implements TypedLookupItem {
@NonNls private static final String PLACEHOLDER = "xxx";
public class SmartCompletionTemplateItem extends LiveTemplateLookupElementImpl implements TypedLookupItem {
private final PsiElement myContext;
public SmartCompletionTemplateItem(Template o, PsiElement context) {
super(o, o.getKey());
public SmartCompletionTemplateItem(TemplateImpl template, PsiElement context) {
super(template, false);
myContext = context;
}
@Override
public PsiType getType() {
final Template template = getObject();
final Template template = getTemplate();
String text = template.getTemplateText();
StringBuilder resultingText = new StringBuilder(text);
@@ -37,9 +34,7 @@ public class SmartCompletionTemplateItem extends LookupItem<Template> implements
continue;
}
int segmentOffset = template.getSegmentOffset(j);
resultingText.insert(segmentOffset, PLACEHOLDER);
resultingText.insert(template.getSegmentOffset(j), "xxx");
}
try {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -27,7 +27,7 @@ public class AnonymousTargetClassPreselectionUtil {
public static void rememberSelection(PsiClass aClass, PsiClass firstClass) {
if (firstClass instanceof PsiAnonymousClass) {
PropertiesComponent.getInstance().setValue(PRESELECT_ANONYMOUS, String.valueOf(aClass == firstClass));
PropertiesComponent.getInstance().setValue(PRESELECT_ANONYMOUS, aClass == firstClass);
}
}
@@ -87,7 +87,7 @@ public class JetBrainsAnnotationsExternalLibraryResolver extends ExternalLibrary
private static abstract class JetBrainsAnnotationsLibraryDescriptor extends ExternalLibraryDescriptor {
public JetBrainsAnnotationsLibraryDescriptor() {
super("com.intellij", "annotations", null);
super("com.intellij", "annotations");
}
}
}
@@ -86,7 +86,7 @@ public class JavaOverrideImplementMemberChooser extends MemberChooser<PsiMethodM
final JavaOverrideImplementMemberChooser javaOverrideImplementMemberChooser =
new JavaOverrideImplementMemberChooser(all, onlyPrimary, lazyElementsWithPercent, project, PsiUtil.isLanguageLevel5OrHigher(aClass),
merge, toImplement, PropertiesComponent.getInstance(project)
.getBoolean(PROP_OVERRIDING_SORTED_OVERRIDE_IMPLEMENT, false));
.getBoolean(PROP_OVERRIDING_SORTED_OVERRIDE_IMPLEMENT));
javaOverrideImplementMemberChooser.setTitle(getChooserTitle(toImplement, merge));
javaOverrideImplementMemberChooser.setCopyJavadocVisible(true);
@@ -151,8 +151,8 @@ public class JavaOverrideImplementMemberChooser extends MemberChooser<PsiMethodM
@Override
protected void doOKAction() {
super.doOKAction();
PropertiesComponent.getInstance(myProject).setValue(PROP_COMBINED_OVERRIDE_IMPLEMENT, String.valueOf(myMerge));
PropertiesComponent.getInstance(myProject).setValue(PROP_OVERRIDING_SORTED_OVERRIDE_IMPLEMENT, String.valueOf(mySortedByOverriding));
PropertiesComponent.getInstance(myProject).setValue(PROP_COMBINED_OVERRIDE_IMPLEMENT, myMerge, true);
PropertiesComponent.getInstance(myProject).setValue(PROP_OVERRIDING_SORTED_OVERRIDE_IMPLEMENT, mySortedByOverriding);
}
@Override
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -21,7 +21,10 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.*;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiNameHelper;
import com.intellij.psi.PsiType;
import com.intellij.refactoring.ui.TypeSelector;
import com.intellij.ui.DocumentAdapter;
import org.jetbrains.annotations.NonNls;
@@ -64,7 +67,7 @@ public class CreateFieldFromParameterDialog extends DialogWrapper {
@Override
protected void doOKAction() {
if (myCbFinal.isEnabled()) {
PropertiesComponent.getInstance().setValue(PROPERTY_NAME, String.valueOf(myCbFinal.isSelected()));
PropertiesComponent.getInstance().setValue(PROPERTY_NAME, myCbFinal.isSelected());
}
final PsiField[] fields = myTargetClass.getFields();
@@ -29,6 +29,8 @@ import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.JavaSdk;
import com.intellij.openapi.projectRoots.JavaSdkVersion;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.PackageIndex;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.JDOMUtil;
import com.intellij.openapi.util.Pair;
@@ -383,23 +385,52 @@ public class JavaDocInfoGenerator {
return null;
if (docURLs != null) {
if (buffer.length() == 0) {
buffer.append("<html><body></body></html>");
if (elementHasSourceCode()) {
LOG.debug("Documentation for " + myElement + " was generated from source code, it wasn't found at following URLs: ", docURLs);
}
else {
if (buffer.length() == 0) {
buffer.append("<html><body></body></html>");
}
String errorSection = "<p id=\"error\">Following external urls were checked:<br>&nbsp;&nbsp;&nbsp;<i>" +
StringUtil.join(docURLs, new Function<String, String>() {
@Override
public String fun(String url) {
return XmlStringUtil.escapeString(url);
}
}, "</i><br>&nbsp;&nbsp;&nbsp;<i>") +
"</i><br>The documentation for this element is not found. Please add all the needed paths to API docs in " +
"<a href=\"open://Project Settings\">Project Settings.</a></p>";
buffer.insert(buffer.indexOf("<body>"), errorSection);
}
String errorSection = "<p id=\"error\">Following external urls were checked:<br>&nbsp;&nbsp;&nbsp;<i>" +
StringUtil.join(docURLs, new Function<String, String>() {
@Override
public String fun(String url) {
return XmlStringUtil.escapeString(url);
}
}, "</i><br>&nbsp;&nbsp;&nbsp;<i>") +
"</i><br>The documentation for this element is not found. Please add all the needed paths to API docs in " +
"<a href=\"open://Project Settings\">Project Settings.</a></p>";
buffer.insert(buffer.indexOf("<body>"), errorSection);
}
return fixupDoc(buffer);
}
private boolean elementHasSourceCode() {
VirtualFile[] files;
if (myElement instanceof PsiDirectory) {
final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage((PsiDirectory)myElement);
if (aPackage == null) return false;
files = PackageIndex.getInstance(myProject).getDirectoriesByPackageName(aPackage.getQualifiedName(), true);
}
else if (myElement instanceof PsiPackage) {
files = PackageIndex.getInstance(myProject).getDirectoriesByPackageName(((PsiPackage)myElement).getQualifiedName(), true);
}
else {
PsiFile containingFile = myElement.getNavigationElement().getContainingFile();
if (containingFile == null) return false;
VirtualFile virtualFile = containingFile.getVirtualFile();
if (virtualFile == null) return false;
files = new VirtualFile[] {virtualFile};
}
ProjectFileIndex projectFileIndex = ProjectFileIndex.SERVICE.getInstance(myProject);
for (VirtualFile file : files) {
if (projectFileIndex.isInSource(file)) return true;
}
return false;
}
private void generateClassJavaDoc(@NonNls StringBuilder buffer, PsiClass aClass, boolean generatePrologueAndEpilogue) {
if (aClass instanceof PsiAnonymousClass) return;
if (generatePrologueAndEpilogue)
@@ -652,7 +683,10 @@ public class JavaDocInfoGenerator {
}
private void generatePackageJavaDoc(final StringBuilder buffer, final PsiPackage psiPackage, boolean generatePrologueAndEpilogue) {
for(PsiDirectory directory: psiPackage.getDirectories()) {
VirtualFile[] dirs = PackageIndex.getInstance(myProject).getDirectoriesByPackageName(psiPackage.getQualifiedName(), true);
for (VirtualFile dir : dirs) {
PsiDirectory directory = PsiManager.getInstance(myProject).findDirectory(dir);
if (directory == null) continue;
final PsiFile packageInfoFile = directory.findFile(PsiPackage.PACKAGE_INFO_FILE);
if (packageInfoFile != null) {
final ASTNode node = packageInfoFile.getNode();
@@ -275,7 +275,7 @@ public class PsiTypeLookupItem extends LookupItem {
}
presentation.setItemText(((PsiType)object).getCanonicalText());
presentation.setItemTextBold(getAttribute(LookupItem.HIGHLIGHTED_ATTR) != null || object instanceof PsiPrimitiveType);
presentation.setItemTextBold(object instanceof PsiPrimitiveType);
if (isAddArrayInitializer()) {
presentation.setTailText("{...}");
}
@@ -20,6 +20,7 @@ import com.intellij.codeInsight.TailType;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.daemon.impl.JavaColorProvider;
import com.intellij.codeInsight.daemon.impl.analysis.HighlightControlFlowUtil;
import com.intellij.codeInsight.lookup.impl.JavaElementLookupRenderer;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.RangeMarker;
@@ -92,6 +93,7 @@ public class VariableLookupItem extends LookupItem<PsiVariable> implements Typed
}
@Override
@NotNull
public PsiType getType() {
return getSubstitutor().substitute(getObject().getType());
}
@@ -124,12 +126,25 @@ public class VariableLookupItem extends LookupItem<PsiVariable> implements Typed
@Override
public void renderElement(LookupElementPresentation presentation) {
super.renderElement(presentation);
boolean qualify = getAttribute(FORCE_QUALIFY) != null;
PsiVariable variable = getObject();
String name = variable.getName();
if (qualify && variable instanceof PsiField && ((PsiField)variable).getContainingClass() != null) {
name = ((PsiField)variable).getContainingClass().getName() + "." + name;
}
presentation.setItemText(name);
presentation.setIcon(DefaultLookupItemRenderer.getRawIcon(this, presentation.isReal()));
presentation.setStrikeout(JavaElementLookupRenderer.isToStrikeout(this));
if (myHelper != null) {
myHelper.renderElement(presentation, getAttribute(FORCE_QUALIFY) != null ? Boolean.TRUE : null, getSubstitutor());
myHelper.renderElement(presentation, qualify ? Boolean.TRUE : null, getSubstitutor());
}
if (myColor != null) {
presentation.setTypeText("", new ColorIcon(12, myColor));
} else {
presentation.setTypeText(getType().getPresentableText());
}
}
@@ -19,7 +19,6 @@ import com.intellij.codeInsight.completion.JavaCompletionUtil;
import com.intellij.codeInsight.lookup.DefaultLookupItemRenderer;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.beanProperties.BeanPropertyElement;
@@ -34,8 +33,7 @@ import java.util.List;
public class JavaElementLookupRenderer implements ElementLookupRenderer {
@Override
public boolean handlesItem(final Object element) {
return element instanceof PsiVariable ||
element instanceof PsiKeyword || element instanceof PsiExpression ||
return element instanceof PsiKeyword || element instanceof PsiExpression ||
element instanceof PsiTypeElement || element instanceof BeanPropertyElement;
}
@@ -45,7 +43,6 @@ public class JavaElementLookupRenderer implements ElementLookupRenderer {
presentation.setItemText(getName(element, item));
presentation.setStrikeout(isToStrikeout(item));
presentation.setItemTextBold(item.getAttribute(LookupItem.HIGHLIGHTED_ATTR) != null);
presentation.setTailText((String)item.getAttribute(LookupItem.TAIL_TEXT_ATTR), item.getAttribute(LookupItem.TAIL_TEXT_SMALL_ATTR) != null);
@@ -69,18 +66,6 @@ public class JavaElementLookupRenderer implements ElementLookupRenderer {
}
}
}
else if (o instanceof PsiArrayType) {
name = ((PsiArrayType)o).getDeepComponentType().getPresentableText();
}
else if (o instanceof PsiType) {
name = ((PsiType)o).getPresentableText();
}
if (item.getAttribute(LookupItem.FORCE_QUALIFY) != null) {
if (o instanceof PsiMember && ((PsiMember)o).getContainingClass() != null) {
name = ((PsiMember)o).getContainingClass().getName() + "." + name;
}
}
return StringUtil.notNullize(name);
}
@@ -91,15 +76,7 @@ public class JavaElementLookupRenderer implements ElementLookupRenderer {
if (o instanceof PsiElement) {
final PsiElement element = (PsiElement)o;
if (element.isValid()) {
if (element instanceof PsiVariable){
PsiVariable variable = (PsiVariable)element;
PsiType type = variable.getType();
if (item instanceof VariableLookupItem) {
type = ((VariableLookupItem)item).getSubstitutor().substitute(type);
}
text = type.getPresentableText();
}
else if (element instanceof PsiExpression){
if (element instanceof PsiExpression){
PsiExpression expression = (PsiExpression)element;
PsiType type = expression.getType();
if (type != null){
@@ -32,7 +32,7 @@ import java.util.List;
*/
public class JCiPExternalLibraryResolver extends ExternalLibraryResolver {
private static final ExternalLibraryDescriptor JDCIP_LIBRARY_DESCRIPTOR =
new ExternalLibraryDescriptor("net.jcip", "jcip-annotations", null) {
new ExternalLibraryDescriptor("net.jcip", "jcip-annotations") {
@NotNull
@Override
public List<String> getLibraryClassesRoots() {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -78,7 +78,7 @@ public class InferNullityAnnotationsAction extends BaseAnalysisAction {
@Override
protected void analyze(@NotNull final Project project, @NotNull final AnalysisScope scope) {
PropertiesComponent.getInstance().setValue(ANNOTATE_LOCAL_VARIABLES, String.valueOf(myAnnotateLocalVariablesCb.isSelected()));
PropertiesComponent.getInstance().setValue(ANNOTATE_LOCAL_VARIABLES, myAnnotateLocalVariablesCb.isSelected());
final ProgressManager progressManager = ProgressManager.getInstance();
final Set<Module> modulesWithoutAnnotations = new HashSet<Module>();
@@ -344,7 +344,7 @@ public class InferNullityAnnotationsAction extends BaseAnalysisAction {
protected JComponent getAdditionalActionSettings(Project project, BaseAnalysisActionDialog dialog) {
final JPanel panel = new JPanel(new VerticalFlowLayout());
panel.add(new TitledSeparator());
myAnnotateLocalVariablesCb = new JCheckBox("Annotate local variables", PropertiesComponent.getInstance().getBoolean(ANNOTATE_LOCAL_VARIABLES, false));
myAnnotateLocalVariablesCb = new JCheckBox("Annotate local variables", PropertiesComponent.getInstance().getBoolean(ANNOTATE_LOCAL_VARIABLES));
panel.add(myAnnotateLocalVariablesCb);
return panel;
}
@@ -202,7 +202,7 @@ public class PackageChooserDialog extends PackageChooser {
private void toggleShowPathComponent(JPanel northPanel, TextFieldAction fieldAction) {
boolean toShowTextField = !isPathShowing();
PropertiesComponent.getInstance().setValue(FileChooserDialogImpl.FILE_CHOOSER_SHOW_PATH_PROPERTY, Boolean.toString(toShowTextField));
PropertiesComponent.getInstance().setValue(FileChooserDialogImpl.FILE_CHOOSER_SHOW_PATH_PROPERTY, toShowTextField, true);
myPathEditor.setVisible(toShowTextField);
fieldAction.update();
northPanel.revalidate();
@@ -1,16 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.javadoc.JavadocGenerationPanel">
<grid id="a2c87" binding="myPanel" layout-manager="GridLayoutManager" row-count="8" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="7">
<grid id="a2c87" binding="myPanel" layout-manager="GridLayoutManager" row-count="9" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="7">
<margin top="2" left="5" bottom="0" right="5"/>
<constraints>
<xy x="47" y="80" width="511" height="440"/>
<xy x="47" y="80" width="511" height="455"/>
</constraints>
<properties/>
<border type="none"/>
<children>
<component id="34b10" class="javax.swing.JLabel">
<constraints>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="eefb8"/>
@@ -19,7 +19,7 @@
</component>
<component id="eefb8" class="javax.swing.JTextField" binding="myOtherOptionsField">
<constraints>
<grid row="4" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<grid row="5" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
@@ -28,7 +28,7 @@
<grid id="35953" layout-manager="GridLayoutManager" row-count="1" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<grid row="2" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
<grid row="3" column="0" row-span="1" col-span="2" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
@@ -172,7 +172,7 @@
</grid>
<component id="7c67a" class="javax.swing.JLabel">
<constraints>
<grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
<grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="61630"/>
@@ -181,7 +181,7 @@
</component>
<component id="61630" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myTfOutputDir">
<constraints>
<grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<grid row="2" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
@@ -189,7 +189,7 @@
</component>
<component id="d6470" class="javax.swing.JLabel">
<constraints>
<grid row="5" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
<grid row="6" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="c592b"/>
@@ -198,7 +198,7 @@
</component>
<component id="c592b" class="javax.swing.JTextField" binding="myHeapSizeField">
<constraints>
<grid row="5" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<grid row="6" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
@@ -208,7 +208,7 @@
</component>
<component id="61bae" class="javax.swing.JCheckBox" binding="myOpenInBrowserCheckBox">
<constraints>
<grid row="6" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
<grid row="7" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<borderPaintedFlat value="false"/>
@@ -221,12 +221,12 @@
</component>
<vspacer id="b3b4c">
<constraints>
<grid row="7" column="1" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
<grid row="8" column="1" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="b7872" class="javax.swing.JLabel">
<constraints>
<grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
<grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<labelFor value="3b6ec"/>
@@ -235,7 +235,7 @@
</component>
<component id="3b6ec" class="javax.swing.JTextField" binding="myLocaleTextField">
<constraints>
<grid row="3" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<grid row="4" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
<preferred-size width="150" height="-1"/>
</grid>
</constraints>
@@ -250,6 +250,15 @@
<text value="Include jdk and library sources in -sourcepath"/>
</properties>
</component>
<component id="44709" class="javax.swing.JCheckBox" binding="myLinkToJdkDocs">
<constraints>
<grid row="1" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<margin top="0" left="8" bottom="10" right="3"/>
<text value="Link to JDK documentation (use -link option)"/>
</properties>
</component>
</children>
</grid>
</form>
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -31,6 +31,7 @@ public final class JavadocConfigurable implements Configurable {
public JComponent createComponent() {
myPanel = new JavadocGenerationPanel();
myPanel.myLinkToJdkDocs.setEnabled(myConfiguration.sdkHasJavadocUrls());
return myPanel.myPanel;
}
@@ -51,6 +52,7 @@ public final class JavadocConfigurable implements Configurable {
configuration.OPTION_DOCUMENT_TAG_DEPRECATED = myPanel.myTagDeprecated.isSelected();
configuration.OPTION_DEPRECATED_LIST = myPanel.myDeprecatedList.isSelected();
configuration.OPTION_INCLUDE_LIBS = myPanel.myIncludeLibraryCb.isSelected();
configuration.OPTION_LINK_TO_JDK_DOCS = myPanel.myLinkToJdkDocs.isSelected();
}
public void loadFrom(JavadocConfiguration configuration) {
@@ -74,6 +76,7 @@ public final class JavadocConfigurable implements Configurable {
myPanel.myDeprecatedList.setEnabled(myPanel.myTagDeprecated.isSelected());
myPanel.myIncludeLibraryCb.setSelected(configuration.OPTION_INCLUDE_LIBS);
myPanel.myLinkToJdkDocs.setSelected(configuration.OPTION_LINK_TO_JDK_DOCS);
}
public boolean isModified() {
@@ -95,6 +98,7 @@ public final class JavadocConfigurable implements Configurable {
isModified |= myPanel.myTagDeprecated.isSelected() != configuration.OPTION_DOCUMENT_TAG_DEPRECATED;
isModified |= myPanel.myDeprecatedList.isSelected() != configuration.OPTION_DEPRECATED_LIST;
isModified |= myPanel.myIncludeLibraryCb.isSelected() != configuration.OPTION_INCLUDE_LIBS;
isModified |= myPanel.myLinkToJdkDocs.isSelected() != configuration.OPTION_LINK_TO_JDK_DOCS;
return isModified;
}
@@ -41,6 +41,7 @@ import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.*;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.util.PathsList;
@@ -85,6 +86,7 @@ public class JavadocConfiguration implements ModuleRunProfile, JDOMExternalizabl
private AnalysisScope myGenerationScope;
private static final Logger LOGGER = Logger.getInstance("#" + JavadocConfiguration.class.getName());
public boolean OPTION_INCLUDE_LIBS = false;
public boolean OPTION_LINK_TO_JDK_DOCS = false;
public void setGenerationScope(AnalysisScope generationScope) {
myGenerationScope = generationScope;
@@ -128,6 +130,10 @@ public class JavadocConfiguration implements ModuleRunProfile, JDOMExternalizabl
public void writeExternal(Element element) throws WriteExternalException {
DefaultJDOMExternalizer.writeExternal(this, element);
}
public boolean sdkHasJavadocUrls() {
return getSdk(myProject).getRootProvider().getFiles(JavadocOrderRootType.getInstance()).length > 0;
}
public static Sdk getSdk(@NotNull Project project) {
return PathUtilEx.getAnyJdk(project);
@@ -295,6 +301,14 @@ public class JavadocConfiguration implements ModuleRunProfile, JDOMExternalizabl
LOGGER.error(e);
}
if (OPTION_LINK_TO_JDK_DOCS) {
VirtualFile[] docUrls = jdk.getRootProvider().getFiles(JavadocOrderRootType.getInstance());
for (VirtualFile docUrl : docUrls) {
parameters.add("-link");
parameters.add(VfsUtil.toUri(docUrl).toString());
}
}
final PathsList classPath;
final OrderEnumerator orderEnumerator = ProjectRootManager.getInstance(myProject).orderEntries(modules);
if (jdk.getSdkType() instanceof JavaSdk) {
@@ -48,6 +48,7 @@ final class JavadocGenerationPanel extends JPanel {
JCheckBox myOpenInBrowserCheckBox;
JTextField myLocaleTextField;
JCheckBox myIncludeLibraryCb;
JCheckBox myLinkToJdkDocs;
JavadocGenerationPanel() {
myTfOutputDir.addBrowseFolderListener(JavadocBundle.message("javadoc.generate.output.directory.browse"), null, null, FileChooserDescriptorFactory.createSingleFolderDescriptor());
@@ -27,8 +27,10 @@ import com.intellij.lang.LangBundle;
import com.intellij.lang.LanguageCommenters;
import com.intellij.lang.documentation.CodeDocumentationProvider;
import com.intellij.lang.documentation.CompositeDocumentationProvider;
import com.intellij.lang.documentation.DocumentationProviderEx;
import com.intellij.lang.documentation.ExternalDocumentationProvider;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.IndexNotReadyException;
@@ -66,7 +68,7 @@ import java.util.Set;
/**
* @author Maxim.Mossienko
*/
public class JavaDocumentationProvider implements CodeDocumentationProvider, ExternalDocumentationProvider {
public class JavaDocumentationProvider extends DocumentationProviderEx implements CodeDocumentationProvider, ExternalDocumentationProvider {
private static final Logger LOG = Logger.getInstance("#" + JavaDocumentationProvider.class.getName());
private static final String LINE_SEPARATOR = "\n";
@@ -793,6 +795,19 @@ public class JavaDocumentationProvider implements CodeDocumentationProvider, Ext
public void promptToConfigureDocumentation(PsiElement element) {
}
@Nullable
@Override
public PsiElement getCustomDocumentationElement(@NotNull Editor editor, @NotNull PsiFile file, @Nullable PsiElement contextElement) {
PsiDocComment docComment = PsiTreeUtil.getParentOfType(contextElement, PsiDocComment.class, false);
if (docComment != null && JavaDocUtil.isInsidePackageInfo(docComment)) {
PsiDirectory directory = file.getContainingDirectory();
if (directory != null) {
return JavaDirectoryService.getInstance().getPackage(directory);
}
}
return null;
}
public static String fetchExternalJavadoc(PsiElement element, final Project project, final List<String> docURLs) {
return fetchExternalJavadoc(element, docURLs, new JavaDocExternalFilter(project));
}
@@ -27,11 +27,17 @@ public abstract class ExternalLibraryDescriptor {
private final String myLibraryGroupId;
private final String myLibraryArtifactId;
private final String myMinVersion;
private final String myMaxVersion;
public ExternalLibraryDescriptor(@NotNull String libraryGroupId, @NotNull String libraryArtifactId, @Nullable String minVersion) {
public ExternalLibraryDescriptor(String libraryGroupId, String libraryArtifactId) {
this(libraryGroupId, libraryArtifactId, null, null);
}
public ExternalLibraryDescriptor(@NotNull String libraryGroupId, @NotNull String libraryArtifactId, @Nullable String minVersion, @Nullable String maxVersion) {
myLibraryGroupId = libraryGroupId;
myLibraryArtifactId = libraryArtifactId;
myMinVersion = minVersion;
myMaxVersion = maxVersion;
}
@NotNull
@@ -49,6 +55,11 @@ public abstract class ExternalLibraryDescriptor {
return myMinVersion;
}
@Nullable
public String getMaxVersion() {
return myMaxVersion;
}
public String getPresentableName() {
return myLibraryArtifactId;
}
@@ -76,7 +76,6 @@ public class HelpID {
public static final String METHOD_DUPLICATES = "refactoring.replaceMethodCodeDuplicates";
public static final String CHANGE_CLASS_SIGNATURE = "change.class.signature.dialog";
public static final String MOVE_INSTANCE_METHOD = "refactoring.moveInstMethod";
public static final String INVERT_BOOLEAN = "refactoring.invertBoolean";
public static final String EXTRACT_METHOD_OBJECT = "refactoring.extractMethodObject";
public static final String REPLACE_CONSTRUCTOR_WITH_BUILDER = "refactoring.replaceConstructorWithBuilder";
@NonNls public static final String ExtractClass = "refactorj.extractClass";
@@ -193,7 +193,7 @@ public class ExtractMethodDialog extends DialogWrapper implements AbstractExtrac
}
if (myGenerateAnnotations != null && myGenerateAnnotations.isEnabled()) {
PropertiesComponent.getInstance(myProject).setValue(EXTRACT_METHOD_GENERATE_ANNOTATIONS, String.valueOf(myGenerateAnnotations.isSelected()));
PropertiesComponent.getInstance(myProject).setValue(EXTRACT_METHOD_GENERATE_ANNOTATIONS, myGenerateAnnotations.isSelected(), true);
}
super.doOKAction();
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -272,10 +272,10 @@ class IntroduceConstantDialog extends DialogWrapper {
LanguageLevelProjectExtension.getInstance(psiManager.getProject()).getLanguageLevel().isAtLeast(LanguageLevel.JDK_1_5) &&
JavaPsiFacade.getInstance(psiManager.getProject()).findClass(AnnotationUtil.NON_NLS, myParentClass.getResolveScope()) != null) {
final PropertiesComponent component = PropertiesComponent.getInstance(myProject);
myCbNonNls.setSelected(component.isTrueValue(NONNLS_SELECTED_PROPERTY));
myCbNonNls.setSelected(component.getBoolean(NONNLS_SELECTED_PROPERTY));
myCbNonNls.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
component.setValue(NONNLS_SELECTED_PROPERTY, Boolean.toString(myCbNonNls.isSelected()));
component.setValue(NONNLS_SELECTED_PROPERTY, myCbNonNls.isSelected());
}
});
} else {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -329,7 +329,7 @@ public abstract class IntroduceFieldCentralPanel {
public void saveFinalState() {
if (myCbFinal != null && myCbFinal.isEnabled()) {
ourLastCbFinalState = myCbFinal.isSelected();
PropertiesComponent.getInstance().setValue(INTRODUCE_FIELD_FINAL_CHECKBOX, String.valueOf(ourLastCbFinalState));
PropertiesComponent.getInstance().setValue(INTRODUCE_FIELD_FINAL_CHECKBOX, ourLastCbFinalState, true);
}
}
@@ -183,7 +183,7 @@ public abstract class IntroduceVariableBase extends IntroduceHandlerBase {
}
public static boolean isPreferStatements() {
return Boolean.valueOf(PropertiesComponent.getInstance().getBoolean(PREFER_STATEMENTS_OPTION, false)) || Registry.is(PREFER_STATEMENTS_OPTION, false);
return Boolean.valueOf(PropertiesComponent.getInstance().getBoolean(PREFER_STATEMENTS_OPTION)) || Registry.is(PREFER_STATEMENTS_OPTION, false);
}
public static List<PsiExpression> collectExpressions(final PsiFile file,
@@ -258,7 +258,7 @@ public class IntroduceParameterObjectDialog extends RefactoringDialog {
IntroduceParameterObjectDialog.this.doCancelAction();
}
};
myParamsPanel.add(paramsPanel, BorderLayout.NORTH);
myParamsPanel.add(paramsPanel, BorderLayout.CENTER);
return myWholePanel;
}
@@ -1,93 +0,0 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.refactoring.invertBoolean;
import com.intellij.ide.util.SuperMethodWarningUtil;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.refactoring.HelpID;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import org.jetbrains.annotations.NotNull;
/**
* @author ven
*/
public class InvertBooleanHandler implements RefactoringActionHandler {
static final String REFACTORING_NAME = RefactoringBundle.message("invert.boolean.title");
public void invoke(@NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
if (element instanceof PsiMethod) {
invoke((PsiMethod)element, project, editor);
}
else if (element instanceof PsiVariable) {
invoke((PsiVariable)element, project, editor);
}
else {
CommonRefactoringUtil.showErrorHint(project, editor, RefactoringBundle.getCannotRefactorMessage(
RefactoringBundle.message("error.wrong.caret.position.method.or.variable.name")), REFACTORING_NAME, HelpID.INVERT_BOOLEAN);
}
}
private static void invoke(PsiVariable var, final Project project, Editor editor) {
final PsiType returnType = var.getType();
if (!PsiType.BOOLEAN.equals(returnType)) {
CommonRefactoringUtil.showErrorHint(project, editor, RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("invert.boolean.wrong.type")), REFACTORING_NAME, HelpID.INVERT_BOOLEAN);
return;
}
if (var instanceof PsiParameter && ((PsiParameter)var).getDeclarationScope() instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)((PsiParameter)var).getDeclarationScope();
final PsiMethod superMethod = SuperMethodWarningUtil.checkSuperMethod(method, RefactoringBundle.message("to.refactor"));
if (superMethod == null) return;
var = superMethod.getParameterList().getParameters()[method.getParameterList().getParameterIndex((PsiParameter)var)];
}
new InvertBooleanDialog(var).show();
}
public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
if (elements.length == 1) {
if (elements[0] instanceof PsiMethod) {
invoke((PsiMethod)elements[0], project, null);
}
else if (elements[0] instanceof PsiVariable) {
invoke((PsiVariable)elements[0], project, null);
}
}
}
private static void invoke(PsiMethod method, final Project project, Editor editor) {
final PsiType returnType = method.getReturnType();
if (!PsiType.BOOLEAN.equals(returnType)) {
CommonRefactoringUtil.showErrorHint(project, editor, RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("invert.boolean.wrong.type")), REFACTORING_NAME, HelpID.INVERT_BOOLEAN);
return;
}
final PsiMethod superMethod = SuperMethodWarningUtil.checkSuperMethod(method, RefactoringBundle.message("to.refactor"));
if (superMethod == null) return;
method = superMethod;
new InvertBooleanDialog(method).show();
}
}
@@ -1,308 +0,0 @@
/*
* Copyright 2000-2015 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.refactoring.invertBoolean;
import com.intellij.codeInsight.CodeInsightServicesUtil;
import com.intellij.codeInsight.daemon.impl.RecursiveCallLineMarkerProvider;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.refactoring.BaseRefactoringProcessor;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.refactoring.rename.RenameUtil;
import com.intellij.refactoring.util.MoveRenameUsageInfo;
import com.intellij.usageView.UsageInfo;
import com.intellij.usageView.UsageViewDescriptor;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.Query;
import com.intellij.util.containers.HashMap;
import com.intellij.util.containers.HashSet;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
/**
* @author ven
*/
public class InvertBooleanProcessor extends BaseRefactoringProcessor {
private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.invertBoolean.InvertBooleanMethodProcessor");
private PsiNamedElement myElement;
private final String myNewName;
private final RenameProcessor myRenameProcessor;
private final Map<UsageInfo, SmartPsiElementPointer> myToInvert = new HashMap<UsageInfo, SmartPsiElementPointer>();
private final SmartPointerManager mySmartPointerManager;
public InvertBooleanProcessor(final PsiNamedElement namedElement, final String newName) {
super(namedElement.getProject());
myElement = namedElement;
myNewName = newName;
final Project project = namedElement.getProject();
myRenameProcessor = Comparing.equal(namedElement.getName(), myNewName) ? null : new RenameProcessor(project, namedElement, newName, false, false);
mySmartPointerManager = SmartPointerManager.getInstance(project);
}
@Override
@NotNull
protected UsageViewDescriptor createUsageViewDescriptor(@NotNull UsageInfo[] usages) {
return new InvertBooleanUsageViewDescriptor(myElement);
}
@Override
protected boolean preprocessUsages(@NotNull Ref<UsageInfo[]> refUsages) {
final MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
for (UsageInfo info : myToInvert.keySet()) {
final PsiElement element = info.getElement();
if (element instanceof PsiMethodReferenceExpression) {
conflicts.putValue(element, "Method is used in method reference expression");
}
}
if (!conflicts.isEmpty()) {
return showConflicts(conflicts, null);
}
if (myRenameProcessor == null || myRenameProcessor.preprocessUsages(refUsages)) {
prepareSuccessful();
return true;
}
return false;
}
@Override
@NotNull
protected UsageInfo[] findUsages() {
final List<SmartPsiElementPointer> toInvert = new ArrayList<SmartPsiElementPointer>();
addRefsToInvert(toInvert, myElement);
if (myElement instanceof PsiMethod) {
final Collection<PsiMethod> overriders = OverridingMethodsSearch.search((PsiMethod)myElement).findAll();
if (myRenameProcessor != null) {
for (PsiMethod overrider : overriders) {
myRenameProcessor.addElement(overrider, myNewName);
}
}
Collection<PsiMethod> allMethods = new HashSet<PsiMethod>(overriders);
allMethods.add((PsiMethod)myElement);
for (PsiMethod method : allMethods) {
method.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitReturnStatement(PsiReturnStatement statement) {
final PsiExpression returnValue = statement.getReturnValue();
if (returnValue != null && PsiType.BOOLEAN.equals(returnValue.getType())) {
toInvert.add(mySmartPointerManager.createSmartPsiElementPointer(returnValue));
}
}
@Override
public void visitClass(PsiClass aClass) {}
@Override
public void visitLambdaExpression(PsiLambdaExpression expression) {}
});
}
} else if (myElement instanceof PsiParameter && ((PsiParameter)myElement).getDeclarationScope() instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)((PsiParameter)myElement).getDeclarationScope();
int index = method.getParameterList().getParameterIndex((PsiParameter)myElement);
LOG.assertTrue(index >= 0);
final Query<PsiReference> methodQuery = MethodReferencesSearch.search(method);
final Collection<PsiReference> methodRefs = methodQuery.findAll();
for (PsiReference ref : methodRefs) {
PsiElement parent = ref.getElement().getParent();
if (parent instanceof PsiAnonymousClass) {
parent = parent.getParent();
}
if (parent instanceof PsiCall) {
final PsiCall call = (PsiCall)parent;
final PsiReferenceExpression methodExpression = call instanceof PsiMethodCallExpression ?
((PsiMethodCallExpression)call).getMethodExpression() :
null;
final PsiExpressionList argumentList = call.getArgumentList();
if (argumentList != null) {
final PsiExpression[] args = argumentList.getExpressions();
if (index < args.length) {
if (methodExpression == null ||
canInvert(methodExpression, args[index] instanceof PsiReferenceExpression && ((PsiReferenceExpression)args[index]).resolve() == myElement)) {
toInvert.add(mySmartPointerManager.createSmartPsiElementPointer(args[index]));
}
}
}
}
}
final Collection<PsiMethod> overriders = OverridingMethodsSearch.search(method).findAll();
for (PsiMethod overrider : overriders) {
final PsiParameter overriderParameter = overrider.getParameterList().getParameters()[index];
if (myRenameProcessor != null) {
myRenameProcessor.addElement(overriderParameter, myNewName);
}
addRefsToInvert(toInvert, overriderParameter);
}
}
final UsageInfo[] renameUsages = myRenameProcessor != null ? myRenameProcessor.findUsages() : UsageInfo.EMPTY_ARRAY;
final SmartPsiElementPointer[] usagesToInvert = toInvert.toArray(new SmartPsiElementPointer[toInvert.size()]);
//merge rename and invert usages
Map<PsiElement, UsageInfo> expressionsToUsages = new HashMap<PsiElement, UsageInfo>();
List<UsageInfo> result = new ArrayList<UsageInfo>();
for (UsageInfo renameUsage : renameUsages) {
expressionsToUsages.put(renameUsage.getElement(), renameUsage);
result.add(renameUsage);
}
for (SmartPsiElementPointer pointer : usagesToInvert) {
final PsiExpression expression = (PsiExpression)pointer.getElement();
if (!expressionsToUsages.containsKey(expression)) {
final UsageInfo usageInfo = new UsageInfo(expression);
expressionsToUsages.put(expression, usageInfo);
result.add(usageInfo); //fake UsageInfo
myToInvert.put(usageInfo, pointer);
} else {
myToInvert.put(expressionsToUsages.get(expression), pointer);
}
}
return result.toArray(new UsageInfo[result.size()]);
}
private static boolean canInvert(PsiReferenceExpression methodExpression, boolean checkRecursive) {
PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
if (qualifierExpression == null || !"super".equals(qualifierExpression.getText())) {
PsiElement parent = methodExpression.getParent();
if (parent instanceof PsiMethodCallExpression) {
return !(checkRecursive && RecursiveCallLineMarkerProvider.isRecursiveMethodCall((PsiMethodCallExpression)parent));
} else {
return true;
}
}
return false;
}
private void addRefsToInvert(final List<SmartPsiElementPointer> toInvert, final PsiNamedElement namedElement) {
final Query<PsiReference> query = namedElement instanceof PsiMethod ?
MethodReferencesSearch.search((PsiMethod)namedElement) :
ReferencesSearch.search(namedElement);
final Collection<PsiReference> refs = query.findAll();
for (PsiReference ref : refs) {
final PsiElement element = ref.getElement();
if (element instanceof PsiReferenceExpression) {
final PsiReferenceExpression refExpr = (PsiReferenceExpression)element;
PsiElement parent = refExpr.getParent();
if (parent instanceof PsiAssignmentExpression && refExpr.equals(((PsiAssignmentExpression)parent).getLExpression())) {
toInvert.add(mySmartPointerManager.createSmartPsiElementPointer(((PsiAssignmentExpression)parent).getRExpression()));
}
else {
if (namedElement instanceof PsiParameter) { //filter usages in super method calls
PsiElement gParent = refExpr.getParent().getParent();
if (gParent instanceof PsiMethodCallExpression) {
if (!canInvert(((PsiMethodCallExpression)gParent).getMethodExpression(), true)) {
continue;
}
}
}
toInvert.add(mySmartPointerManager.createSmartPsiElementPointer(refExpr));
}
}
}
if (namedElement instanceof PsiVariable) {
final PsiExpression initializer = ((PsiVariable)namedElement).getInitializer();
if (initializer != null) {
toInvert.add(mySmartPointerManager.createSmartPsiElementPointer(initializer));
}
}
}
@Override
protected void refreshElements(@NotNull PsiElement[] elements) {
LOG.assertTrue(elements.length == 1 && elements[0] instanceof PsiMethod);
myElement = (PsiMethod)elements[0];
}
private static UsageInfo[] extractUsagesForElement(PsiElement element, UsageInfo[] usages) {
final ArrayList<UsageInfo> extractedUsages = new ArrayList<UsageInfo>(usages.length);
for (UsageInfo usage : usages) {
if (usage instanceof MoveRenameUsageInfo) {
MoveRenameUsageInfo usageInfo = (MoveRenameUsageInfo)usage;
if (element.equals(usageInfo.getReferencedElement())) {
extractedUsages.add(usageInfo);
}
}
}
return extractedUsages.toArray(new UsageInfo[extractedUsages.size()]);
}
@Override
protected void performRefactoring(@NotNull UsageInfo[] usages) {
if (myRenameProcessor != null) {
for (final PsiElement element : myRenameProcessor.getElements()) {
try {
RenameUtil.doRename(element, myRenameProcessor.getNewName(element), extractUsagesForElement(element, usages), myProject, null);
}
catch (final IncorrectOperationException e) {
RenameUtil.showErrorMessage(e, element, myProject);
return;
}
}
}
for (UsageInfo usage : usages) {
final SmartPsiElementPointer pointerToInvert = myToInvert.get(usage);
if (pointerToInvert != null) {
PsiExpression expression = (PsiExpression)pointerToInvert.getElement();
LOG.assertTrue(expression != null);
if (expression.getParent() instanceof PsiMethodCallExpression) expression = (PsiExpression)expression.getParent();
try {
while (expression.getParent() instanceof PsiPrefixExpression &&
((PsiPrefixExpression)expression.getParent()).getOperationTokenType() == JavaTokenType.EXCL) {
expression = (PsiExpression)expression.getParent();
}
if (!(expression.getParent() instanceof PsiExpressionStatement)) {
expression.replace(CodeInsightServicesUtil.invertCondition(expression));
}
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
}
if (myElement instanceof PsiField && ((PsiField)myElement).getInitializer() == null) {
((PsiField)myElement).setInitializer(JavaPsiFacade.getElementFactory(myProject).createExpressionFromText("true", myElement));
}
}
@Override
protected String getCommandName() {
return InvertBooleanHandler.REFACTORING_NAME;
}
}
@@ -0,0 +1,266 @@
/*
* Copyright 2000-2015 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.refactoring.invertBoolean;
import com.intellij.codeInsight.CodeInsightServicesUtil;
import com.intellij.codeInsight.daemon.impl.RecursiveCallLineMarkerProvider;
import com.intellij.ide.util.SuperMethodWarningUtil;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.MethodReferencesSearch;
import com.intellij.psi.search.searches.OverridingMethodsSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.rename.RenameProcessor;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.Query;
import com.intellij.util.containers.HashSet;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
public class JavaInvertBooleanDelegate extends InvertBooleanDelegate {
@Override
public boolean isVisibleOnElement(@NotNull PsiElement element) {
return element instanceof PsiVariable || element instanceof PsiMethod;
}
@Override
public boolean isAvailableOnElement(@NotNull PsiElement element) {
if (element instanceof PsiVariable) {
return PsiType.BOOLEAN.equals(((PsiVariable) element).getType());
}
else if (element instanceof PsiMethod) {
return PsiType.BOOLEAN.equals(((PsiMethod) element).getReturnType());
}
return false;
}
@Override
public PsiElement adjustElement(PsiElement element, Project project, Editor editor) {
if (element instanceof PsiVariable) {
PsiVariable var = (PsiVariable)element;
final PsiType returnType = var.getType();
if (!PsiType.BOOLEAN.equals(returnType)) {
CommonRefactoringUtil.showErrorHint(project, editor,
RefactoringBundle
.getCannotRefactorMessage(RefactoringBundle.message("invert.boolean.wrong.type")),
InvertBooleanHandler.REFACTORING_NAME, InvertBooleanHandler.INVERT_BOOLEAN_HELP_ID);
return null;
}
if (var instanceof PsiParameter && ((PsiParameter)var).getDeclarationScope() instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)((PsiParameter)var).getDeclarationScope();
final PsiMethod superMethod = SuperMethodWarningUtil.checkSuperMethod(method, RefactoringBundle.message("to.refactor"));
if (superMethod == null) {
return null;
}
var = superMethod.getParameterList().getParameters()[method.getParameterList().getParameterIndex((PsiParameter)var)];
}
return var;
}
else if (element instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)element;
final PsiType returnType = method.getReturnType();
if (!PsiType.BOOLEAN.equals(returnType)) {
CommonRefactoringUtil.showErrorHint(project, editor,
RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("invert.boolean.wrong.type")),
InvertBooleanHandler.REFACTORING_NAME,
InvertBooleanHandler.INVERT_BOOLEAN_HELP_ID);
return null;
}
return SuperMethodWarningUtil.checkSuperMethod(method, RefactoringBundle.message("to.refactor"));
}
return null;
}
public void collectRefsToInvert(PsiElement namedElement, Collection<PsiElement> elementsToInvert) {
final Query<PsiReference> query = namedElement instanceof PsiMethod ?
MethodReferencesSearch.search((PsiMethod)namedElement) :
ReferencesSearch.search(namedElement);
final Collection<PsiReference> refs = query.findAll();
for (PsiReference ref : refs) {
final PsiElement element = ref.getElement();
PsiElement refElement = getElementToInvert(namedElement, element);
if (refElement == null) {
refElement = getForeignElementToInvert(namedElement, element, JavaLanguage.INSTANCE);
}
if (refElement != null) {
elementsToInvert.add(refElement);
}
}
if (namedElement instanceof PsiVariable) {
final PsiExpression initializer = ((PsiVariable)namedElement).getInitializer();
if (initializer != null) {
elementsToInvert.add(initializer);
}
}
}
public PsiElement getElementToInvert(PsiElement namedElement, PsiElement element) {
if (element instanceof PsiReferenceExpression) {
final PsiReferenceExpression refExpr = (PsiReferenceExpression)element;
PsiElement parent = refExpr.getParent();
if (parent instanceof PsiAssignmentExpression && refExpr.equals(((PsiAssignmentExpression)parent).getLExpression())) {
return ((PsiAssignmentExpression)parent).getRExpression();
}
else {
if (namedElement instanceof PsiParameter) { //filter usages in super method calls
PsiElement gParent = refExpr.getParent().getParent();
if (gParent instanceof PsiMethodCallExpression) {
if (!canInvertReferenceElement(((PsiMethodCallExpression)gParent).getMethodExpression(), true)) {
return null;
}
}
}
return refExpr;
}
}
return null;
}
private static boolean canInvertReferenceElement(PsiElement expression, boolean recursive) {
PsiExpression qualifierExpression = expression instanceof PsiReferenceExpression ? ((PsiReferenceExpression)expression).getQualifierExpression()
: null;
if (qualifierExpression == null || !"super".equals(qualifierExpression.getText())) {
PsiElement parent = expression.getParent();
if (parent instanceof PsiMethodCallExpression) {
return !(recursive && RecursiveCallLineMarkerProvider.isRecursiveMethodCall((PsiMethodCallExpression)parent));
} else {
return true;
}
}
return false;
}
@Override
public void replaceWithNegatedExpression(@NotNull PsiElement expression) {
if (!(expression instanceof PsiExpression)) {
return;
}
if (expression.getParent() instanceof PsiMethodCallExpression) {
expression = expression.getParent();
}
while (expression.getParent() instanceof PsiPrefixExpression &&
((PsiPrefixExpression)expression.getParent()).getOperationTokenType() == JavaTokenType.EXCL) {
expression = expression.getParent();
}
if (!(expression.getParent() instanceof PsiExpressionStatement)) {
expression.replace(CodeInsightServicesUtil.invertCondition((PsiExpression)expression));
}
}
@Override
public void invertDefaultElementInitializer(final PsiElement element) {
if (element instanceof PsiField && ((PsiField)element).getInitializer() == null) {
((PsiField)element).setInitializer(JavaPsiFacade.getElementFactory(element.getProject()).createExpressionFromText("true", element));
}
}
public void collectRefElements(final PsiElement element,
final Collection<PsiElement> elementsToInvert,
final RenameProcessor renameProcessor,
@NotNull final String newName) {
collectRefsToInvert(element, elementsToInvert);
if (element instanceof PsiMethod) {
final Collection<PsiMethod> overriders = OverridingMethodsSearch.search((PsiMethod)element).findAll();
if (renameProcessor != null) {
for (PsiMethod overrider : overriders) {
renameProcessor.addElement(overrider, newName);
}
}
Collection<PsiMethod> allMethods = new HashSet<PsiMethod>(overriders);
allMethods.add((PsiMethod)element);
for (PsiMethod method : allMethods) {
method.accept(new JavaRecursiveElementWalkingVisitor() {
@Override public void visitReturnStatement(PsiReturnStatement statement) {
final PsiExpression returnValue = statement.getReturnValue();
if (returnValue != null && PsiType.BOOLEAN.equals(returnValue.getType())) {
elementsToInvert.add(returnValue);
}
}
@Override
public void visitClass(PsiClass aClass) {}
@Override
public void visitLambdaExpression(PsiLambdaExpression expression) {}
});
}
}
else if (element instanceof PsiParameter && ((PsiParameter)element).getDeclarationScope() instanceof PsiMethod) {
final PsiMethod method = (PsiMethod)((PsiParameter)element).getDeclarationScope();
int index = method.getParameterList().getParameterIndex((PsiParameter)element);
assert index >= 0;
final Query<PsiReference> methodQuery = MethodReferencesSearch.search(method);
final Collection<PsiReference> methodRefs = methodQuery.findAll();
for (PsiReference ref : methodRefs) {
PsiElement parent = ref.getElement().getParent();
if (parent instanceof PsiAnonymousClass) {
parent = parent.getParent();
}
if (parent instanceof PsiCall) {
final PsiCall call = (PsiCall)parent;
final PsiReferenceExpression methodExpression = call instanceof PsiMethodCallExpression ?
((PsiMethodCallExpression)call).getMethodExpression() :
null;
final PsiExpressionList argumentList = call.getArgumentList();
if (argumentList != null) {
final PsiExpression[] args = argumentList.getExpressions();
if (index < args.length) {
if (methodExpression == null ||
canInvertReferenceElement(methodExpression,
args[index] instanceof PsiReferenceExpression &&
((PsiReferenceExpression)args[index]).resolve() == element)) {
elementsToInvert.add(args[index]);
}
}
}
}
}
final Collection<PsiMethod> overriders = OverridingMethodsSearch.search(method).findAll();
for (PsiMethod overrider : overriders) {
final PsiParameter overriderParameter = overrider.getParameterList().getParameters()[index];
if (renameProcessor != null) {
renameProcessor.addElement(overriderParameter, newName);
}
collectRefsToInvert(overriderParameter, elementsToInvert);
}
}
}
@Override
public void findConflicts(MultiMap<PsiElement, String> conflicts, UsageInfo[] usageInfos) {
for (UsageInfo info : usageInfos) {
final PsiElement element = info.getElement();
if (element instanceof PsiMethodReferenceExpression) {
conflicts.putValue(element, "Method is used in method reference expression");
}
}
}
}
@@ -1,6 +1,6 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -239,7 +239,7 @@ public class MigrationMapSet {
for(int i = 0; i < myMaps.size(); i++){
MigrationMap map = myMaps.get(i);
filePaths[i] = dir + File.separator + namesProvider.generateUniqueName(FileUtil.sanitizeName(map.getName())) + ".xml";
filePaths[i] = dir + File.separator + namesProvider.generateUniqueName(FileUtil.sanitizeFileName(map.getName(), false)) + ".xml";
documents[i] = saveMap(map);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -41,7 +41,7 @@ public abstract class MoveDialogBase extends RefactoringDialog {
protected void saveOpenInEditorOption() {
if (myOpenEditorCb != null) {
PropertiesComponent.getInstance().setValue("Move" + getMovePropertySuffix() +".OpenInEditor", String.valueOf(myOpenEditorCb.isSelected()));
PropertiesComponent.getInstance().setValue("Move" + getMovePropertySuffix() +".OpenInEditor", myOpenEditorCb.isSelected(), isEnabledByDefault());
}
}
@@ -46,7 +46,7 @@ public class TestRunLineMarkerProvider extends RunLineMarkerContributor {
if (element instanceof PsiClass) {
TestFramework framework = TestFrameworks.detectFramework((PsiClass)element);
if (framework != null && framework.isTestClass(element)) {
return new Info(framework.getIcon(), TOOLTIP_PROVIDER, ExecutorAction.ACTIONS);
return new Info(framework.getIcon(), TOOLTIP_PROVIDER, ExecutorAction.ACTIONS(1));
}
}
if (element instanceof PsiMethod) {
@@ -54,7 +54,7 @@ public class TestRunLineMarkerProvider extends RunLineMarkerContributor {
TestFramework framework = TestFrameworks.detectFramework(psiClass);
if (psiClass != null && framework != null && framework.isTestMethod(element)) {
// String url = "java:test://" + psiClass.getQualifiedName() + "." + ((PsiMethod)element).getName();
return new Info(framework.getIcon(), TOOLTIP_PROVIDER, ExecutorAction.ACTIONS);
return new Info(framework.getIcon(), TOOLTIP_PROVIDER, ExecutorAction.ACTIONS(1));
}
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -106,13 +106,13 @@ public class CreateTestAction extends PsiElementBaseIntentionAction {
final PropertiesComponent propertiesComponent = PropertiesComponent.getInstance();
final HashSet<VirtualFile> testFolders = new HashSet<VirtualFile>();
checkForTestRoots(srcModule, testFolders);
if (testFolders.isEmpty() && !propertiesComponent.getBoolean(CREATE_TEST_IN_THE_SAME_ROOT, false)) {
if (testFolders.isEmpty() && !propertiesComponent.getBoolean(CREATE_TEST_IN_THE_SAME_ROOT)) {
if (Messages.showOkCancelDialog(project, "Create test in the same source root?", "No Test Roots Found", Messages.getQuestionIcon()) !=
Messages.OK) {
return;
}
propertiesComponent.setValue(CREATE_TEST_IN_THE_SAME_ROOT, String.valueOf(true));
propertiesComponent.setValue(CREATE_TEST_IN_THE_SAME_ROOT, true);
}
final CreateTestDialog d = createTestDialog(project, srcModule, srcClass, srcPackage);
@@ -186,13 +186,11 @@ public class CreateTestDialog extends DialogWrapper {
}
private void restoreShowInheritedMembersStatus() {
String v = getProperties().getValue(SHOW_INHERITED_MEMBERS_PROPERTY);
myShowInheritedMethodsBox.setSelected(v != null && v.equals("true"));
myShowInheritedMethodsBox.setSelected(getProperties().getBoolean(SHOW_INHERITED_MEMBERS_PROPERTY));
}
private void saveShowInheritedMembersStatus() {
boolean v = myShowInheritedMethodsBox.isSelected();
getProperties().setValue(SHOW_INHERITED_MEMBERS_PROPERTY, Boolean.toString(v));
getProperties().setValue(SHOW_INHERITED_MEMBERS_PROPERTY, myShowInheritedMethodsBox.isSelected());
}
private PropertiesComponent getProperties() {
@@ -452,40 +452,6 @@ public class PsiFormatUtil extends PsiFormatUtilBase {
return builder.toString();
}
@Nullable
public static String getRawExternalName(PsiModifierListOwner owner) {
final StringBuilder builder = new StringBuilder();
final PsiClass psiClass = PsiTreeUtil.getParentOfType(owner, PsiClass.class, false);
if (psiClass == null) return null;
ClassUtil.formatClassName(psiClass, builder);
if (owner instanceof PsiMethod) {
builder.append(" ");
formatMethod((PsiMethod)owner, PsiSubstitutor.EMPTY,
SHOW_NAME | SHOW_FQ_NAME | SHOW_TYPE | SHOW_RAW_TYPE | SHOW_PARAMETERS | SHOW_FQ_CLASS_NAMES,
SHOW_TYPE | SHOW_RAW_TYPE | SHOW_FQ_CLASS_NAMES,
Integer.MAX_VALUE, builder);
}
else if (owner instanceof PsiParameter) {
final PsiElement declarationScope = ((PsiParameter)owner).getDeclarationScope();
if (!(declarationScope instanceof PsiMethod)) {
return null;
}
final PsiMethod psiMethod = (PsiMethod)declarationScope;
builder.append(" ");
formatMethod(psiMethod, PsiSubstitutor.EMPTY,
SHOW_NAME | SHOW_FQ_NAME | SHOW_TYPE | SHOW_RAW_TYPE | SHOW_PARAMETERS | SHOW_FQ_CLASS_NAMES,
SHOW_TYPE | SHOW_RAW_TYPE | SHOW_FQ_CLASS_NAMES,
Integer.MAX_VALUE, builder);
builder.append(" ");
builder.append(psiMethod.getParameterList().getParameterIndex((PsiParameter)owner));
}
else {
return null;
}
return builder.toString();
}
public static String getPackageDisplayName(@NotNull final PsiClass psiClass) {
if (psiClass instanceof PsiTypeParameter) {
PsiTypeParameterListOwner owner = ((PsiTypeParameter)psiClass).getOwner();
@@ -1335,6 +1335,7 @@ public class InferenceSession {
*/
public static boolean isMoreSpecific(PsiMethod m1,
PsiMethod m2,
PsiSubstitutor siteSubstitutor1,
PsiExpression[] args,
PsiElement context,
boolean varargs) {
@@ -1342,7 +1343,10 @@ public class InferenceSession {
for (PsiTypeParameter param : PsiUtil.typeParametersIterable(m2)) {
params.add(param);
}
final InferenceSession session = new InferenceSession(params.toArray(new PsiTypeParameter[params.size()]), PsiSubstitutor.EMPTY, m2.getManager(), context);
siteSubstitutor1 = getSiteSubstitutor(siteSubstitutor1, params);
final InferenceSession session = new InferenceSession(params.toArray(new PsiTypeParameter[params.size()]), siteSubstitutor1, m2.getManager(), context);
final PsiParameter[] parameters1 = m1.getParameterList().getParameters();
final PsiParameter[] parameters2 = m2.getParameterList().getParameters();
@@ -1352,8 +1356,8 @@ public class InferenceSession {
final int paramsLength = !varargs ? parameters1.length : parameters1.length - 1;
for (int i = 0; i < paramsLength; i++) {
PsiType sType = getParameterType(parameters1, i, PsiSubstitutor.EMPTY, false);
PsiType tType = session.substituteWithInferenceVariables(getParameterType(parameters2, i, PsiSubstitutor.EMPTY, varargs));
PsiType sType = getParameterType(parameters1, i, siteSubstitutor1, false);
PsiType tType = session.substituteWithInferenceVariables(getParameterType(parameters2, i, siteSubstitutor1, varargs));
if (LambdaUtil.isFunctionalType(sType) && LambdaUtil.isFunctionalType(tType) && !relates(sType, tType)) {
if (!isFunctionalTypeMoreSpecific(sType, tType, session, args[i])) {
return false;
@@ -1369,14 +1373,22 @@ public class InferenceSession {
}
if (varargs) {
PsiType sType = getParameterType(parameters1, paramsLength, PsiSubstitutor.EMPTY, true);
PsiType tType = session.substituteWithInferenceVariables(getParameterType(parameters2, paramsLength, PsiSubstitutor.EMPTY, true));
PsiType sType = getParameterType(parameters1, paramsLength, siteSubstitutor1, true);
PsiType tType = session.substituteWithInferenceVariables(getParameterType(parameters2, paramsLength, siteSubstitutor1, true));
session.addConstraint(new StrictSubtypingConstraint(tType, sType));
}
return session.repeatInferencePhases(true);
}
private static PsiSubstitutor getSiteSubstitutor(PsiSubstitutor siteSubstitutor1, List<PsiTypeParameter> params) {
PsiSubstitutor subst = PsiSubstitutor.EMPTY;
for (PsiTypeParameter param : params) {
subst = subst.put(param, siteSubstitutor1.substitute(param));
}
return subst;
}
/**
* 15.12.2.5 Choosing the Most Specific Method
* "a functional interface type S is more specific than a functional interface type T for an expression exp" part
@@ -544,10 +544,10 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{
final PsiSubstitutor methodSubstitutor1 = calculateMethodSubstitutor(typeParameters1, method1, siteSubstitutor1, types1, types2AtSite,
languageLevel);
boolean applicable12 = isApplicableTo(types2AtSite, method1, languageLevel, varargsPosition, methodSubstitutor1, method2);
boolean applicable12 = isApplicableTo(types2AtSite, method1, languageLevel, varargsPosition, methodSubstitutor1, method2, siteSubstitutor2);
final PsiSubstitutor methodSubstitutor2 = calculateMethodSubstitutor(typeParameters2, method2, siteSubstitutor2, types2, types1AtSite, languageLevel);
boolean applicable21 = isApplicableTo(types1AtSite, method2, languageLevel, varargsPosition, methodSubstitutor2, method1);
boolean applicable21 = isApplicableTo(types1AtSite, method2, languageLevel, varargsPosition, methodSubstitutor2, method1, siteSubstitutor1);
if (!myLanguageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
final boolean typeArgsApplicable12 = GenericsUtil.isTypeArgumentsApplicable(typeParameters1, methodSubstitutor1, myArgumentsList, !applicable21);
@@ -641,11 +641,12 @@ public class JavaMethodsConflictResolver implements PsiConflictResolver{
@NotNull LanguageLevel languageLevel,
boolean varargsPosition,
@NotNull PsiSubstitutor methodSubstitutor1,
@NotNull PsiMethod method2) {
@NotNull PsiMethod method2,
PsiSubstitutor siteSubstitutor1) {
if (languageLevel.isAtLeast(LanguageLevel.JDK_1_8) && method1.getTypeParameters().length > 0 && myArgumentsList instanceof PsiExpressionList) {
final PsiElement parent = myArgumentsList.getParent();
if (parent instanceof PsiCallExpression) {
return InferenceSession.isMoreSpecific(method2, method1, ((PsiExpressionList)myArgumentsList).getExpressions(), myArgumentsList, varargsPosition);
return InferenceSession.isMoreSpecific(method2, method1, siteSubstitutor1, ((PsiExpressionList)myArgumentsList).getExpressions(), myArgumentsList, varargsPosition);
}
}
final PsiUtil.ApplicabilityChecker applicabilityChecker = languageLevel.isAtLeast(LanguageLevel.JDK_1_8)
@@ -0,0 +1,10 @@
class Test {
interface One<T> {
<S extends T> S save(S entity);
<S extends T> Iterable<S> save(Iterable<S> entities);
}
static One<String> foo;
public static void main(String[] args) throws Exception {
foo.save <error descr="Ambiguous method call: both 'One.save(String)' and 'One.save(Iterable<String>)' match">(null)</error>;
}
}
@@ -0,0 +1,8 @@
// "Replace lambda with method reference" "false"
class Example {
static Runnable runner;
public static void main(String[] args) {
lambda = () -> runn<caret>er.run();
}
}
@@ -0,0 +1,64 @@
<html><head><base href="placeholder"> <style type="text/css"> #error { background-color: #eeeeee; margin-bottom: 10px; } p { margin: 5px 0; } </style></head><body><small><b>java.lang</b></small><PRE>public final class <b>String</b>
extends <a href="psi_element://java.lang.Object"><code>java.lang.Object</code></a>
implements <a href="psi_element://java.io.Serializable"><code>java.io.Serializable</code></a>,&nbsp;<a href="psi_element://java.lang.Comparable"><code>java.lang.Comparable</code></a>&lt;<a href="psi_element://java.lang.String"><code>String</code></a>&gt;,&nbsp;<a href="psi_element://java.lang.CharSequence"><code>java.lang.CharSequence</code></a></PRE>
The <code>String</code> class represents character strings. All
string literals in Java programs, such as <code>"abc"</code>, are
implemented as instances of this class.
<p>
Strings are constant; their values cannot be changed after they
are created. String buffers support mutable strings.
Because String objects are immutable they can be shared. For example:
<p><blockquote><pre>
String str = "abc";
</pre></blockquote><p>
is equivalent to:
<p><blockquote><pre>
char data[] = {'a', 'b', 'c'};
String str = new String(data);
</pre></blockquote><p>
Here are some more examples of how strings can be used:
<p><blockquote><pre>
System.out.println("abc");
String cde = "cde";
System.out.println("abc" + cde);
String c = "abc".substring(2,3);
String d = cde.substring(1, 2);
</pre></blockquote>
<p>
The class <code>String</code> includes methods for examining
individual characters of the sequence, for comparing strings, for
searching strings, for extracting substrings, and for creating a
copy of a string with all characters translated to uppercase or to
lowercase. Case mapping is based on the Unicode Standard version
specified by the <a href="psi_element://java.lang.Character"><code>Character</code></a> class.
<p>
The Java language provides special support for the string
concatenation operator (&nbsp;+&nbsp;), and for conversion of
other objects to strings. String concatenation is implemented
through the <code>StringBuilder</code>(or <code>StringBuffer</code>)
class and its <code>append</code> method.
String conversions are implemented through the method
<code>toString</code>, defined by <code>Object</code> and
inherited by all classes in Java. For additional information on
string concatenation and conversion, see Gosling, Joy, and Steele,
<i>The Java Language Specification</i>.
<p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
or method in this class will cause a <a href="psi_element://java.lang.NullPointerException"><code>NullPointerException</code></a> to be
thrown.
<p>A <code>String</code> represents a string in the UTF-16 format
in which <em>supplementary characters</em> are represented by <em>surrogate
pairs</em> (see the section <a href="psi_element://java.lang.Character###unicode">Unicode
Character Representations</a> in the <code>Character</code> class for
more information).
Index values refer to <code>char</code> code units, so a supplementary
character uses two positions in a <code>String</code>.
<p>The <code>String</code> class provides methods for dealing with
Unicode code points (i.e., characters), in addition to those for
dealing with Unicode code units (i.e., <code>char</code> values).
<DD><DL><DT><b>Since:</b><DD>JDK1.0</DD></DL></DD><DD><DL><DT><b>See Also:</b><DD><a href="psi_element://java.lang.Object#toString()"><code>Object.toString()</code></a>,
<a href="psi_element://java.lang.StringBuffer"><code>StringBuffer</code></a>,
<a href="psi_element://java.lang.StringBuilder"><code>StringBuilder</code></a>,
<font color=red>java.nio.charset.Charset</font></DD></DL></DD></body></html>
@@ -0,0 +1,2 @@
<html><head> <style type="text/css"> #error { background-color: #eeeeee; margin-bottom: 10px; } p { margin: 5px 0; } </style></head><body>
Description of com.jetbrains package</body></html>
@@ -0,0 +1,4 @@
/**
* some text
*/
package packageInfoFromComment;
@@ -0,0 +1,2 @@
<html><head> <style type="text/css"> #error { background-color: #eeeeee; margin-bottom: 10px; } p { margin: 5px 0; } </style></head><body>
some text</body></html>
@@ -0,0 +1,10 @@
abstract class Main {
public static void main(String notification) throws Exception {
System.out.println(
"Too large notification " + noti<caret>fication +
" of " + notification.getClass() +
"\nListener=" + notification.substring(0));
}
}
@@ -0,0 +1,13 @@
abstract class Main {
private static String notification;
public static void main(String notification) throws Exception {
Main.notification = notification;
System.out.println(
"Too large notification " + Main.notification +
" of " + notification.getClass() +
"\nListener=" + notification.substring(0));
}
}
@@ -25,6 +25,7 @@ import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.JavadocOrderRootType;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.openapi.roots.OrderRootType;
@@ -103,6 +104,7 @@ public class JavaExternalDocumentationTest extends PlatformTestCase {
}
private static void waitTillDone(ActionCallback actionCallback) throws InterruptedException {
if (actionCallback == null) return;
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 300000) {
//noinspection BusyWait
@@ -118,7 +120,7 @@ public class JavaExternalDocumentationTest extends PlatformTestCase {
}
@NotNull
private static VirtualFile getJarFile(String name) {
public static VirtualFile getJarFile(String name) {
VirtualFile file = getVirtualFile(getDataFile(name));
assertNotNull(file);
VirtualFile jarFile = JarFileSystem.getInstance().getJarRootForLocalFile(file);
@@ -133,14 +135,19 @@ public class JavaExternalDocumentationTest extends PlatformTestCase {
sourceEditorText.substring(caretPosition + EditorTestUtil.CARET_TAG.length());
}
PsiFile psiFile = PsiFileFactory.getInstance(myProject).createFileFromText(JavaLanguage.INSTANCE, sourceEditorText);
Document document = PsiDocumentManager.getInstance(myProject).getDocument(psiFile);
return getDocumentationText(psiFile, caretPosition);
}
public static String getDocumentationText(@NotNull PsiFile psiFile, int caretPosition) throws InterruptedException {
Project project = psiFile.getProject();
Document document = PsiDocumentManager.getInstance(project).getDocument(psiFile);
assertNotNull(document);
Editor editor = EditorFactory.getInstance().createEditor(document, myProject);
Editor editor = EditorFactory.getInstance().createEditor(document, project);
try {
if (caretPosition >= 0) {
editor.getCaretModel().moveToOffset(caretPosition);
}
DocumentationManager documentationManager = DocumentationManager.getInstance(myProject);
DocumentationManager documentationManager = DocumentationManager.getInstance(project);
MockDocumentationComponent documentationComponent = new MockDocumentationComponent(documentationManager);
try {
documentationManager.setDocumentationComponent(documentationComponent);
@@ -157,7 +164,7 @@ public class JavaExternalDocumentationTest extends PlatformTestCase {
finally {
EditorFactory.getInstance().releaseEditor(editor);
}
}
}
@Override
protected boolean isRunInWriteAction() {
@@ -126,6 +126,10 @@ public class MostSpecificResolutionTest extends LightDaemonAnalyzerTestCase {
doTest(false);
}
public void testIncompatibleSiteSubstitutionBounds() throws Exception {
doTest(false);
}
private void doTest() {
doTest(true);
}
@@ -17,10 +17,19 @@ package com.intellij.codeInsight.javadoc;
import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.CodeInsightTestCase;
import com.intellij.codeInsight.JavaExternalDocumentationTest;
import com.intellij.lang.java.JavaDocumentationProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.roots.ModuleRootModificationUtil;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiTreeUtil;
@@ -29,6 +38,8 @@ import com.intellij.testFramework.PsiTestUtil;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* @author yole
@@ -220,7 +231,11 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase {
}
private void verifyJavaDoc(final PsiElement field) throws IOException {
String docInfo = new JavaDocInfoGenerator(getProject(), field).generateDocInfo(null);
verifyJavaDoc(field, null);
}
private void verifyJavaDoc(final PsiElement field, List<String> docUrls) throws IOException {
String docInfo = new JavaDocInfoGenerator(getProject(), field).generateDocInfo(docUrls);
assertNotNull(docInfo);
assertEquals(exampleHtmlFileText(getTestName(true)), replaceEnvironmentDependentContent(docInfo));
}
@@ -235,6 +250,18 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase {
assertNotNull(info);
assertEquals(StringUtil.convertLineSeparators(htmlText.trim()), replaceEnvironmentDependentContent(info));
}
public void testPackageInfoFromComment() throws Exception {
final String rootPath = getTestDataPath() + "/codeInsight/javadocIG/";
VirtualFile root = PsiTestUtil.createTestProjectStructure(myProject, myModule, rootPath, myFilesToDelete);
VirtualFile piFile = root.findFileByRelativePath("packageInfoFromComment/package-info.java");
assertNotNull(piFile);
PsiFile psiFile = PsiManager.getInstance(myProject).findFile(piFile);
assertNotNull(psiFile);
final String info = JavaExternalDocumentationTest.getDocumentationText(psiFile, psiFile.getText().indexOf("some"));
String htmlText = FileUtil.loadFile(new File(rootPath + getTestName(true) + File.separator + "packageInfo.html"));
assertEquals(StringUtil.convertLineSeparators(htmlText.trim()), replaceEnvironmentDependentContent(info));
}
public void testInheritedParameter() throws Exception {
configureByFile("/codeInsight/javadocIG/" + getTestName(true) + ".java");
@@ -291,6 +318,33 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase {
PsiMethod method = psiClass.getMethods()[0];
verifyJavaDoc(method);
}
public void testDocumentationForJdkClassWhenExternalDocIsNotAvailable() throws Exception {
PsiClass aClass = JavaPsiFacade.getInstance(myProject).findClass("java.lang.String", GlobalSearchScope.allScope(myProject));
assertNotNull(aClass);
verifyJavaDoc(aClass, Collections.singletonList("dummyUrl"));
}
public void testLibraryPackageDocumentation() throws Exception {
final VirtualFile libClasses = JavaExternalDocumentationTest.getJarFile("library.jar");
final VirtualFile libSources = JavaExternalDocumentationTest.getJarFile("library-src.jar");
ApplicationManager.getApplication().runWriteAction(() -> {
final Library library = LibraryTablesRegistrar.getInstance().getLibraryTable(myProject).createLibrary("myLib");
final Library.ModifiableModel model = library.getModifiableModel();
model.addRoot(libClasses, OrderRootType.CLASSES);
model.addRoot(libSources, OrderRootType.SOURCES);
model.commit();
Module[] modules = ModuleManager.getInstance(myProject).getModules();
assertSize(1, modules);
ModuleRootModificationUtil.addDependency(modules[0], library);
});
PsiPackage aPackage = JavaPsiFacade.getInstance(myProject).findPackage("com.jetbrains");
assertNotNull(aPackage);
verifyJavaDoc(aPackage);
}
@Override
protected String getTestDataPath() {
@@ -313,6 +367,12 @@ public class JavaDocInfoGeneratorTest extends CodeInsightTestCase {
}
private static String replaceEnvironmentDependentContent(String html) {
return StringUtil.convertLineSeparators(html.trim()).replaceAll("<base href=\"[^\"]*\">", "<base href=\"placeholder\">");
return html == null ? null : StringUtil.convertLineSeparators(html.trim()).replaceAll("<base href=\"[^\"]*\">",
"<base href=\"placeholder\">");
}
@Override
protected boolean isRunInWriteAction() {
return false;
}
}
@@ -15,16 +15,25 @@
*/
package com.intellij.codeInsight.navigation;
import com.intellij.codeInsight.daemon.GutterMark;
import com.intellij.openapi.actionSystem.ActionGroup;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.testFramework.TestActionEvent;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import com.intellij.util.containers.ContainerUtil;
import java.util.List;
/**
* @author Dmitry Avdeev
*/
@SuppressWarnings("ConstantConditions")
public class RunLineMarkerTest extends LightCodeInsightFixtureTestCase {
public void testRunLineMarker() throws Exception {
myFixture.configureByText("MainTest.java", "public class MainTest {\n" +
" public static void fo<caret>o(String[] args) {\n" +
" public static void <caret>foo(String[] args) {\n" +
" }\n " +
" public static void main(String[] args) {\n" +
" }\n" +
@@ -32,4 +41,29 @@ public class RunLineMarkerTest extends LightCodeInsightFixtureTestCase {
assertEquals(0, myFixture.findGuttersAtCaret().size());
assertEquals(2, myFixture.findAllGutters().size());
}
public void testTestClassWithMain() throws Exception {
myFixture.addClass("package junit.framework; public class TestCase {}");
myFixture.configureByText("MainTest.java", "public class <caret>MainTest extends junit.framework.TestCase {\n" +
" public static void main(String[] args) {\n" +
" }\n" +
" public void testFoo() {\n" +
" }\n" +
"}");
List<GutterMark> marks = myFixture.findGuttersAtCaret();
assertEquals(1, marks.size());
GutterIconRenderer mark = (GutterIconRenderer)marks.get(0);
ActionGroup group = mark.getPopupMenuActions();
assertNotNull(group);
TestActionEvent event = new TestActionEvent();
List<AnAction> list = ContainerUtil.findAll(group.getChildren(event), action -> {
action.update(event);
return event.getPresentation().getText().startsWith("Run");
});
assertEquals(2, list.size());
list.get(0).update(event);
assertEquals("Run 'MainTest.main()'", event.getPresentation().getText());
list.get(1).update(event);
assertEquals("Run 'MainTest'", event.getPresentation().getText());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -33,7 +33,7 @@ public abstract class JavaFileStructureTestCase extends FileStructureTestBase {
@Override
public void setUp() throws Exception {
super.setUp();
myShowAnonymousByDefault = PropertiesComponent.getInstance().getBoolean(getAnonymousPropertyName(), false);
myShowAnonymousByDefault = PropertiesComponent.getInstance().getBoolean(getAnonymousPropertyName());
if (getTestName(false).contains("Anonymous")) {
setShowAnonymous(true);
}
@@ -56,7 +56,7 @@ public abstract class JavaFileStructureTestCase extends FileStructureTestBase {
@Override
public void tearDown() throws Exception {
PropertiesComponent.getInstance().setValue(getAnonymousPropertyName(), Boolean.toString(myShowAnonymousByDefault));
PropertiesComponent.getInstance().setValue(getAnonymousPropertyName(), myShowAnonymousByDefault);
super.tearDown();
}
@@ -115,6 +115,14 @@ public class InplaceIntroduceFieldTest extends AbstractJavaInplaceIntroduceTest
}
});
}
public void testNormalizeDeclarationWithDisabledFormatting() throws Exception {
doTest(new Pass<AbstractInplaceIntroducer>() {
@Override
public void pass(AbstractInplaceIntroducer inplaceIntroduceFieldPopup) {
}
});
}
public void testEscapePosition() throws Exception {
doTestEscape();
@@ -508,7 +508,7 @@ public class SchemeManagerImpl<T : Scheme, E : ExternalizableScheme>(private val
var fileNameWithoutExtension = currentFileNameWithoutExtension
if (fileNameWithoutExtension == null || isRenamed(scheme)) {
fileNameWithoutExtension = nameGenerator.generateUniqueName(FileUtil.sanitizeName(scheme.getName()))
fileNameWithoutExtension = nameGenerator.generateUniqueName(FileUtil.sanitizeFileName(scheme.getName(), false))
}
val newHash = JDOMUtil.getTreeHash(element!!, true)
@@ -518,7 +518,7 @@ public class SchemeManagerImpl<T : Scheme, E : ExternalizableScheme>(private val
// save only if scheme differs from bundled
val bundledScheme = readOnlyExternalizableSchemes.get(scheme.getName())
if (bundledScheme != null && schemeToInfo.get(bundledScheme)!!.hash == newHash) {
if (bundledScheme != null && schemeToInfo.get(bundledScheme)?.hash == newHash) {
externalInfo?.scheduleDelete()
return
}
@@ -67,6 +67,10 @@ class StoreAwareProjectManager(virtualFileManager: VirtualFileManager, progressM
if (!changes.isEmpty()) {
runBatchUpdate(project.getMessageBus()) {
for ((store, storages) in changes.entrySet()) {
if ((store.storageManager as? StateStorageManagerImpl)?.componentManager?.isDisposed() ?: false) {
continue
}
@suppress("UNCHECKED_CAST")
if (reloadStore(storages as Set<StateStorage>, store, false) == ReloadComponentStoreStatus.RESTART_AGREED) {
projectsToReload.add(project)
@@ -79,7 +79,7 @@ class ApplicationStoreTest {
componentStore.initComponent(component, false)
assertThat(component.foo).isEqualTo("newValue")
assertThat(Paths.get(componentStore.storageManager.fileSpecToPath(fileSpec))).exists()
assertThat(Paths.get(componentStore.storageManager.fileSpecToPath(fileSpec))).isRegularFile()
}
@Test fun `remove deprecated storage on write`() {
@@ -102,7 +102,7 @@ class ApplicationStoreTest {
component.foo = "new2"
runInEdtAndWait { componentStore.save(SmartList()) }
assertThat(oldFile.exists()).isFalse()
assertThat(oldFile).doesNotExist()
}
private fun writeConfig(fileName: String, Language("XML") data: String) = testAppConfig.writeChild(fileName, data)
@@ -42,7 +42,7 @@ public abstract class PropertiesComponent {
public abstract String getValue(@NonNls String name);
/**
* @deprecated Use {@link #setValue(String, String, String)} to avoid write defaults.
* Consider to use {@link #setValue(String, String, String)} to avoid write defaults.
*/
public abstract void setValue(@NotNull String name, @Nullable String value);
@@ -64,10 +64,12 @@ public abstract class PropertiesComponent {
/**
* Set value or unset if equals to false
*/
public abstract void setValue(@NotNull String name, boolean value);
public final void setValue(@NotNull String name, boolean value) {
setValue(name, value, false);
}
/**
* Set value or unset if equals to false
* Set value or unset if equals to default
*/
public abstract void setValue(@NotNull String name, boolean value, boolean defaultValue);
@@ -88,10 +90,14 @@ public abstract class PropertiesComponent {
return Boolean.valueOf(getValue(name)).booleanValue();
}
public final boolean getBoolean(@NonNls String name, boolean defaultValue) {
public final boolean getBoolean(@NotNull String name, boolean defaultValue) {
return isValueSet(name) ? isTrueValue(name) : defaultValue;
}
public final boolean getBoolean(@NotNull String name) {
return getBoolean(name, false);
}
@NotNull
public String getValue(@NonNls String name, @NotNull String defaultValue) {
if (!isValueSet(name)) {
@@ -73,6 +73,12 @@ public class IdentitySmartPointer<T extends PsiElement> implements SmartPsiEleme
@Override
public Segment getRange() {
return getPsiRange();
}
@Nullable
@Override
public Segment getPsiRange() {
return myElement.getTextRange();
}
}
@@ -45,6 +45,18 @@ public interface SmartPsiElementPointer<E extends PsiElement> {
VirtualFile getVirtualFile();
/**
* @return the range in the document. For committed document, it's the same as {@link #getPsiRange()}, for non-committed documents
* the ranges may be changed (like in {@link com.intellij.openapi.editor.RangeMarker}) or even invalidated. In the latter case returns null.
* Returns null for invalid pointers.
*/
@Nullable
Segment getRange();
/**
* @return the range in the committed PSI file. May be different from {@link #getRange()} result when the document has been changed since commit.
* Returns null for invalid pointers.
*/
@Nullable
Segment getPsiRange();
}
@@ -25,7 +25,7 @@ import com.intellij.util.messages.Topic;
*/
public class PowerSaveMode {
private static final String POWER_SAVE_MODE = "power.save.mode";
private boolean myEnabled = PropertiesComponent.getInstance().getBoolean(POWER_SAVE_MODE, false);
private boolean myEnabled = PropertiesComponent.getInstance().getBoolean(POWER_SAVE_MODE);
private final MessageBus myBus;
public PowerSaveMode(MessageBus bus) {
@@ -41,7 +41,7 @@ public class PowerSaveMode {
if (instance.myEnabled != value) {
instance.myEnabled = value;
instance.myBus.syncPublisher(TOPIC).powerSaveStateChanged();
PropertiesComponent.getInstance().setValue(POWER_SAVE_MODE, String.valueOf(value), "false");
PropertiesComponent.getInstance().setValue(POWER_SAVE_MODE, value);
}
}
@@ -117,16 +117,6 @@ public class PropertiesComponentImpl extends PropertiesComponent implements Pers
}
}
@Override
public void setValue(@NotNull String name, boolean value) {
if (value) {
setValue(name, "true");
}
else {
myMap.remove(name);
}
}
@Override
public void setValue(@NotNull String name, boolean value, boolean defaultValue) {
if (value == defaultValue) {
@@ -61,6 +61,7 @@ import org.jetbrains.annotations.TestOnly;
import javax.swing.*;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
public abstract class PsiDocumentManagerBase extends PsiDocumentManager implements DocumentListener, ProjectComponent {
static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.PsiDocumentManagerImpl");
@@ -582,14 +583,31 @@ public abstract class PsiDocumentManagerBase extends PsiDocumentManager implemen
}
@NotNull
public FrozenDocument getLastCommittedDocument(@NotNull Document document) {
if (document instanceof FrozenDocument) return (FrozenDocument)document;
public DocumentEx getLastCommittedDocument(@NotNull Document document) {
if (document instanceof FrozenDocument) return (DocumentEx)document;
if (document instanceof DocumentWindow) {
DocumentWindow window = (DocumentWindow)document;
Document delegate = window.getDelegate();
if (delegate instanceof FrozenDocument) return (DocumentEx)window;
UncommittedInfo info = myUncommittedInfos.get(delegate);
DocumentWindow answer = info == null ? null : info.myFrozenWindows.get(document);
if (answer == null) answer = freezeWindow(window);
if (info != null) answer = ConcurrencyUtil.cacheOrGet(info.myFrozenWindows, window, answer);
return (DocumentEx)answer;
}
assert document instanceof DocumentImpl;
UncommittedInfo info = myUncommittedInfos.get(document);
return info != null ? info.myFrozen : ((DocumentImpl)document).freeze();
}
@NotNull
protected DocumentWindow freezeWindow(@NotNull DocumentWindow document) {
throw new UnsupportedOperationException();
}
@NotNull
public List<DocumentEvent> getEventsSinceCommit(@NotNull Document document) {
assert document instanceof DocumentImpl;
@@ -899,6 +917,7 @@ public abstract class PsiDocumentManagerBase extends PsiDocumentManager implemen
final DocumentImpl myOriginal;
final FrozenDocument myFrozen;
final List<DocumentEvent> myEvents = ContainerUtil.newArrayList();
final ConcurrentMap<DocumentWindow, DocumentWindow> myFrozenWindows = ContainerUtil.newConcurrentMap();
public UncommittedInfo(DocumentImpl original) {
myOriginal = original;
@@ -23,6 +23,7 @@ import com.intellij.psi.PsiAnchor;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: cdr
@@ -68,6 +69,12 @@ public class ClsElementInfo extends SmartPointerElementInfo {
return myStubIndexReference.getProject();
}
@Nullable
@Override
public Segment getPsiRange() {
return null;
}
@Override
public PsiFile restoreFile() {
return myStubIndexReference.getFile();
@@ -16,14 +16,19 @@
package com.intellij.psi.impl.smartPointers;
import com.intellij.lang.Language;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Segment;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.PsiDocumentManagerBase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: cdr
@@ -90,4 +95,12 @@ class FileElementInfo extends SmartPointerElementInfo {
return myProject;
}
@Nullable
@Override
public Segment getPsiRange() {
Document currentDoc = FileDocumentManager.getInstance().getCachedDocument(myVirtualFile);
Document committedDoc = currentDoc == null ? null :
((PsiDocumentManagerBase)PsiDocumentManager.getInstance(myProject)).getLastCommittedDocument(currentDoc);
return committedDoc == null ? getRange() : new TextRange(0, committedDoc.getTextLength());
}
}
@@ -68,6 +68,11 @@ class HardElementInfo extends SmartPointerElementInfo {
return myElement.getTextRange();
}
@Override
public Segment getPsiRange() {
return getRange();
}
@NotNull
@Override
public Project getProject() {
@@ -28,6 +28,7 @@ import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.FreeThreadedFileViewProvider;
import com.intellij.psi.impl.PsiDocumentManagerBase;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -72,7 +73,13 @@ class InjectedSelfElementInfo extends SmartPointerElementInfo {
@Override
public Segment getRange() {
return getInjectedRange();
return getInjectedRange(false);
}
@Nullable
@Override
public Segment getPsiRange() {
return getInjectedRange(true);
}
@Override
@@ -83,20 +90,14 @@ class InjectedSelfElementInfo extends SmartPointerElementInfo {
PsiElement hostContext = myHostContext.getElement();
if (hostContext == null) return null;
Segment segment = myInjectedFileRangeInHostFile.getRange();
Segment segment = myInjectedFileRangeInHostFile.getPsiRange();
if (segment == null) return null;
final TextRange rangeInHostFile = TextRange.create(segment);
PsiElement result = null;
PsiFile injectedPsi = getInjectedFileIn(hostContext, hostFile, rangeInHostFile);
if (injectedPsi != null) {
Document document = PsiDocumentManager.getInstance(getProject()).getDocument(injectedPsi);
int start = ((DocumentWindow)document).hostToInjected(rangeInHostFile.getStartOffset());
int end = ((DocumentWindow)document).hostToInjected(rangeInHostFile.getEndOffset());
result = SelfElementInfo.findElementInside(injectedPsi, start, end, anchorClass, anchorLanguage);
}
PsiFile injectedPsi = getInjectedFileIn(hostContext, hostFile, TextRange.create(segment));
ProperTextRange rangeInInjected = hostToInjected(true, segment, injectedPsi);
if (rangeInInjected == null) return null;
return result;
return SelfElementInfo.findElementInside(injectedPsi, rangeInInjected.getStartOffset(), rangeInInjected.getEndOffset(), anchorClass, anchorLanguage);
}
private PsiFile getInjectedFileIn(@NotNull final PsiElement hostContext,
@@ -161,24 +162,31 @@ class InjectedSelfElementInfo extends SmartPointerElementInfo {
return getInjectedFileIn(hostContext, hostFile, rangeInHostFile);
}
private ProperTextRange getInjectedRange() {
PsiFile hostFile = myHostContext.getContainingFile();
if (hostFile == null || !hostFile.isValid()) return null;
@Nullable
private ProperTextRange getInjectedRange(boolean psi) {
PsiElement hostContext = myHostContext.getElement();
if (hostContext == null) return null;
Segment hostElementRange = myInjectedFileRangeInHostFile.getRange();
Segment hostElementRange = psi ? myInjectedFileRangeInHostFile.getPsiRange() : myInjectedFileRangeInHostFile.getRange();
if (hostElementRange == null) return null;
PsiFile injectedFile = restoreFile();
if (injectedFile == null) return null;
VirtualFile virtualFile = injectedFile.getVirtualFile();
DocumentWindow documentWindow = virtualFile instanceof VirtualFileWindow ? ((VirtualFileWindow)virtualFile).getDocumentWindow() : null;
if (documentWindow==null) return null;
int start = documentWindow.hostToInjected(hostElementRange.getStartOffset());
int end = documentWindow.hostToInjected(hostElementRange.getEndOffset());
return ProperTextRange.create(start, end);
return hostToInjected(psi, hostElementRange, restoreFile());
}
@Nullable
private ProperTextRange hostToInjected(boolean psi, Segment hostRange, @Nullable PsiFile injectedFile) {
VirtualFile virtualFile = injectedFile == null ? null : injectedFile.getVirtualFile();
if (virtualFile instanceof VirtualFileWindow) {
DocumentWindow documentWindow = ((VirtualFileWindow)virtualFile).getDocumentWindow();
if (psi) {
documentWindow = (DocumentWindow) ((PsiDocumentManagerBase) PsiDocumentManager.getInstance(getProject())).getLastCommittedDocument(documentWindow);
}
int start = documentWindow.hostToInjected(hostRange.getStartOffset());
int end = documentWindow.hostToInjected(hostRange.getEndOffset());
return ProperTextRange.create(start, end);
}
return null;
}
@Override
@@ -19,6 +19,7 @@ import com.intellij.lang.Language;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.impl.FrozenDocument;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.*;
@@ -109,7 +110,8 @@ public class SelfElementInfo extends SmartPointerElementInfo {
}
@Nullable
protected ProperTextRange getPsiRange() {
@Override
public ProperTextRange getPsiRange() {
return calcPsiRange();
}
@@ -248,7 +250,7 @@ public class SelfElementInfo extends SmartPointerElementInfo {
PsiDocumentManagerBase documentManager = myManager.getPsiDocumentManager();
List<DocumentEvent> events = documentManager.getEventsSinceCommit(document);
if (!events.isEmpty()) {
return myMarkerCache.getUpdatedRange(markerCacheKey(), documentManager.getLastCommittedDocument(document), events);
return myMarkerCache.getUpdatedRange(markerCacheKey(), (FrozenDocument)documentManager.getLastCommittedDocument(document), events);
}
}
}
@@ -51,4 +51,7 @@ abstract class SmartPointerElementInfo {
public void cleanup() {
}
@Nullable
public abstract Segment getPsiRange();
}
@@ -128,6 +128,12 @@ class SmartPsiElementPointerImpl<E extends PsiElement> implements SmartPointerEx
return myElementInfo.getRange();
}
@Nullable
@Override
public Segment getPsiRange() {
return myElementInfo.getPsiRange();
}
@NotNull
private static <E extends PsiElement> SmartPointerElementInfo createElementInfo(@NotNull Project project,
@NotNull E element,
@@ -70,6 +70,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
@SuppressWarnings({"unchecked"})
public class DirDiffPanel implements Disposable, DataProvider {
public static final String DIVIDER_PROPERTY = "dir.diff.panel.divider.location";
private static final int DIVIDER_PROPERTY_DEFAULT_VALUE = 200;
private JPanel myDiffPanel;
private JBTable myTable;
private JPanel myComponent;
@@ -506,7 +507,7 @@ public class DirDiffPanel implements Disposable, DataProvider {
public void dispose() {
myModel.stopUpdating();
PropertiesComponent.getInstance().setValue(DIVIDER_PROPERTY, String.valueOf(mySplitPanel.getDividerLocation()));
PropertiesComponent.getInstance().setValue(DIVIDER_PROPERTY, mySplitPanel.getDividerLocation(), DIVIDER_PROPERTY_DEFAULT_VALUE);
clearDiffPanel();
}
@@ -528,7 +529,7 @@ public class DirDiffPanel implements Disposable, DataProvider {
}
public void setupSplitter() {
mySplitPanel.setDividerLocation(Integer.valueOf(PropertiesComponent.getInstance().getValue(DIVIDER_PROPERTY, "200")));
mySplitPanel.setDividerLocation(Integer.valueOf(PropertiesComponent.getInstance().getInt(DIVIDER_PROPERTY, DIVIDER_PROPERTY_DEFAULT_VALUE)));
}
@Override
@@ -37,10 +37,10 @@ public class WarnOnDeletion extends ToggleAction implements DumbAware {
}
public static boolean isWarnWhenDeleteItems() {
return !PropertiesComponent.getInstance().isTrueValue(PROPERTY_NAME);
return PropertiesComponent.getInstance().getBoolean(PROPERTY_NAME);
}
public static void setWarnWhenDeleteItems(boolean warn) {
PropertiesComponent.getInstance().setValue(PROPERTY_NAME, Boolean.valueOf(!warn).toString());
PropertiesComponent.getInstance().setValue(PROPERTY_NAME, warn);
}
}
@@ -28,6 +28,7 @@ import com.intellij.openapi.vcs.VcsListener;
import com.intellij.openapi.vcs.VcsRoot;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -53,8 +54,7 @@ public class VcsRepositoryManager extends AbstractProjectComponent implements Di
@NotNull
public static VcsRepositoryManager getInstance(@NotNull Project project) {
//noinspection ConstantConditions
return project.getComponent(VcsRepositoryManager.class);
return ObjectUtils.assertNotNull(project.getComponent(VcsRepositoryManager.class));
}
public VcsRepositoryManager(@NotNull Project project, @NotNull ProjectLevelVcsManager vcsManager) {
@@ -112,6 +112,11 @@ public abstract class ConfigurationFromContext {
return false;
}
@Override
public String toString() {
return getConfigurationSettings().toString();
}
/**
* Compares configurations according to precedence.
*/
@@ -28,5 +28,11 @@ public interface RenameInputValidator {
ExtensionPointName<RenameInputValidator> EP_NAME = ExtensionPointName.create("com.intellij.renameInputValidator");
ElementPattern<? extends PsiElement> getPattern();
/**
* Is invoked for elements accepted by pattern {@link #getPattern()}.
* Should return true if {@link RenameInputValidatorEx} is intended to return custom error message,
* otherwise default message "newName is not a valid identifier" would be shown
*/
boolean isInputValid(final String newName, final PsiElement element, final ProcessingContext context);
}
@@ -16,6 +16,8 @@
package com.intellij.refactoring.rename;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import org.jetbrains.annotations.Nullable;
/**
@@ -23,6 +25,13 @@ import org.jetbrains.annotations.Nullable;
* Date: 3/14/11
*/
public interface RenameInputValidatorEx extends RenameInputValidator {
/**
* Called only if all input validators ({@link RenameInputValidator}) accept
* the new name in {@link #isInputValid(String, PsiElement, ProcessingContext)}
* and name is a valid identifier for a language of the element
*
* @return null if newName is a valid name, custom error message otherwise
*/
@Nullable
String getErrorMessage(String newName, Project project);
}
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.application.options.editor.EditorAppearanceConfigurable">
<grid id="27dc6" binding="myRootPanel" layout-manager="GridLayoutManager" row-count="14" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="0">
<grid id="27dc6" binding="myRootPanel" layout-manager="GridLayoutManager" row-count="15" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="0">
<margin top="0" left="0" bottom="0" right="0"/>
<constraints>
<xy x="20" y="20" width="500" height="451"/>
@@ -10,7 +10,7 @@
<children>
<vspacer id="f3f11">
<constraints>
<grid row="13" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
<grid row="14" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
</vspacer>
<component id="2eb36" class="javax.swing.JCheckBox" binding="myCbBlockCursor">
@@ -86,7 +86,7 @@
</component>
<grid id="7b00c" binding="myAddonPanel" layout-manager="GridBagLayout">
<constraints>
<grid row="12" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="2" indent="0" use-parent-layout="false"/>
<grid row="13" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="2" indent="0" use-parent-layout="false"/>
</constraints>
<properties/>
<border type="none"/>
@@ -146,6 +146,14 @@
<text resource-bundle="messages/IdeBundle" key="checkbox.show.editor.preview.popup"/>
</properties>
</component>
<component id="6c585" class="javax.swing.JCheckBox" binding="myShowBreadcrumbsCheckBox">
<constraints>
<grid row="12" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
</constraints>
<properties>
<text resource-bundle="messages/ApplicationBundle" key="checkbox.show.breadcrumbs"/>
</properties>
</component>
</children>
</grid>
</form>
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -24,7 +24,9 @@ import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.extensions.ExtensionPointName;
import com.intellij.openapi.options.*;
import com.intellij.openapi.options.CompositeConfigurable;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.UnnamedConfigurable;
import com.intellij.openapi.options.ex.ConfigurableWrapper;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
@@ -36,7 +38,7 @@ import java.awt.event.ActionListener;
import java.util.List;
/**
* To provide additional options in Editor | Appearance section register implementation of {@link com.intellij.openapi.options.UnnamedConfigurable} in the plugin.xml:
* To provide additional options in Editor | Appearance section register implementation of {@link UnnamedConfigurable} in the plugin.xml:
* <p/>
* &lt;extensions defaultExtensionNs="com.intellij"&gt;<br>
* &nbsp;&nbsp;&lt;editorAppearanceConfigurable instance="class-name"/&gt;<br>
@@ -64,6 +66,7 @@ public class EditorAppearanceConfigurable extends CompositeConfigurable<UnnamedC
private JCheckBox myShowCodeLensInEditorCheckBox;
private JCheckBox myCbShowIconsInGutter;
private JCheckBox myShowVerticalIndentGuidesCheckBox;
private JCheckBox myShowBreadcrumbsCheckBox;
//private JCheckBox myUseLCDRendering;
public EditorAppearanceConfigurable() {
@@ -115,6 +118,7 @@ public class EditorAppearanceConfigurable extends CompositeConfigurable<UnnamedC
myInnerWhitespacesCheckBox.setSelected(editorSettings.isInnerWhitespacesShown());
myTrailingWhitespacesCheckBox.setSelected(editorSettings.isTrailingWhitespacesShown());
myShowVerticalIndentGuidesCheckBox.setSelected(editorSettings.isIndentGuidesShown());
myShowBreadcrumbsCheckBox.setSelected(editorSettings.isBreadcrumbsShown());
//myAntialiasingInEditorCheckBox.setSelected(UISettings.getInstance().ANTIALIASING_IN_EDITOR);
//myUseLCDRendering.setSelected(UISettings.getInstance().USE_LCD_RENDERING_IN_EDITOR);
myShowCodeLensInEditorCheckBox.setSelected(UISettings.getInstance().SHOW_EDITOR_TOOLTIP);
@@ -132,7 +136,7 @@ public class EditorAppearanceConfigurable extends CompositeConfigurable<UnnamedC
try {
editorSettings.setBlinkPeriod(Integer.parseInt(myBlinkIntervalField.getText()));
}
catch (NumberFormatException e) {
catch (NumberFormatException ignore) {
}
editorSettings.setBlockCursor(myCbBlockCursor.isSelected());
@@ -151,6 +155,7 @@ public class EditorAppearanceConfigurable extends CompositeConfigurable<UnnamedC
UISettings uiSettings = UISettings.getInstance();
boolean uiSettingsModified = false;
boolean lafSettingsModified = false;
//if (uiSettings.ANTIALIASING_IN_EDITOR != myAntialiasingInEditorCheckBox.isSelected()) {
// uiSettings.ANTIALIASING_IN_EDITOR = myAntialiasingInEditorCheckBox.isSelected();
// uiSettingsModified = true;
@@ -164,12 +169,20 @@ public class EditorAppearanceConfigurable extends CompositeConfigurable<UnnamedC
if (uiSettings.SHOW_EDITOR_TOOLTIP != myShowCodeLensInEditorCheckBox.isSelected()) {
uiSettings.SHOW_EDITOR_TOOLTIP = myShowCodeLensInEditorCheckBox.isSelected();
uiSettingsModified = true;
lafSettingsModified = true;
}
if (uiSettingsModified) {
LafManager.getInstance().repaintUI();
uiSettings.fireUISettingsChanged();
if(editorSettings.isBreadcrumbsShown() != myShowBreadcrumbsCheckBox.isSelected()) {
editorSettings.setBreadcrumbsShown(myShowBreadcrumbsCheckBox.isSelected());
uiSettingsModified = true;
}
if (lafSettingsModified) {
LafManager.getInstance().repaintUI();
}
if (uiSettingsModified) {
uiSettings.fireUISettingsChanged();
}
EditorOptionsPanel.restartDaemons();
super.apply();
@@ -197,6 +210,7 @@ public class EditorAppearanceConfigurable extends CompositeConfigurable<UnnamedC
//isModified |= myAntialiasingInEditorCheckBox.isSelected() != UISettings.getInstance().ANTIALIASING_IN_EDITOR;
//isModified |= myUseLCDRendering.isSelected() != UISettings.getInstance().USE_LCD_RENDERING_IN_EDITOR;
isModified |= myShowCodeLensInEditorCheckBox.isSelected() != UISettings.getInstance().SHOW_EDITOR_TOOLTIP;
isModified |= myShowBreadcrumbsCheckBox.isSelected() != editorSettings.isBreadcrumbsShown();
return isModified;
}
@@ -229,8 +243,11 @@ public class EditorAppearanceConfigurable extends CompositeConfigurable<UnnamedC
@Override
public JComponent createComponent() {
for (UnnamedConfigurable provider : getConfigurables()) {
myAddonPanel.add(provider.createComponent(), new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0, 0, GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE, new Insets(0,0,15,0), 0,0));
JComponent component = provider.createComponent();
if (component != null) {
myAddonPanel.add(component, new GridBagConstraints(0, GridBagConstraints.RELATIVE, 1, 1, 0, 0, GridBagConstraints.NORTHWEST,
GridBagConstraints.NONE, new Insets(0, 0, 15, 0), 0, 0));
}
}
return myRootPanel;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 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.
@@ -53,11 +53,11 @@ public class LastRunReformatCodeOptionsProvider {
}
public boolean getLastOptimizeImports() {
return myPropertiesComponent.getBoolean(OPTIMIZE_IMPORTS_KEY, false);
return myPropertiesComponent.getBoolean(OPTIMIZE_IMPORTS_KEY);
}
public TextRangeType getLastTextRangeType() {
return myPropertiesComponent.getBoolean(PROCESS_CHANGED_TEXT_KEY, false) ? TextRangeType.VCS_CHANGED_TEXT : TextRangeType.WHOLE_FILE;
return myPropertiesComponent.getBoolean(PROCESS_CHANGED_TEXT_KEY) ? TextRangeType.VCS_CHANGED_TEXT : TextRangeType.WHOLE_FILE;
}
public void saveProcessVcsChangedTextState(boolean value) {
@@ -66,16 +66,16 @@ public class LastRunReformatCodeOptionsProvider {
}
public void saveRearrangeCodeState(boolean value) {
myPropertiesComponent.setValue(REARRANGE_ENTRIES_KEY, Boolean.toString(value));
myPropertiesComponent.setValue(REARRANGE_ENTRIES_KEY, value);
}
public boolean getLastRearrangeCode() {
return myPropertiesComponent.getBoolean(REARRANGE_ENTRIES_KEY, false);
return myPropertiesComponent.getBoolean(REARRANGE_ENTRIES_KEY);
}
public boolean isRearrangeCode(@NotNull Language language) {
String key = getRearrangeCodeKeyFor(language);
return myPropertiesComponent.getBoolean(key, false);
return myPropertiesComponent.getBoolean(key);
}
private static String getRearrangeCodeKeyFor(@NotNull Language language) {
@@ -55,6 +55,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -214,6 +215,7 @@ public class CommentByLineCommentHandler extends MultiCaretCodeInsightActionHand
}
}
// third pass - actual change
Collections.reverse(myBlocks);
for (Block block : myBlocks) {
if (!block.skip) {
if (!allLinesCommented) {
@@ -15,19 +15,33 @@
*/
package com.intellij.codeInsight.lookup.impl;
import com.intellij.codeInsight.lookup.LookupItem;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import org.jetbrains.annotations.NotNull;
/**
* @author peter
*/
public class EmptyLookupItem extends LookupItem<String> {
public class EmptyLookupItem extends LookupElement {
private final String myText;
private final boolean myLoading;
public EmptyLookupItem(final String s, boolean loading) {
super(s, " ");
myText = s;
myLoading = loading;
}
@NotNull
@Override
public String getLookupString() {
return " ";
}
@Override
public void renderElement(LookupElementPresentation presentation) {
presentation.setItemText(myText);
}
public boolean isLoading() {
return myLoading;
}
@@ -424,7 +424,7 @@ public class LookupImpl extends LightweightHint implements LookupEx, Disposable,
}
private void addEmptyItem(CollectionListModel<LookupElement> model) {
LookupItem<String> item = new EmptyLookupItem(myCalculating ? " " : LangBundle.message("completion.no.suggestions"), false);
LookupElement item = new EmptyLookupItem(myCalculating ? " " : LangBundle.message("completion.no.suggestions"), false);
myMatchers.put(item, new CamelHumpMatcher(""));
model.add(item);
@@ -99,7 +99,7 @@ public class DuplexConsoleView<S extends ConsoleView, T extends ConsoleView> ext
if (myStateStorageKey == null) {
return false;
}
return PropertiesComponent.getInstance().getBoolean(myStateStorageKey, false);
return PropertiesComponent.getInstance().getBoolean(myStateStorageKey);
}
public void enableConsole(boolean primary) {
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.console;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
@@ -174,7 +189,7 @@ public final class LanguageConsoleBuilder {
if (processInputStateKey != null) {
assert executeActionHandler != null;
if (PropertiesComponent.getInstance().getBoolean(processInputStateKey, false)) {
if (PropertiesComponent.getInstance().getBoolean(processInputStateKey)) {
executeActionHandler.myUseProcessStdIn = true;
DaemonCodeAnalyzer daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(consoleView.getProject());
daemonCodeAnalyzer.setHighlightingEnabled(consoleView.getFile(), false);
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.console;
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
@@ -24,7 +39,7 @@ final class UseConsoleInputAction extends ToggleAction implements DumbAware {
super("Use Console Input", null, AllIcons.Debugger.CommandLine);
this.processInputStateKey = processInputStateKey;
useProcessStdIn = PropertiesComponent.getInstance().getBoolean(processInputStateKey, false);
useProcessStdIn = PropertiesComponent.getInstance().getBoolean(processInputStateKey);
}
@Override
@@ -42,12 +57,7 @@ final class UseConsoleInputAction extends ToggleAction implements DumbAware {
PsiFile file = consoleView.getFile();
daemonCodeAnalyzer.setHighlightingEnabled(file, state);
daemonCodeAnalyzer.restart(file);
if (state) {
PropertiesComponent.getInstance().unsetValue(processInputStateKey);
}
else {
PropertiesComponent.getInstance().setValue(processInputStateKey, "true");
}
PropertiesComponent.getInstance().setValue(processInputStateKey, useProcessStdIn);
List<AnAction> actions = ActionUtil.getActions(consoleView.getConsoleEditor().getComponent());
ConsoleExecuteAction action = ContainerUtil.findInstance(actions, ConsoleExecuteAction.class);
@@ -31,7 +31,6 @@ import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collections;
import java.util.List;
/**
@@ -39,21 +38,25 @@ import java.util.List;
*/
public class ExecutorAction extends AnAction {
public static AnAction[] ACTIONS =
ContainerUtil.map2Array(ExecutorRegistry.getInstance().getRegisteredExecutors(), AnAction.class, new Function<Executor, AnAction>() {
public static AnAction[] ACTIONS(final int order) {
return ContainerUtil.map2Array(ExecutorRegistry.getInstance().getRegisteredExecutors(), AnAction.class, new Function<Executor, AnAction>() {
@Override
public AnAction fun(Executor executor) {
return new ExecutorAction(ActionManager.getInstance().getAction(executor.getContextActionId()), executor);
return new ExecutorAction(ActionManager.getInstance().getAction(executor.getContextActionId()), executor, order);
}
});
}
private final AnAction myOrigin;
private final Executor myExecutor;
private final int myOrder;
private ExecutorAction(AnAction origin,
Executor executor) {
Executor executor,
int order) {
myOrigin = origin;
myExecutor = executor;
myOrder = order;
copyFrom(origin);
}
@@ -69,7 +72,7 @@ public class ExecutorAction extends AnAction {
myOrigin.actionPerformed(e);
}
private static String getActionName(DataContext dataContext, @NotNull Executor executor) {
private String getActionName(DataContext dataContext, @NotNull Executor executor) {
final ConfigurationContext context = ConfigurationContext.getFromContext(dataContext);
List<RunConfigurationProducer<?>> producers = RunConfigurationProducer.getProducers(context.getProject());
List<ConfigurationFromContext> list = ContainerUtil.mapNotNull(producers,
@@ -81,8 +84,8 @@ public class ExecutorAction extends AnAction {
}
);
if (list.isEmpty()) return null;
Collections.sort(list, ConfigurationFromContext.COMPARATOR);
String actionName = BaseRunConfigurationAction.suggestRunActionName((LocatableConfiguration)list.get(0).getConfiguration());
ConfigurationFromContext configuration = list.get(myOrder < list.size() ? myOrder : 0);
String actionName = BaseRunConfigurationAction.suggestRunActionName((LocatableConfiguration)configuration.getConfiguration());
return executor.getStartActionText(actionName);
}
@@ -42,7 +42,7 @@ public class PowerSaveModeNotifier implements StartupActivity {
}
static void notifyOnPowerSaveMode(Project project) {
if (PropertiesComponent.getInstance().getBoolean(IGNORE_POWER_SAVE_MODE, false)) {
if (PropertiesComponent.getInstance().getBoolean(IGNORE_POWER_SAVE_MODE)) {
return;
}
@@ -871,7 +871,7 @@ public class FileStructurePopup implements Disposable, TreeActionsOwner {
private static boolean getDefaultValue(TreeAction action) {
if (action instanceof PropertyOwner) {
final String propertyName = ((PropertyOwner)action).getPropertyName();
return PropertiesComponent.getInstance().getBoolean(TreeStructureUtil.getPropertyName(propertyName), false);
return PropertiesComponent.getInstance().getBoolean(TreeStructureUtil.getPropertyName(propertyName));
}
return false;
@@ -880,7 +880,7 @@ public class FileStructurePopup implements Disposable, TreeActionsOwner {
private static void saveState(TreeAction action, boolean state) {
if (action instanceof PropertyOwner) {
final String propertyName = ((PropertyOwner)action).getPropertyName();
PropertiesComponent.getInstance().setValue(TreeStructureUtil.getPropertyName(propertyName), Boolean.toString(state));
PropertiesComponent.getInstance().setValue(TreeStructureUtil.getPropertyName(propertyName), state);
}
}
@@ -79,17 +79,17 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
protected final Map<String, ApplyIntentionAction> myIntentions = new TreeMap<String, ApplyIntentionAction>();
private final Map<String, String> myConfigurablesNames = ContainerUtil.newTroveMap();
public GotoActionModel(@Nullable Project project, final Component component) {
public GotoActionModel(@Nullable Project project, Component component) {
this(project, component, null, null);
}
public GotoActionModel(@Nullable Project project, final Component component, @Nullable Editor editor, @Nullable PsiFile file) {
public GotoActionModel(@Nullable Project project, Component component, @Nullable Editor editor, @Nullable PsiFile file) {
myProject = project;
myContextComponent = component;
final ActionGroup mainMenu = (ActionGroup)myActionManager.getActionOrStub(IdeActions.GROUP_MAIN_MENU);
ActionGroup mainMenu = (ActionGroup)myActionManager.getActionOrStub(IdeActions.GROUP_MAIN_MENU);
collectActions(myActionGroups, mainMenu, mainMenu.getTemplatePresentation().getText());
if (project != null && editor != null && file != null) {
final ApplyIntentionAction[] children = ApplyIntentionAction.getAvailableIntentions(editor, file);
ApplyIntentionAction[] children = ApplyIntentionAction.getAvailableIntentions(editor, file);
if (children != null) {
for (ApplyIntentionAction action : children) {
myIntentions.put(action.getName(), action);
@@ -232,12 +232,12 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
});
}
protected String getActionId(@NotNull final AnAction anAction) {
protected String getActionId(@NotNull AnAction anAction) {
return myActionManager.getId(anAction);
}
private static JLabel createIconLabel(final Icon icon) {
final LayeredIcon layeredIcon = new LayeredIcon(2);
private static JLabel createIconLabel(Icon icon) {
LayeredIcon layeredIcon = new LayeredIcon(2);
layeredIcon.setIcon(EMPTY_ICON, 0);
if (icon != null && icon.getIconWidth() <= EMPTY_ICON.getIconWidth() && icon.getIconHeight() <= EMPTY_ICON.getIconHeight()) {
layeredIcon
@@ -248,19 +248,19 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
}
protected JLabel createActionLabel(final AnAction anAction, final String anActionName,
final Color fg, final Color bg,
final Icon icon) {
final LayeredIcon layeredIcon = new LayeredIcon(2);
protected JLabel createActionLabel(AnAction anAction, String anActionName,
Color fg, Color bg,
Icon icon) {
LayeredIcon layeredIcon = new LayeredIcon(2);
layeredIcon.setIcon(EMPTY_ICON, 0);
if (icon != null && icon.getIconWidth() <= EMPTY_ICON.getIconWidth() && icon.getIconHeight() <= EMPTY_ICON.getIconHeight()) {
layeredIcon
.setIcon(icon, 1, (-icon.getIconWidth() + EMPTY_ICON.getIconWidth()) / 2, (EMPTY_ICON.getIconHeight() - icon.getIconHeight()) / 2);
}
final Shortcut shortcut = preferKeyboardShortcut(KeymapManager.getInstance().getActiveKeymap().getShortcuts(getActionId(anAction)));
final String actionName = anActionName + (shortcut != null ? " (" + KeymapUtil.getShortcutText(shortcut) + ")" : "");
final JLabel actionLabel = new JLabel(actionName, layeredIcon, SwingConstants.LEFT);
Shortcut shortcut = preferKeyboardShortcut(KeymapManager.getInstance().getActiveKeymap().getShortcuts(getActionId(anAction)));
String actionName = anActionName + (shortcut != null ? " (" + KeymapUtil.getShortcutText(shortcut) + ")" : "");
JLabel actionLabel = new JLabel(actionName, layeredIcon, SwingConstants.LEFT);
actionLabel.setBackground(bg);
actionLabel.setForeground(fg);
return actionLabel;
@@ -304,7 +304,7 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
@Override
@NotNull
public Object[] getElementsByName(final String id, final boolean checkBoxState, final String pattern) {
public Object[] getElementsByName(String id, boolean checkBoxState, String pattern) {
return ArrayUtil.EMPTY_OBJECT_ARRAY;
}
@@ -317,7 +317,7 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
return settings + " > " + name;
}
private void collectActions(Map<AnAction, String> result, ActionGroup group, final String containingGroupName) {
private void collectActions(Map<AnAction, String> result, ActionGroup group, String containingGroupName) {
AnAction[] actions = group.getChildren(null);
includeGroup(result, group, actions, containingGroupName);
for (AnAction action : actions) {
@@ -357,7 +357,7 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
@Override
@Nullable
public String getFullName(final Object element) {
public String getFullName(Object element) {
return getElementName(element);
}
@@ -374,13 +374,13 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
}
@Override
public String getElementName(final Object mv) {
public String getElementName(Object mv) {
return ((MatchedValue) mv).getValueText();
}
@Override
public boolean matches(@NotNull final String name, @NotNull final String pattern) {
final AnAction anAction = myActionManager.getAction(name);
public boolean matches(@NotNull String name, @NotNull String pattern) {
AnAction anAction = myActionManager.getAction(name);
if (anAction == null) return true;
return actionMatches(pattern, anAction) != MatchMode.NONE;
}
@@ -456,7 +456,7 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
}
static String convertPattern(String pattern) {
final int eol = pattern.indexOf('\n');
int eol = pattern.indexOf('\n');
if (eol != -1) {
pattern = pattern.substring(0, eol);
}
@@ -464,7 +464,7 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
pattern = pattern.substring(0, 80);
}
@NonNls final StringBuilder buffer = new StringBuilder();
@NonNls StringBuilder buffer = new StringBuilder();
boolean allowToLower = true;
if (containsOnlyUppercaseLetters(pattern)) {
@@ -477,7 +477,7 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
boolean firstIdentifierLetter = true;
for (int i = 0; i < pattern.length(); i++) {
final char c = pattern.charAt(i);
char c = pattern.charAt(i);
if (Character.isLetterOrDigit(c)) {
// This logic allows to use uppercase letters only to catch the name like PDM for PsiDocumentManager
if (Character.isUpperCase(c) || Character.isDigit(c)) {
@@ -643,11 +643,11 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
}
@Override
public Component getListCellRendererComponent(@NotNull final JList list,
final Object matchedValue,
final int index, final boolean isSelected, final boolean cellHasFocus) {
public Component getListCellRendererComponent(@NotNull JList list,
Object matchedValue,
int index, boolean isSelected, boolean cellHasFocus) {
boolean showIcon = UISettings.getInstance().SHOW_ICONS_IN_MENUS;
final JPanel panel = new JPanel(new BorderLayout());
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(IdeBorderFactory.createEmptyBorder(2));
panel.setOpaque(true);
Color bg = UIUtil.getListBackground(isSelected);
@@ -667,23 +667,23 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
Color groupFg = isSelected ? UIUtil.getListSelectionForeground() : UIUtil.getLabelDisabledForeground();
final Object value = ((MatchedValue) matchedValue).value;
Object value = ((MatchedValue) matchedValue).value;
String pattern = ((MatchedValue)matchedValue).pattern;
Border eastBorder = IdeBorderFactory.createEmptyBorder(0, 0, 0, 2);
if (value instanceof ActionWrapper) {
final ActionWrapper actionWithParentGroup = (ActionWrapper)value;
final AnAction anAction = actionWithParentGroup.getAction();
final Presentation presentation = anAction.getTemplatePresentation();
ActionWrapper actionWithParentGroup = (ActionWrapper)value;
AnAction anAction = actionWithParentGroup.getAction();
Presentation presentation = anAction.getTemplatePresentation();
boolean toggle = anAction instanceof ToggleAction;
String groupName = actionWithParentGroup.getAction() instanceof ApplyIntentionAction ? null : actionWithParentGroup.getGroupName();
final Color fg = defaultActionForeground(isSelected, actionWithParentGroup.getPresentation());
Color fg = defaultActionForeground(isSelected, actionWithParentGroup.getPresentation());
if (showIcon) {
panel.add(createIconLabel(presentation.getIcon()), BorderLayout.WEST);
}
appendWithColoredMatches(nameComponent, getName(presentation.getText(), groupName, toggle), pattern, fg, isSelected);
final Shortcut shortcut = preferKeyboardShortcut(KeymapManager.getInstance().getActiveKeymap().getShortcuts(ActionManager.getInstance().getId(anAction)));
Shortcut shortcut = preferKeyboardShortcut(KeymapManager.getInstance().getActiveKeymap().getShortcuts(ActionManager.getInstance().getId(anAction)));
if (shortcut != null) {
nameComponent.append(" " + KeymapUtil.getShortcutText(shortcut),
new SimpleTextAttributes(SimpleTextAttributes.STYLE_SMALLER | SimpleTextAttributes.STYLE_BOLD,
@@ -691,14 +691,13 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
}
if (toggle) {
final OnOffButton button = new OnOffButton();
AnActionEvent event = AnActionEvent.createFromDataContext(ActionPlaces.UNKNOWN, null, ((ActionWrapper)value).myDataContext);
button.setSelected(((ToggleAction)anAction).isSelected(event));
panel.add(button, BorderLayout.EAST);
boolean selected = ((ToggleAction)anAction).isSelected(event);
addOnOffButton(panel, selected);
}
else {
if (groupName != null) {
final JLabel groupLabel = new JLabel(groupName);
JLabel groupLabel = new JLabel(groupName);
groupLabel.setBackground(bg);
groupLabel.setBorder(eastBorder);
groupLabel.setForeground(groupFg);
@@ -721,7 +720,7 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
String fullHit = hit;
hit = StringUtil.first(hit, 45, true);
final Color fg = UIUtil.getListForeground(isSelected);
Color fg = UIUtil.getListForeground(isSelected);
appendWithColoredMatches(nameComponent, hit.trim(), pattern, fg, isSelected);
@@ -731,12 +730,11 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
panel.setToolTipText(fullHit);
if (value instanceof BooleanOptionDescription) {
final OnOffButton button = new OnOffButton();
button.setSelected(((BooleanOptionDescription)value).isOptionEnabled());
panel.add(button, BorderLayout.EAST);
boolean selected = ((BooleanOptionDescription)value).isOptionEnabled();
addOnOffButton(panel, selected);
}
else {
final JLabel settingsLabel = new JLabel(myGroupNamer.fun((OptionDescription)value));
JLabel settingsLabel = new JLabel(myGroupNamer.fun((OptionDescription)value));
settingsLabel.setForeground(groupFg);
settingsLabel.setBackground(bg);
settingsLabel.setBorder(eastBorder);
@@ -746,6 +744,13 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
return panel;
}
private static void addOnOffButton(@NotNull JPanel panel, boolean selected) {
OnOffButton button = new OnOffButton();
button.setSelected(selected);
panel.add(button, BorderLayout.EAST);
panel.setBorder(IdeBorderFactory.createEmptyBorder(0, 2, 0, 2));
}
public String getName(String text, String groupName, boolean toggle) {
return toggle && StringUtil.isNotEmpty(groupName)? groupName + ": "+ text : text;
}
@@ -755,8 +760,8 @@ public class GotoActionModel implements ChooseByNameModel, CustomMatcherModel, C
String pattern,
Color fg,
boolean selected) {
final SimpleTextAttributes plain = new SimpleTextAttributes(STYLE_PLAIN, fg);
final SimpleTextAttributes highlighted = new SimpleTextAttributes(null, fg, null, STYLE_SEARCH_MATCH);
SimpleTextAttributes plain = new SimpleTextAttributes(STYLE_PLAIN, fg);
SimpleTextAttributes highlighted = new SimpleTextAttributes(null, fg, null, STYLE_SEARCH_MATCH);
List<TextRange> fragments = ContainerUtil.newArrayList();
if (selected) {
int matchStart = StringUtil.indexOfIgnoreCase(name, pattern, 0);

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