*/
package org.intellij.lang.regexp;
-import com.intellij.application.options.colors.InspectionColorSettingsPage;
import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.openapi.options.colors.AttributesDescriptor;
/**
* @author traff
*/
-public class RegExpColorsPage implements ColorSettingsPage, InspectionColorSettingsPage {
+public class RegExpColorsPage implements ColorSettingsPage {
private static final AttributesDescriptor[] ATTRS = new AttributesDescriptor[] {
- new AttributesDescriptor("Keywords", RegExpHighlighter.META),
- new AttributesDescriptor("Escaped characters", RegExpHighlighter.ESC_CHARACTER),
- new AttributesDescriptor("Braces", RegExpHighlighter.BRACES),
- new AttributesDescriptor("Brackets", RegExpHighlighter.BRACKETS),
+ new AttributesDescriptor("Keyword", RegExpHighlighter.META),
+ new AttributesDescriptor("Escaped character", RegExpHighlighter.ESC_CHARACTER),
+ new AttributesDescriptor("Invalid escape sequence", RegExpHighlighter.INVALID_CHARACTER_ESCAPE),
+ new AttributesDescriptor("Redundant escape sequence", RegExpHighlighter.REDUNDANT_ESCAPE),
+ new AttributesDescriptor("Brace", RegExpHighlighter.BRACES),
+ new AttributesDescriptor("Bracket", RegExpHighlighter.BRACKETS),
new AttributesDescriptor("Parenthesis", RegExpHighlighter.PARENTHS),
+ new AttributesDescriptor("Comma", RegExpHighlighter.COMMA),
+ new AttributesDescriptor("Bad character", RegExpHighlighter.BAD_CHARACTER),
+ new AttributesDescriptor("Character class", RegExpHighlighter.CHAR_CLASS),
+ new AttributesDescriptor("Quote character", RegExpHighlighter.QUOTE_CHARACTER),
+ new AttributesDescriptor("Comment", RegExpHighlighter.COMMENT)
};
@NonNls private static final HashMap<String,TextAttributesKey> ourTagToDescriptorMap = new HashMap<String, TextAttributesKey>();
@NotNull
public String getDemoText() {
return
- "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$";
+ "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}\\x0g\\#\\p{alpha}\\Q\\E$";
}
"REGEXP.QUOTE_CHARACTER",
SyntaxHighlighterColors.VALID_STRING_ESCAPE.getDefaultAttributes()
);
- static final TextAttributesKey CTRL_CHARACTER = TextAttributesKey.createTextAttributesKey(
- "REGEXP.CTRL_CHARACTER",
- SyntaxHighlighterColors.VALID_STRING_ESCAPE.getDefaultAttributes()
- );
static final TextAttributesKey COMMENT = TextAttributesKey.createTextAttributesKey(
"REGEXP.COMMENT",
SyntaxHighlighterColors.LINE_COMMENT.getDefaultAttributes()
keys1.put(RegExpTT.BAD_HEX_VALUE, INVALID_CHARACTER_ESCAPE);
keys1.put(RegExpTT.BAD_OCT_VALUE, INVALID_CHARACTER_ESCAPE);
- keys1.put(RegExpTT.CTRL_CHARACTER, CTRL_CHARACTER);
keys1.put(RegExpTT.PROPERTY, CHAR_CLASS);
keys1.put(RegExpTT.ESC_CHARACTER, ESC_CHARACTER);
:: ---------------------------------------------------------------------
:: Before you run IntelliJ IDEA specify the location of the
-:: JDK 1.5 installation directory which will be used for running IDEA
+:: JDK 1.6 installation directory which will be used for running IDEA
:: ---------------------------------------------------------------------
IF "%IDEA_JDK%" == "" SET IDEA_JDK=%JDK_HOME%
IF "%IDEA_JDK%" == "" goto error
--- /dev/null
+IntelliJ IDEA
+
+INSTALLATION INSTRUCTIONS
+===============================================================================
+
+ Linux Installation Instructions
+ ------------------------------------------------------------------------------
+ 1. Unpack the IntelliJ IDEA distribution file that you downloaded to
+ where you wish to install the program. We will refer to this destination
+ location as your {installation home} below.
+
+ 2. Open a console and cd into "{installation home}/bin" and type:
+
+ ./idea.sh
+
+ to start the application.
+
+ 3. [OPTIONAL] Add the "{installation home}/bin" to your PATH environmental
+ variable so that you may start IntelliJ IDEA from any directory.
+
+ 4. [OPTIONAL] To adjust the value of JVM heap size open idea.vmoptions and
+ modify the -Xms and -Xmx parameters.
+
+
+ [OPTIONAL] Changing location of "config" and "system" directory
+ ------------------------------------------------------------------------------
+ By default IDEA stores all your settings under ~/.IntelliJIdea10/config directory
+ and stores data cache under ~/.IntelliJIdea10/system directory.
+ If you want to change these settings,
+
+ 1. Open a console and cd into "{installation home}/bin"
+
+ 2. Open file "idea.properties" in an editor. You should find strings like
+
+ idea.system.path=~/.IntelliJIdea10/system
+
+ and
+
+ idea.config.path=~/.IntelliJIdea10/config
+
+ and change them.
+
+ 3. Note that we recommend to store data cache ("system" directory) at a disk
+ with at least 1G bytes free space
+
+
+
+
+Enjoy!
+
+-IntelliJ IDEA Development Team
fileset(dir: "$home/bin/nix")
fileset(dir: "$home/build/images")
}
+ fileset(dir: "$home/build", includes: "Install-Linux-tar.txt")
}
patchPropertiesFile(paths.distUnix)
<feedback eap-url="http://youtrack.jetbrains.net" release-url="http://www.jetbrains.com/feedback/feedback.jsp?product=IDEA&build=$BUILD&timezone=$TIMEZONE&eval=$EVAL"/>
<plugins url="http://plugins.intellij.net"/>
<whatsnew url="http://www.jetbrains.com/idea/whatsnew/index.html"/>
- <keymap win="http://www.jetbrains.com/idea/docs/IntelliJIDEA9_ReferenceCard.pdf"
- mac="http://www.jetbrains.com/idea/docs/IntelliJIDEA9_ReferenceCard_Mac.pdf"/>
+ <keymap win="http://www.jetbrains.com/idea/docs/IntelliJIDEA_ReferenceCard.pdf"
+ mac="http://www.jetbrains.com/idea/docs/IntelliJIDEA_ReferenceCard_Mac.pdf"/>
<plugins-page category="VCS Integration" title="Select VCS Integration Plugins"/>
<plugins-page title="Select Other Plugins"/>
import com.intellij.rt.execution.junit.segments.PacketProcessor;
import com.intellij.rt.execution.junit.segments.SegmentedStream;
import com.intellij.util.StringBuilderSpinAllocator;
-import com.intellij.util.containers.HashMap;
import java.io.BufferedReader;
import java.io.IOException;
if (nextByte != SegmentedStream.SPECIAL_SYMBOL) break;
final Integer packetRead = readControlSequence();
if (packetRead != null) break;
+ if (available() == 0) return -1;
}
return nextByte;
}
import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl;
import com.intellij.openapi.projectRoots.impl.SdkConfigurationUtil;
import com.intellij.openapi.roots.OrderRootType;
-import com.intellij.openapi.roots.ui.configuration.OrderRootTypeUIFactory;
+import com.intellij.openapi.roots.ui.OrderRootTypeUIFactory;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.ActionCallback;
for (OrderRootType type : OrderRootType.getAllTypes()) {
if (mySdk == null || mySdk.getSdkType().isRootTypeApplicable(type)) {
final PathEditor pathEditor = OrderRootTypeUIFactory.FACTORY.getByKey(type).createPathEditor(mySdk);
- myTabbedPane.addTab(pathEditor.getDisplayName(), pathEditor.createComponent());
- myPathEditors.put(type, pathEditor);
+ if (pathEditor != null) {
+ myTabbedPane.addTab(pathEditor.getDisplayName(), pathEditor.createComponent());
+ myPathEditors.put(type, pathEditor);
+ }
}
}
*/
package com.intellij.openapi.projectRoots.ui;
-import com.intellij.openapi.project.ProjectBundle;
-import com.intellij.openapi.ui.InputValidator;
-import com.intellij.openapi.ui.Messages;
+import com.intellij.openapi.roots.libraries.doc.DocUrlChooser;
import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.openapi.vfs.VirtualFileManager;
+import org.jetbrains.annotations.Nullable;
import javax.swing.*;
-import java.net.MalformedURLException;
-import java.net.URL;
/**
+ * Note: for languages other than Java use com.intellij.openapi.roots.libraries.doc.DocUrlChooser.
* @author MYakovlev
* Date: Oct 29, 2002
* Time: 8:47:43 PM
*/
public class Util{
+ @Nullable
public static VirtualFile showSpecifyJavadocUrlDialog(JComponent parent) {
return showSpecifyJavadocUrlDialog(parent, "");
}
+ @Nullable
public static VirtualFile showSpecifyJavadocUrlDialog(JComponent parent, String initialValue){
- final String url = Messages.showInputDialog(parent, ProjectBundle.message("sdk.configure.javadoc.url.prompt"),
- ProjectBundle.message("sdk.configure.javadoc.url.title"), Messages.getQuestionIcon(), initialValue, new InputValidator() {
- public boolean checkInput(String inputString) {
- return true;
- }
- public boolean canClose(String inputString) {
- try {
- new URL(inputString);
- return true;
- }
- catch (MalformedURLException e1) {
- Messages.showErrorDialog(e1.getMessage(), ProjectBundle.message("sdk.configure.javadoc.url.title"));
- }
- return false;
- }
- });
- if (url == null) {
- return null;
- }
- return VirtualFileManager.getInstance().findFileByUrl(url);
+ return DocUrlChooser.showSpecifyDocUrlDialog(parent, initialValue);
}
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.ui.PathEditor;
import com.intellij.openapi.roots.AnnotationOrderRootType;
-import com.intellij.openapi.roots.ui.configuration.OrderRootTypeUIFactory;
+import com.intellij.openapi.roots.ui.OrderRootTypeUIFactory;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
return new PathEditor(ProjectBundle.message("sdk.configure.annotations.tab"), AnnotationOrderRootType.getInstance(),
FileChooserDescriptorFactory.createSingleFolderDescriptor());
}
-}
\ No newline at end of file
+}
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.ui.PathEditor;
import com.intellij.openapi.roots.OrderRootType;
-import com.intellij.openapi.roots.ui.configuration.OrderRootTypeUIFactory;
+import com.intellij.openapi.roots.ui.OrderRootTypeUIFactory;
import com.intellij.openapi.util.IconLoader;
import javax.swing.*;
public String getNodeText() {
return ProjectBundle.message("library.classes.node");
}
-}
\ No newline at end of file
+}
import com.intellij.openapi.roots.libraries.ui.ChooserBasedAttachRootButtonDescriptor;
import com.intellij.openapi.roots.libraries.ui.LibraryRootsComponentDescriptor;
import com.intellij.openapi.roots.libraries.ui.OrderRootTypePresentation;
-import com.intellij.openapi.roots.ui.configuration.OrderRootTypeUIFactory;
+import com.intellij.openapi.roots.ui.OrderRootTypeUIFactory;
import com.intellij.openapi.roots.ui.configuration.PathUIUtils;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.ui.PathEditor;
+import com.intellij.openapi.roots.ui.OrderRootTypeUIFactory;
import com.intellij.openapi.projectRoots.ui.Util;
import com.intellij.openapi.roots.JavadocOrderRootType;
-import com.intellij.openapi.roots.ui.configuration.OrderRootTypeUIFactory;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.java.LanguageLevel;
return "";
}
}
-}
\ No newline at end of file
+}
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
import com.intellij.openapi.project.ProjectBundle;
import com.intellij.openapi.projectRoots.Sdk;
+import com.intellij.openapi.roots.ui.OrderRootTypeUIFactory;
import com.intellij.openapi.projectRoots.ui.PathEditor;
import com.intellij.openapi.roots.OrderRootType;
-import com.intellij.openapi.roots.ui.configuration.OrderRootTypeUIFactory;
import com.intellij.openapi.roots.ui.configuration.PathUIUtils;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.vfs.VirtualFile;
public String getNodeText() {
return ProjectBundle.message("library.sources.node");
}
-}
\ No newline at end of file
+}
import com.intellij.util.Consumer;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.util.HashSet;
import java.util.Set;
final PsiClass psiClass = (PsiClass)object;
if (JavaCompletionUtil.hasAccessibleInnerClass(psiClass, myPosition)) return;
- ContainerUtil.addIfNotNull(myAddedClasses, psiClass.getQualifiedName());
+ ContainerUtil.addIfNotNull(myAddedClasses, getClassName(psiClass));
}
myResult.addElement(AutoCompletionPolicy.NEVER_AUTOCOMPLETE.applyPolicy(lookupElement));
}
+ @Nullable
+ private static String getClassName(PsiClass psiClass) {
+ String name = psiClass.getQualifiedName();
+ return name == null ? psiClass.getName() : name;
+ }
+
public boolean alreadyProcessed(@NotNull LookupElement element) {
final Object object = element.getObject();
- if (object instanceof PsiClass) {
- if (alreadyProcessed((PsiClass)object)) return true;
- }
- return false;
+ return object instanceof PsiClass && alreadyProcessed((PsiClass)object);
}
public boolean alreadyProcessed(@NotNull PsiClass object) {
- final String qualifiedName = object.getQualifiedName();
- if (qualifiedName == null || myAddedClasses.contains(qualifiedName)) {
- return true;
- }
- return false;
+ final String name = getClassName(object);
+ return name == null || myAddedClasses.contains(name);
}
}
*/
package com.intellij.codeInsight.completion;
+import com.intellij.codeInsight.CodeInsightSettings;
import com.intellij.codeInsight.CodeInsightUtilBase;
import com.intellij.codeInsight.ExpectedTypeInfo;
import com.intellij.codeInsight.TailType;
return defType;
}
- final PsiExpression enclosing = PsiTreeUtil.getContextOfType(myPosition, PsiExpression.class, true);
LookupElement item = getDelegate();
+ Object object = item.getObject();
+ if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET && (object instanceof PsiMethod || object instanceof PsiClass)) {
+ return TailType.NONE;
+ }
+
+ final PsiExpression enclosing = PsiTreeUtil.getContextOfType(myPosition, PsiExpression.class, true);
- if (enclosing != null && item.getObject() instanceof PsiElement) {
+ if (enclosing != null && object instanceof PsiElement) {
final PsiType type = getItemType(item);
final TailType itemType = item instanceof LookupItem ? ((LookupItem)item).getTailType() : TailType.NONE;
TailType cached = itemType;
import com.intellij.formatting.*;
import com.intellij.lang.ASTNode;
+import com.intellij.psi.JavaTokenType;
import com.intellij.psi.codeStyle.CodeStyleSettings;
import com.intellij.psi.formatter.FormatterUtil;
import com.intellij.psi.impl.source.tree.ElementType;
import com.intellij.psi.impl.source.tree.JavaDocElementType;
+import com.intellij.psi.impl.source.tree.JavaElementType;
import com.intellij.psi.impl.source.tree.StdTokenSets;
import com.intellij.psi.tree.IElementType;
+import com.intellij.psi.tree.TokenSet;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
public class BlockContainingJavaBlock extends AbstractJavaBlock{
+ private static final TokenSet TYPES_OF_STATEMENTS_WITH_OPTIONAL_BRACES = TokenSet.create(
+ JavaElementType.IF_STATEMENT, JavaElementType.WHILE_STATEMENT, JavaElementType.FOR_STATEMENT
+ );
+
private final static int BEFORE_FIRST = 0;
private final static int BEFORE_BLOCK = 1;
private final static int AFTER_ELSE = 2;
return new ChildAttributes(getCodeBlockExternalIndent(), null);
}
+ boolean useExternalIndent = false;
if (newChildIndex == getSubBlocks().size()) {
+ useExternalIndent = true;
+ }
+ else if (TYPES_OF_STATEMENTS_WITH_OPTIONAL_BRACES.contains(myNode.getElementType())) {
+ // There is a possible case that we have situation like below:
+ // if (true) <enter was pressed here>
+ // <caret>
+ // System.out.println();
+ // We would like to indent current caret position then because there is a high probability that the user starts
+ // typing there (populating statement body). So, we perform dedicated check for that here and use 'external indent'
+ // if necessary.
+ Block prevBlock = getSubBlocks().get(newChildIndex - 1);
+ Block nextBlock = getSubBlocks().get(newChildIndex);
+ if (prevBlock instanceof ASTBlock && nextBlock instanceof ASTBlock) {
+ ASTNode prevNode = ((ASTBlock)prevBlock).getNode();
+ ASTNode nextNode = ((ASTBlock)nextBlock).getNode();
+ if (prevNode != null && nextNode != null && prevNode.getElementType() == JavaTokenType.RPARENTH
+ && nextNode.getElementType() != JavaTokenType.LBRACE)
+ {
+ useExternalIndent = true;
+ }
+ }
+ }
+
+ if (useExternalIndent) {
return new ChildAttributes(getCodeBlockChildExternalIndent(newChildIndex), null);
}
-
- return new ChildAttributes(myIndentsBefore.get(newChildIndex), null);
-
+ else {
+ return new ChildAttributes(myIndentsBefore.get(newChildIndex), null);
+ }
}
private boolean isInsideForParens(final int newChildIndex) {
*/
package com.intellij.refactoring.changeSignature.inCallers;
+import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiMethod;
import com.intellij.refactoring.changeSignature.CallerChooserBase;
public class JavaCallerChooser extends CallerChooserBase<PsiMethod> {
public JavaCallerChooser(PsiMethod method, Project project, String title, Tree previousTree, Consumer<Set<PsiMethod>> callback) {
- super(method, project, title, previousTree, callback);
+ super(method, project, title, previousTree, "dummy." + StdFileTypes.JAVA.getDefaultExtension(), callback);
}
@Override
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.presentation.java.SymbolPresentationUtil;
import com.intellij.psi.util.PsiTreeUtil;
final String className = getClassName();
if (className.length() == 0 || !nameHelper.isIdentifier(className)) {
- throw new ConfigurationException("\'" + StringUtil.first(className, 10, true) + "\' is invalid extracted class name");
+ throw new ConfigurationException("\'" + className + "\' is invalid extracted class name");
}
final String packageName = getPackageName();
if (packageName.length() == 0 || !nameHelper.isQualifiedName(packageName)){
- throw new ConfigurationException("\'" + StringUtil.last(packageName, 10, true) + "\' is invalid extracted class package name");
+ throw new ConfigurationException("\'" + packageName + "\' is invalid extracted class package name");
}
}
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
import com.intellij.psi.codeStyle.SuggestedNameInfo;
final String fieldName = getFieldName();
final PsiNameHelper helper = JavaPsiFacade.getInstance(myProject).getNameHelper();
if (!helper.isIdentifier(fieldName)){
- throw new ConfigurationException("\'" + StringUtil.first(fieldName, 10, true) + "\' is invalid field name for delegation");
+ throw new ConfigurationException("\'" + fieldName + "\' is invalid field name for delegation");
}
if (myInnerClassNameField != null) {
final String className = myInnerClassNameField.getEnteredName();
if (!helper.isIdentifier(className)) {
- throw new ConfigurationException("\'" + StringUtil.first(className, 10, true) + "\' is invalid inner class name");
+ throw new ConfigurationException("\'" + className + "\' is invalid inner class name");
}
}
}
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.refactoring.HelpID;
protected void canRun() throws ConfigurationException {
String name = getParameterName();
if (name == null || !JavaPsiFacade.getInstance(myProject).getNameHelper().isIdentifier(name)) {
- throw new ConfigurationException("\'" + StringUtil.first(name != null ? name : "", 10 , true) + "\' is invalid parameter name");
+ throw new ConfigurationException("\'" + (name != null ? name : "") + "\' is invalid parameter name");
}
}
import com.intellij.codeInsight.completion.JavaCompletionUtil;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInsight.intention.impl.TypeExpression;
-import com.intellij.codeInsight.lookup.LookupElement;
-import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.lookup.LookupManager;
-import com.intellij.codeInsight.template.*;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.lang.LanguageRefactoringSupport;
import com.intellij.psi.util.PsiExpressionTrimRenderer;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
-import com.intellij.psi.util.TypeConversionUtil;
import com.intellij.refactoring.*;
import com.intellij.refactoring.introduceField.ElementToWorkOn;
import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer;
import com.intellij.refactoring.util.RefactoringUtil;
import com.intellij.refactoring.util.occurences.ExpressionOccurenceManager;
import com.intellij.refactoring.util.occurences.NotInSuperCallOccurenceFilter;
-import com.intellij.util.Consumer;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.MultiMap;
import org.jetbrains.annotations.NonNls;
final PsiVariable elementToRename = variable.get().getElement();
if (elementToRename != null) {
editor.getCaretModel().moveToOffset(elementToRename.getTextOffset());
- final PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(elementToRename, PsiDeclarationStatement.class);
- final SmartPsiElementPointer<PsiDeclarationStatement> pointer =
- SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationStatement);
- editor.putUserData(ReassignVariableUtil.DECLARATION_KEY, pointer);
- editor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY,
- occurrenceMarkers.toArray(new RangeMarker[occurrenceMarkers.size()]));
final boolean cantChangeFinalModifier = hasWriteAccess || (inFinalContext && choice == OccurrencesChooser.ReplaceChoice.ALL);
- final VariableInplaceRenamer renamer = new VariableInplaceRenamer(elementToRename, editor){
- @Override
- protected void addAdditionalVariables(TemplateBuilderImpl builder) {
- final PsiTypeElement typeElement = elementToRename.getTypeElement();
- builder.replaceElement(typeElement, "Variable_Type",
- ReassignVariableUtil.createExpression(expression, typeElement.getText(), !cantChangeFinalModifier), true, true);
- if (!cantChangeFinalModifier) {
- builder.replaceElement(elementToRename.getModifierList(), "_FINAL_", new FinalExpression(project), false, true);
- }
- }
- };
- renamer.setAdvertisementText(
- ReassignVariableUtil.getAdvertisementText(editor, declarationStatement, elementToRename.getType(), typeSelectorManager.getTypesForAll(), !cantChangeFinalModifier));
- renamer.performInplaceRename(false, new LinkedHashSet<String>(Arrays.asList(suggestedName.names)), new Consumer<Boolean>() {
- @Override
- public void consume(Boolean apply) {
- if (apply) {
- final Document document = editor.getDocument();
- final PsiDeclarationStatement declarationStatement = pointer.getElement();
- final PsiVariable psiVariable = declarationStatement != null ? (PsiVariable)declarationStatement.getDeclaredElements()[0] : null;
- if (psiVariable != null) {
- JavaRefactoringSettings.getInstance().INTRODUCE_LOCAL_CREATE_FINALS = psiVariable.hasModifierProperty(PsiModifier.FINAL);
- FinalExpression.adjustLine(psiVariable, document);
- }
- int startOffset = exprMarker.getStartOffset();
- final PsiReference referenceAt = file.findReferenceAt(startOffset);
- if (referenceAt != null && referenceAt.resolve() instanceof PsiLocalVariable) {
- startOffset = referenceAt.getElement().getTextRange().getEndOffset();
- } else if (declarationStatement != null) {
- startOffset = declarationStatement.getTextRange().getEndOffset();
- }
- editor.getCaretModel().moveToOffset(startOffset);
- final PsiType selectedType = ReassignVariableUtil.getVariableType(declarationStatement);
- if (selectedType != null) {
- typeSelectorManager.typeSelected(selectedType);
- }
- ApplicationManager.getApplication().runWriteAction(new Runnable() {
- public void run() {
- appendTypeCasts(occurrenceMarkers, file, project, psiVariable);
- }
- });
- }
- editor.putUserData(ReassignVariableUtil.DECLARATION_KEY, null);
- for (RangeMarker occurrenceMarker : occurrenceMarkers) {
- occurrenceMarker.dispose();
- }
- editor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY, null);
- exprMarker.dispose();
- }
- });
+ final VariableInplaceRenamer renamer =
+ new VariableInplaceIntroducer(project, expression, editor, elementToRename, cantChangeFinalModifier,
+ typeSelectorManager.getTypesForAll().length > 1, exprMarker, occurrenceMarkers);
+ renamer.performInplaceRename(false, new LinkedHashSet<String>(Arrays.asList(suggestedName.names)));
}
}
}
return true;
}
- private static void appendTypeCasts(List<RangeMarker> occurrenceMarkers,
- PsiFile file,
- Project project,
- PsiVariable psiVariable) {
- for (RangeMarker occurrenceMarker : occurrenceMarkers) {
- final PsiElement refVariableElement = file.findElementAt(occurrenceMarker.getStartOffset());
- final PsiReferenceExpression referenceExpression = PsiTreeUtil.getParentOfType(refVariableElement, PsiReferenceExpression.class);
- if (referenceExpression != null) {
- final PsiElement parent = referenceExpression.getParent();
- if (parent instanceof PsiVariable) {
- createCastInVariableDeclaration(project, (PsiVariable)parent);
- } else if (parent instanceof PsiReferenceExpression && psiVariable != null) {
- final PsiExpression initializer = psiVariable.getInitializer();
- LOG.assertTrue(initializer != null);
- final PsiType type = initializer.getType();
- if (((PsiReferenceExpression)parent).resolve() == null) {
- final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
- final PsiExpression castedExpr =
- elementFactory.createExpressionFromText("((" + type.getCanonicalText() + ")" + referenceExpression.getText() + ")", parent);
- JavaCodeStyleManager.getInstance(project).shortenClassReferences(referenceExpression.replace(castedExpr));
- }
- }
- }
- }
- if (psiVariable != null && psiVariable.isValid()) {
- createCastInVariableDeclaration(project, psiVariable);
- }
- }
-
- private static void createCastInVariableDeclaration(Project project, PsiVariable psiVariable) {
- final PsiExpression initializer = psiVariable.getInitializer();
- LOG.assertTrue(initializer != null);
- final PsiType type = psiVariable.getType();
- final PsiType initializerType = initializer.getType();
- if (initializerType != null && !TypeConversionUtil.isAssignable(type, initializerType)) {
- final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
- final PsiExpression castExpr =
- elementFactory.createExpressionFromText("(" +psiVariable.getType().getCanonicalText()+ ")" + initializer.getText(), psiVariable);
- JavaCodeStyleManager.getInstance(project).shortenClassReferences(initializer.replace(castExpr));
- }
- }
private static Runnable introduce(final Project project,
final PsiExpression expr,
};
}
- private static boolean createFinals(Project project) {
+ public static boolean createFinals(Project project) {
final Boolean createFinals = JavaRefactoringSettings.getInstance().INTRODUCE_LOCAL_CREATE_FINALS;
return createFinals == null ? CodeStyleSettingsManager.getSettings(project).GENERATE_FINAL_LOCALS : createFinals.booleanValue();
}
}
}
- private static class FinalExpression extends Expression {
- private final Project myProject;
-
- public FinalExpression(Project project) {
- myProject = project;
- }
-
- @Override
- public Result calculateResult(ExpressionContext context) {
- return new TextResult(createFinals(myProject) ? PsiKeyword.FINAL : "");
- }
-
- @Override
- public Result calculateQuickResult(ExpressionContext context) {
- return calculateResult(context);
- }
- @Override
- public LookupElement[] calculateLookupItems(ExpressionContext context) {
- LookupElement[] lookupElements = new LookupElement[2];
- lookupElements[0] = LookupElementBuilder.create("");
- lookupElements[1] = LookupElementBuilder.create(PsiModifier.FINAL + " ");
- return lookupElements;
- }
-
- public static void adjustLine(final PsiVariable psiVariable, final Document document) {
- final int modifierListOffset = psiVariable.getTextRange().getStartOffset();
- final int varLineNumber = document.getLineNumber(modifierListOffset);
- ApplicationManager.getApplication().runWriteAction(new Runnable() { //adjust line indent if final was inserted and then deleted
- public void run() {
- CodeStyleManager.getInstance(psiVariable.getProject()).adjustLineIndent(document, document.getLineStartOffset(varLineNumber));
- }
- });
- }
- }
}
*/
package com.intellij.refactoring.introduceVariable;
-import com.intellij.codeInsight.intention.impl.TypeExpression;
-import com.intellij.codeInsight.lookup.LookupElement;
-import com.intellij.codeInsight.template.Expression;
-import com.intellij.codeInsight.template.ExpressionContext;
-import com.intellij.codeInsight.template.TextResult;
import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
import com.intellij.codeInsight.template.impl.TemplateState;
import com.intellij.ide.ui.ListCellRendererWrapper;
-import com.intellij.openapi.actionSystem.Shortcut;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.VisualPosition;
-import com.intellij.openapi.keymap.Keymap;
-import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.Key;
import com.intellij.psi.*;
final PsiDeclarationStatement declaration = pointer != null ? pointer.getElement() : null;
final PsiType type = getVariableType(declaration);
if (type != null) {
- VariablesProcessor proc = findVariablesOfType(editor, declaration, type);
+ VariablesProcessor proc = findVariablesOfType(declaration, type);
if (proc.size() > 0) {
if (proc.size() == 1) {
return null;
}
- private static VariablesProcessor findVariablesOfType(Editor editor, final PsiDeclarationStatement declaration, final PsiType type) {
+ static VariablesProcessor findVariablesOfType(final PsiDeclarationStatement declaration, final PsiType type) {
VariablesProcessor proc = new VariablesProcessor(false) {
@Override
protected boolean check(PsiVariable var, ResolveState state) {
editor.putUserData(VariableInplaceRenamer.INPLACE_RENAMER, null);
}
}
-
- @Nullable
- static String getAdvertisementText(Editor editor, PsiDeclarationStatement declaration, PsiType type, PsiType[] typesForAll, boolean canAdjustFinal) {
- final VariablesProcessor processor = findVariablesOfType(editor, declaration, type);
- final Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
- if (processor.size() > 0) {
- final Shortcut[] shortcuts = keymap.getShortcuts("IntroduceVariable");
- if (shortcuts.length > 0) {
- return "Press " + shortcuts[0] + " to reassign existing variable";
- }
- }
- if (typesForAll.length > 1) {
- final Shortcut[] shortcuts = keymap.getShortcuts("PreviousTemplateVariable");
- if (shortcuts.length > 0) {
- return "Press " + shortcuts[0] + " to change type";
- }
- }
- return adjustFinalText(canAdjustFinal);
- }
-
- @Nullable
- private static String adjustFinalText(boolean canBeFinalAdjusted) {
- if (canBeFinalAdjusted) {
- final Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap().getShortcuts("PreviousTemplateVariable");
- if (shortcuts.length > 0) {
- return "Press " + shortcuts[0] + " to adjust final modifier";
- }
- }
- return null;
- }
-
- public static Expression createExpression(final TypeExpression expression, final String defaultType, final boolean canBeFinalAdjusted) {
- return new Expression() {
- @Override
- public com.intellij.codeInsight.template.Result calculateResult(ExpressionContext context) {
- return new TextResult(defaultType);
- }
-
- @Override
- public com.intellij.codeInsight.template.Result calculateQuickResult(ExpressionContext context) {
- return new TextResult(defaultType);
- }
-
- @Override
- public LookupElement[] calculateLookupItems(ExpressionContext context) {
- return expression.calculateLookupItems(context);
- }
-
- @Override
- public String getAdvertisingText() {
- return adjustFinalText(canBeFinalAdjusted);
- }
- };
- }
}
--- /dev/null
+/*
+ * Copyright 2000-2010 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.introduceVariable;
+
+import com.intellij.codeInsight.intention.impl.TypeExpression;
+import com.intellij.codeInsight.lookup.LookupElement;
+import com.intellij.codeInsight.lookup.LookupElementBuilder;
+import com.intellij.codeInsight.template.*;
+import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
+import com.intellij.codeInsight.template.impl.TemplateState;
+import com.intellij.openapi.actionSystem.Shortcut;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.RangeMarker;
+import com.intellij.openapi.extensions.Extensions;
+import com.intellij.openapi.keymap.Keymap;
+import com.intellij.openapi.keymap.KeymapManager;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Comparing;
+import com.intellij.psi.*;
+import com.intellij.psi.codeStyle.CodeStyleManager;
+import com.intellij.psi.codeStyle.JavaCodeStyleManager;
+import com.intellij.psi.scope.processor.VariablesProcessor;
+import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.psi.util.TypeConversionUtil;
+import com.intellij.refactoring.JavaRefactoringSettings;
+import com.intellij.refactoring.rename.NameSuggestionProvider;
+import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer;
+import com.intellij.refactoring.ui.TypeSelectorManagerImpl;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.Iterator;
+import java.util.LinkedHashSet;
+import java.util.List;
+
+/**
+ * User: anna
+ * Date: 12/8/10
+ */
+class VariableInplaceIntroducer extends VariableInplaceRenamer {
+ private final PsiVariable myElementToRename;
+ private final Editor myEditor;
+ private final TypeExpression myExpression;
+ private final boolean myCantChangeFinalModifier;
+ private final Project myProject;
+ private final SmartPsiElementPointer<PsiDeclarationStatement> myPointer;
+ private final RangeMarker myExprMarker;
+ private final List<RangeMarker> myOccurrenceMarkers;
+ private final PsiType myDefaultType;
+
+ public VariableInplaceIntroducer(final Project project,
+ final TypeExpression expression,
+ final Editor editor,
+ final PsiVariable elementToRename,
+ final boolean cantChangeFinalModifier,
+ final boolean hasTypeSuggestion,
+ final RangeMarker exprMarker,
+ final List<RangeMarker> occurrenceMarkers) {
+ super(elementToRename, editor);
+ myProject = project;
+ myEditor = editor;
+ myElementToRename = elementToRename;
+ myExpression = expression;
+ myCantChangeFinalModifier = cantChangeFinalModifier;
+
+ myExprMarker = exprMarker;
+ myOccurrenceMarkers = occurrenceMarkers;
+
+ myDefaultType = elementToRename.getType();
+
+ final PsiDeclarationStatement declarationStatement = PsiTreeUtil.getParentOfType(elementToRename, PsiDeclarationStatement.class);
+ myPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationStatement);
+ editor.putUserData(ReassignVariableUtil.DECLARATION_KEY, myPointer);
+ editor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY,
+ occurrenceMarkers.toArray(new RangeMarker[occurrenceMarkers.size()]));
+ setAdvertisementText(getAdvertisementText(declarationStatement, myDefaultType,
+ hasTypeSuggestion, !cantChangeFinalModifier));
+ }
+
+ @Override
+ protected void addAdditionalVariables(TemplateBuilderImpl builder) {
+ final PsiTypeElement typeElement = myElementToRename.getTypeElement();
+ builder.replaceElement(typeElement, "Variable_Type",
+ createExpression(myExpression, typeElement.getText(), !myCantChangeFinalModifier), true,
+ true);
+ if (!myCantChangeFinalModifier) {
+ builder.replaceElement(myElementToRename.getModifierList(), "_FINAL_", new FinalExpression(myProject), false, true);
+ }
+ }
+
+ @Override
+ protected LookupElement[] createLookupItems(LookupElement[] lookupItems, String name) {
+ TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor);
+ final PsiDeclarationStatement declarationStatement = myPointer.getElement();
+ final PsiVariable psiVariable =
+ declarationStatement != null ? (PsiVariable)declarationStatement.getDeclaredElements()[0] : null;
+ if (psiVariable != null) {
+ final TextResult insertedValue =
+ templateState != null ? templateState.getVariableValue(PRIMARY_VARIABLE_NAME) : null;
+ if (insertedValue != null) {
+ final String text = insertedValue.getText();
+ if (!text.isEmpty() && !Comparing.strEqual(text, name)) {
+ final LinkedHashSet<String> names = new LinkedHashSet<String>();
+ names.add(text);
+ for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) {
+ provider.getSuggestedNames(psiVariable, psiVariable, names);
+ }
+ final LookupElement[] items = new LookupElement[names.size()];
+ final Iterator<String> iterator = names.iterator();
+ for (int i = 0; i < items.length; i++) {
+ items[i] = LookupElementBuilder.create(iterator.next());
+ }
+ return items;
+ }
+ }
+ }
+ return super.createLookupItems(lookupItems, name);
+ }
+
+ @Override
+ protected void moveOffsetAfter(boolean success) {
+ if (success) {
+ final Document document = myEditor.getDocument();
+ final PsiDeclarationStatement declarationStatement = myPointer.getElement();
+ final PsiVariable psiVariable = declarationStatement != null ? (PsiVariable)declarationStatement.getDeclaredElements()[0] : null;
+ if (psiVariable != null) {
+ JavaRefactoringSettings.getInstance().INTRODUCE_LOCAL_CREATE_FINALS = psiVariable.hasModifierProperty(PsiModifier.FINAL);
+ FinalExpression.adjustLine(psiVariable, document);
+ }
+ int startOffset = myExprMarker.getStartOffset();
+ final PsiFile file = declarationStatement.getContainingFile();
+ final PsiReference referenceAt = file.findReferenceAt(startOffset);
+ if (referenceAt != null && referenceAt.resolve() instanceof PsiLocalVariable) {
+ startOffset = referenceAt.getElement().getTextRange().getEndOffset();
+ }
+ else if (declarationStatement != null) {
+ startOffset = declarationStatement.getTextRange().getEndOffset();
+ }
+ myEditor.getCaretModel().moveToOffset(startOffset);
+ final PsiType selectedType = ReassignVariableUtil.getVariableType(declarationStatement);
+ if (selectedType != null) {
+ TypeSelectorManagerImpl.typeSelected(selectedType, myDefaultType);
+ }
+ ApplicationManager.getApplication().runWriteAction(new Runnable() {
+ public void run() {
+ appendTypeCasts(myOccurrenceMarkers, file, myProject, psiVariable);
+ }
+ });
+ }
+ myEditor.putUserData(ReassignVariableUtil.DECLARATION_KEY, null);
+ for (RangeMarker occurrenceMarker : myOccurrenceMarkers) {
+ occurrenceMarker.dispose();
+ }
+ myEditor.putUserData(ReassignVariableUtil.OCCURRENCES_KEY, null);
+ myExprMarker.dispose();
+ }
+
+ private static void appendTypeCasts(List<RangeMarker> occurrenceMarkers,
+ PsiFile file,
+ Project project,
+ PsiVariable psiVariable) {
+ for (RangeMarker occurrenceMarker : occurrenceMarkers) {
+ final PsiElement refVariableElement = file.findElementAt(occurrenceMarker.getStartOffset());
+ final PsiReferenceExpression referenceExpression = PsiTreeUtil.getParentOfType(refVariableElement, PsiReferenceExpression.class);
+ if (referenceExpression != null) {
+ final PsiElement parent = referenceExpression.getParent();
+ if (parent instanceof PsiVariable) {
+ createCastInVariableDeclaration(project, (PsiVariable)parent);
+ }
+ else if (parent instanceof PsiReferenceExpression && psiVariable != null) {
+ final PsiExpression initializer = psiVariable.getInitializer();
+ LOG.assertTrue(initializer != null);
+ final PsiType type = initializer.getType();
+ if (((PsiReferenceExpression)parent).resolve() == null) {
+ final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
+ final PsiExpression castedExpr =
+ elementFactory.createExpressionFromText("((" + type.getCanonicalText() + ")" + referenceExpression.getText() + ")", parent);
+ JavaCodeStyleManager.getInstance(project).shortenClassReferences(referenceExpression.replace(castedExpr));
+ }
+ }
+ }
+ }
+ if (psiVariable != null && psiVariable.isValid()) {
+ createCastInVariableDeclaration(project, psiVariable);
+ }
+ }
+
+ private static void createCastInVariableDeclaration(Project project, PsiVariable psiVariable) {
+ final PsiExpression initializer = psiVariable.getInitializer();
+ LOG.assertTrue(initializer != null);
+ final PsiType type = psiVariable.getType();
+ final PsiType initializerType = initializer.getType();
+ if (initializerType != null && !TypeConversionUtil.isAssignable(type, initializerType)) {
+ final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
+ final PsiExpression castExpr =
+ elementFactory.createExpressionFromText("(" + psiVariable.getType().getCanonicalText() + ")" + initializer.getText(), psiVariable);
+ JavaCodeStyleManager.getInstance(project).shortenClassReferences(initializer.replace(castExpr));
+ }
+ }
+
+ @Nullable
+ private static String getAdvertisementText(final PsiDeclarationStatement declaration,
+ final PsiType type,
+ final boolean hasTypeSuggestion,
+ final boolean canAdjustFinal) {
+ final VariablesProcessor processor = ReassignVariableUtil.findVariablesOfType(declaration, type);
+ final Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
+ if (processor.size() > 0) {
+ final Shortcut[] shortcuts = keymap.getShortcuts("IntroduceVariable");
+ if (shortcuts.length > 0) {
+ return "Press " + shortcuts[0] + " to reassign existing variable";
+ }
+ }
+ if (hasTypeSuggestion) {
+ final Shortcut[] shortcuts = keymap.getShortcuts("PreviousTemplateVariable");
+ if (shortcuts.length > 0) {
+ return "Press " + shortcuts[0] + " to change type";
+ }
+ }
+ return adjustFinalText(canAdjustFinal);
+ }
+
+ @Nullable
+ private static String adjustFinalText(final boolean canBeFinalAdjusted) {
+ if (canBeFinalAdjusted) {
+ final Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap().getShortcuts("PreviousTemplateVariable");
+ if (shortcuts.length > 0) {
+ return "Press " + shortcuts[0] + " to adjust final modifier";
+ }
+ }
+ return null;
+ }
+
+ private static Expression createExpression(final TypeExpression expression, final String defaultType, final boolean canBeFinalAdjusted) {
+ return new Expression() {
+ @Override
+ public Result calculateResult(ExpressionContext context) {
+ return new TextResult(defaultType);
+ }
+
+ @Override
+ public Result calculateQuickResult(ExpressionContext context) {
+ return new TextResult(defaultType);
+ }
+
+ @Override
+ public LookupElement[] calculateLookupItems(ExpressionContext context) {
+ return expression.calculateLookupItems(context);
+ }
+
+ @Override
+ public String getAdvertisingText() {
+ return adjustFinalText(canBeFinalAdjusted);
+ }
+ };
+ }
+
+ private static class FinalExpression extends Expression {
+ private final Project myProject;
+
+ public FinalExpression(Project project) {
+ myProject = project;
+ }
+
+ @Override
+ public Result calculateResult(ExpressionContext context) {
+ return new TextResult(IntroduceVariableBase.createFinals(myProject) ? PsiKeyword.FINAL : "");
+ }
+
+ @Override
+ public Result calculateQuickResult(ExpressionContext context) {
+ return calculateResult(context);
+ }
+
+ @Override
+ public LookupElement[] calculateLookupItems(ExpressionContext context) {
+ LookupElement[] lookupElements = new LookupElement[2];
+ lookupElements[0] = LookupElementBuilder.create("");
+ lookupElements[1] = LookupElementBuilder.create(PsiModifier.FINAL + " ");
+ return lookupElements;
+ }
+
+ public static void adjustLine(final PsiVariable psiVariable, final Document document) {
+ final int modifierListOffset = psiVariable.getTextRange().getStartOffset();
+ final int varLineNumber = document.getLineNumber(modifierListOffset);
+ ApplicationManager.getApplication().runWriteAction(new Runnable() { //adjust line indent if final was inserted and then deleted
+
+ public void run() {
+ CodeStyleManager.getInstance(psiVariable.getProject()).adjustLineIndent(document, document.getLineStartOffset(varLineNumber));
+ }
+ });
+ }
+ }
+}
}
if (myCreateInnerClassRadioButton.isSelected()) {
final String innerClassName = getInnerClassName().trim();
- if (!nameHelper.isIdentifier(innerClassName)) throw new ConfigurationException("\'" + StringUtil.first(innerClassName, 10, true) + "\' is invalid inner class name");
- if (sourceMethod.getContainingClass().findInnerClassByName(innerClassName, false) != null) throw new ConfigurationException("Inner class with name \'" + StringUtil.first(innerClassName, 10, true) + "\' already exist");
+ if (!nameHelper.isIdentifier(innerClassName)) throw new ConfigurationException("\'" + innerClassName + "\' is invalid inner class name");
+ if (sourceMethod.getContainingClass().findInnerClassByName(innerClassName, false) != null) throw new ConfigurationException("Inner class with name \'" + innerClassName + "\' already exist");
} else if (!useExistingClass()) {
final String className = getClassName();
if (className.length() == 0 || !nameHelper.isIdentifier(className)) {
- throw new ConfigurationException("\'" + StringUtil.first(className, 10, true) + "\' is invalid parameter class name");
+ throw new ConfigurationException("\'" + className + "\' is invalid parameter class name");
}
final String packageName = getPackageName();
if (packageName.length() == 0 || !nameHelper.isQualifiedName(packageName)) {
- throw new ConfigurationException("\'" + StringUtil.last(packageName, 10, true) + "\' is invalid parameter class package name");
+ throw new ConfigurationException("\'" + packageName + "\' is invalid parameter class package name");
}
}
else {
final String className = getExistingClassName();
if (className.length() == 0 || !nameHelper.isQualifiedName(className)) {
- throw new ConfigurationException("\'" + StringUtil.first(className, 10, true) + "\' is invalid qualified parameter class name");
+ throw new ConfigurationException("\'" + className + "\' is invalid qualified parameter class name");
}
if (JavaPsiFacade.getInstance(getProject()).findClass(className, GlobalSearchScope.allScope(getProject())) == null) {
- throw new ConfigurationException("\'" + StringUtil.first(className, 10, true) + "\' does not exist");
+ throw new ConfigurationException("\'" + className + "\' does not exist");
}
}
}
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
-import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.search.ProjectScope;
if (isMoveToPackage()) {
String name = getTargetPackage().trim();
if (name.length() != 0 && !JavaPsiFacade.getInstance(myManager.getProject()).getNameHelper().isQualifiedName(name)) {
- throw new ConfigurationException("\'" + StringUtil.last(name, 10, true) + "\' is invalid destination package name");
+ throw new ConfigurationException("\'" + name + "\' is invalid destination package name");
}
}
else {
protected void canRun() throws ConfigurationException {
final PsiNameHelper nameHelper = JavaPsiFacade.getInstance(myProject).getNameHelper();
for (ParameterData parameterData : myParametersMap.values()) {
- if (!nameHelper.isIdentifier(parameterData.getFieldName())) throw new ConfigurationException("\'" + StringUtil.first(parameterData.getFieldName(), 10, true) + "\' is not a valid field name");
- if (!nameHelper.isIdentifier(parameterData.getSetterName())) throw new ConfigurationException("\'" + StringUtil.first(parameterData.getSetterName(), 10, true) + "\' is not a valid setter name");
+ if (!nameHelper.isIdentifier(parameterData.getFieldName())) throw new ConfigurationException("\'" + parameterData.getFieldName() + "\' is not a valid field name");
+ if (!nameHelper.isIdentifier(parameterData.getSetterName())) throw new ConfigurationException("\'" + parameterData.getSetterName() + "\' is not a valid setter name");
}
if (myCreateBuilderClassRadioButton.isSelected()) {
final String className = myNewClassName.getText().trim();
- if (className.length() == 0 || !nameHelper.isQualifiedName(className)) throw new ConfigurationException("\'" + StringUtil.first(className, 10, true) + "\' is invalid builder class name");
+ if (className.length() == 0 || !nameHelper.isQualifiedName(className)) throw new ConfigurationException("\'" + className + "\' is invalid builder class name");
final String packageName = myPackageTextField.getText().trim();
- if (packageName.length() > 0 && !nameHelper.isQualifiedName(packageName)) throw new ConfigurationException("\'" + StringUtil.last(packageName , 10, true)+ "\' is invalid builder package name");
+ if (packageName.length() > 0 && !nameHelper.isQualifiedName(packageName)) throw new ConfigurationException("\'" + packageName + "\' is invalid builder package name");
} else {
final String qualifiedName = myExistentClassTF.getText().trim();
- if (qualifiedName.length() == 0 || !nameHelper.isQualifiedName(qualifiedName)) throw new ConfigurationException("\'" + StringUtil.last(qualifiedName, 10, true) + "\' is invalid builder qualified class name");
+ if (qualifiedName.length() == 0 || !nameHelper.isQualifiedName(qualifiedName)) throw new ConfigurationException("\'" + qualifiedName + "\' is invalid builder qualified class name");
}
}
import com.intellij.openapi.help.HelpManager;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.refactoring.HelpID;
final String name = myNameField.getEnteredName();
final PsiNameHelper nameHelper = JavaPsiFacade.getInstance(myContainingClass.getProject()).getNameHelper();
if (!nameHelper.isIdentifier(name)) {
- throw new ConfigurationException("\'" + StringUtil.first(name, 10, true) + "\' is invalid factory method name");
+ throw new ConfigurationException("\'" + name + "\' is invalid factory method name");
}
}
}
import com.intellij.openapi.ui.LabeledComponent;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
-import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
@Override
protected void canRun() throws ConfigurationException {
- if (!checkType(getMigrationType())) throw new ConfigurationException("\'" + StringUtil.first(myTypeCodeFragment.getText(), 10, true) + "\' is invalid type");
+ if (!checkType(getMigrationType())) throw new ConfigurationException("\'" + myTypeCodeFragment.getText() + "\' is invalid type");
if (myScopeChooserCombo.getSelectedScope() == null) throw new ConfigurationException("Scope is not chosen");
}
}
public void typeSelected(@NotNull PsiType type) {
- StatisticsManager.getInstance().incUseCount(new StatisticsInfo(getStatsKey(), serialize(type)));
+ typeSelected(type, getDefaultType());
+ }
+
+ public static void typeSelected(final PsiType type, final PsiType defaultType) {
+ StatisticsManager.getInstance().incUseCount(new StatisticsInfo(getStatsKey(defaultType), serialize(type)));
}
private String getStatsKey() {
- return "IntroduceVariable##" + serialize(getDefaultType());
+ return getStatsKey(getDefaultType());
+ }
+
+ private static String getStatsKey(final PsiType defaultType) {
+ return "IntroduceVariable##" + serialize(defaultType);
}
- private String serialize(PsiType type) {
+ private static String serialize(PsiType type) {
if (PsiUtil.resolveClassInType(type) instanceof PsiTypeParameter) return type.getCanonicalText();
return TypeConversionUtil.erasure(type).getCanonicalText();
}
final PsiNameHelper nameHelper = manager.getNameHelper();
if (myCreateInnerClassButton.isSelected()) {
final String innerClassName = getInnerClassName().trim();
- if (!nameHelper.isIdentifier(innerClassName)) throw new ConfigurationException("\'" + StringUtil.first(innerClassName, 10, true) + "\' is invalid inner class name");
- if (sourceMethod.getContainingClass().findInnerClassByName(innerClassName, false) != null) throw new ConfigurationException("Inner class with name \'" + StringUtil.first(innerClassName, 10, true) + "\' already exist");
+ if (!nameHelper.isIdentifier(innerClassName)) throw new ConfigurationException("\'" + innerClassName + "\' is invalid inner class name");
+ if (sourceMethod.getContainingClass().findInnerClassByName(innerClassName, false) != null) throw new ConfigurationException("Inner class with name \'" + innerClassName + "\' already exist");
} else if (useExistingClassButton.isSelected()) {
final String className = existingClassField.getText().trim();
if (className.length() == 0 || !nameHelper.isQualifiedName(className)) {
- throw new ConfigurationException("\'" + StringUtil.last(className, 10, true) + "\' is invalid qualified wrapper class name");
+ throw new ConfigurationException("\'" + className + "\' is invalid qualified wrapper class name");
}
final Object item = myFieldsCombo.getSelectedItem();
if (item == null) {
} else {
final String className = getClassName();
if (className.length() == 0 || !nameHelper.isIdentifier(className)) {
- throw new ConfigurationException("\'" + StringUtil.first(className, 10, true) + "\' is invalid wrapper class name");
+ throw new ConfigurationException("\'" + className + "\' is invalid wrapper class name");
}
final String packageName = getPackageName();
if (packageName.length() == 0 || !nameHelper.isQualifiedName(packageName)) {
- throw new ConfigurationException("\'" + StringUtil.last(packageName, 10, true) + "\' is invalid wrapper class package name");
+ throw new ConfigurationException("\'" + packageName + "\' is invalid wrapper class package name");
}
}
}
package com.intellij.unscramble;
import com.intellij.openapi.application.ApplicationAdapter;
+import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.IdeFrame;
import java.util.regex.Pattern;
final String clipboard = AnalyzeStacktraceUtil.getTextInClipboard();
if (clipboard != null && clipboard.length() < MAX_STACKTRACE_SIZE && !clipboard.equals(stacktrace)) {
stacktrace = clipboard;
- if (isStacktrace(stacktrace)) {
- final UnscrambleDialog dialog = new UnscrambleDialog(ideFrame.getProject());
+ final Project project = ideFrame.getProject();
+ if (project != null && isStacktrace(stacktrace)) {
+ final UnscrambleDialog dialog = new UnscrambleDialog(project);
dialog.createNormalizeTextAction().actionPerformed(null);
dialog.doOKAction();
}
*/
package com.intellij.rt.execution.junit.segments;
+import java.util.Collection;
import java.util.Hashtable;
public abstract class OutputObjectRegistry {
private final Hashtable myKnownKeys = new Hashtable();
private int myLastIndex = 0;
private PacketProcessor myMainTransport;
- private PacketProcessor myAuxilaryTransport;
public OutputObjectRegistry(PacketProcessor transport) {
myMainTransport = transport;
}
- public OutputObjectRegistry(PacketProcessor mainTransport, PacketProcessor auxilaryTransport) {
- this(mainTransport);
- myAuxilaryTransport = auxilaryTransport;
- }
-
public String referenceTo(Object test) {
if (myKnownKeys.containsKey(test))
return (String) myKnownKeys.get(test);
return sendObject(test);
}
+ public String referenceTo(Object test, Collection packets) {
+ if (myKnownKeys.containsKey(test))
+ return (String) myKnownKeys.get(test);
+ return sendObject(test, packets);
+ }
+
+ private String sendObject(Object test, Collection packets) {
+ String key = String.valueOf(myLastIndex++);
+ myKnownKeys.put(test, key);
+ final Packet packet = createPacket();
+ packet.addString(PoolOfDelimiters.OBJECT_PREFIX).addReference(key);
+ addStringRepresentation(test, packet);
+ packet.addLong(getTestCont(test));
+ packet.addString(PoolOfDelimiters.REFERENCE_END_STR);
+ packets.add(packet);
+ return key;
+ }
+
public Packet createPacket() {
return new Packet(myMainTransport, this);
}
Packet packet = createPacket().addString(PoolOfDelimiters.OBJECT_PREFIX).addReference(key);
addStringRepresentation(test, packet);
packet.addLong(getTestCont(test));
- sendViaAllTransports(packet);
+ packet.send();
return key;
}
protected abstract int getTestCont(Object test);
protected abstract void addStringRepresentation(Object test, Packet packet);
- private void sendViaAllTransports(Packet packet) {
- packet.send();
- if (myAuxilaryTransport != null)
- packet.sendThrough(myAuxilaryTransport);
- }
-
-
-
protected static void addTestClass(Packet packet, String className) {
packet.
addLimitedString(PoolOfTestTypes.TEST_CLASS).
import junit.runner.BaseTestRunner;
import java.io.*;
+import java.util.Collection;
import java.util.Vector;
public class Packet extends PacketWriter {
return addReference(myRegistry.referenceTo(test));
}
+ public Packet addObject(Object test, Collection packet) {
+ return addReference(myRegistry.referenceTo(test, packet));
+ }
+
public Packet addReference(String reference) {
appendString(reference + PoolOfDelimiters.REFERENCE_END);
return this;
*/
public interface PoolOfDelimiters {
char REFERENCE_END = ':';
+ String REFERENCE_END_STR = ":";
char INTEGER_DELIMITER = ' ';
String OBJECT_PREFIX = "O";
--- /dev/null
+class Koo {}
+public class FooMap<K,V> implements YourMapInterface<K<caret>, V> {
+}
--- /dev/null
+class Koo{}
+public class FooMap<K,V extends K<caret>> {
+}
--- /dev/null
+public class FooMap<K,V extends K> implements YourMapInterface<K, V> {
+ void foo() {
+ class Zoooooooo {}
+ Zoo<caret>
+ }
+}
\ No newline at end of file
--- /dev/null
+public class FooMap<K,V extends K> implements YourMapInterface<K, V> {
+ void foo() {
+ class Zoooooooo {}
+ Zoooooooo<caret>
+ }
+}
\ No newline at end of file
--- /dev/null
+class Zooooo {}
+public class FooMap<K,V extends K> implements YourMapInterface<K, V> {
+ void foo() {
+ class Zoooz implements Runnable {}
+ Runnable r = new Zo<caret>
+ }
+}
\ No newline at end of file
--- /dev/null
+class Zoooz {}
+class Zooooo {}
+public class FooMap<K,V extends K> implements YourMapInterface<K, V> {
+ void foo() {
+ class Zoooz implements Runnable {}
+ Runnable r = new Zo<caret>
+ }
+}
\ No newline at end of file
--- /dev/null
+class A {
+ {
+ String c = new String(<caret>
+ }
+}
\ No newline at end of file
--- /dev/null
+class A {
+ {
+ String c = new Stri<caret>
+ }
+}
\ No newline at end of file
--- /dev/null
+class A {
+ {
+ String x;
+ Class c = x.getClass(<caret>
+ }
+}
\ No newline at end of file
--- /dev/null
+class A {
+ {
+ String x;
+ Class c = x.getCl<caret>
+ }
+}
\ No newline at end of file
--- /dev/null
+class A {
+ {
+ Class c = this.xxxxx(<caret>
+ }
+
+ Class xxxxx() {}
+}
\ No newline at end of file
--- /dev/null
+class A {
+ {
+ Class c = this.xx<caret>
+ }
+
+ Class xxxxx() {}
+}
\ No newline at end of file
}
class W<T> {}
-class P<L> {}
\ No newline at end of file
+class P<L> {}
+
+// IDEA-62529
+class Refx<T> {
+ Class<? super T> get() { return null; }
+ boolean f() {
+ if (get() == Enum.class) return false;
+ return (Class<Enum>)get() == Enum.class;
+ }
+}
}
public void testExcessSpaceInTypeCast() throws Throwable {
- configureByFile(getTestName(false) + ".java");
+ configure()
selectItem(myItems[0]);
checkResult()
}
doTest();
}
+ public void testLocalClassName() throws Throwable { doTest(); }
+
+ public void testClassTypeParameters() throws Throwable {
+ configure()
+ assert 'K' in myFixture.lookupElementStrings
+ }
+
+ public void testClassTypeParametersGenericBounds() throws Throwable {
+ configure()
+ assert 'K' in myFixture.lookupElementStrings
+ }
+
+ public void testLocalClassTwice() throws Throwable {
+ configure()
+ assertOrderedEquals myFixture.lookupElementStrings, 'Zoooz', 'Zooooo'
+ }
+
+ public void testLocalTopLevelConflict() throws Throwable {
+ configure()
+ assertOrderedEquals myFixture.lookupElementStrings, 'Zoooz', 'Zooooo'
+ }
+
public void testMethodParenthesesSpaces() throws Throwable {
final settings = CodeStyleSettingsManager.getSettings(getProject())
settings.SPACE_BEFORE_METHOD_CALL_PARENTHESES = true
public void testSameNamedFieldAndLocal() throws Throwable { doTest(); }
+ public void testNoTailWhenNoPairBracket() throws Throwable {
+ doTestNoPairBracket();
+ }
+
+ public void testNoTailWhenNoPairBracket2() throws Throwable {
+ doTestNoPairBracket();
+ }
+
+ private void doTestNoPairBracket() throws Exception {
+ boolean old = CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET;
+ CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET = false;
+ try {
+ doTest();
+ }
+ finally {
+ CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET = old;
+ }
+ }
+
+ public void testNoConstructorTailWhenNoPairBracket() throws Throwable {
+ doTestNoPairBracket();
+ }
+
public void testAbstractClassTwice() throws Throwable {
configureByTestName();
assertOneElement(myItems);
*/
@Nullable
String getType();
+
+ boolean isDeferred();
+
+ boolean isDynamic();
}
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.PostprocessReformattingAspect;
}
}));
- VirtualFileManager.getInstance().refresh(false);
+ toDir.refresh(false, true);
}
else {
editorInfos = new LinkedHashMap<VirtualFile, EditorInfo>();
@NonNls private final String myName; // for debug only
private final boolean myFirst;
private final boolean myLast;
- private final Set<String> myBefore = new HashSet<String>();
- private final Set<String> myAfter = new HashSet<String>();
+ private final Set<String> myBefore = new HashSet<String>(2);
+ private final Set<String> myAfter = new HashSet<String>(2);
private LoadingOrder() {
myName = "ANY";
}
public static void sort(final Orderable[] orderables) {
+ // our graph is pretty sparse so do benefit from the fact
final Map<String,Orderable> map = new HashMap<String, Orderable>();
- for (final Orderable orderable : orderables) {
- final String id = orderable.getOrderId();
- if (StringUtil.isNotEmpty(id)) {
- map.put(id, orderable);
- }
+ final HashMap<Orderable, LoadingOrder> cachedMap = new HashMap<Orderable, LoadingOrder>(orderables.length);
+ final HashSet<Orderable> first = new HashSet<Orderable>(1);
+ final HashSet<Orderable> hasBefore = new HashSet<Orderable>(orderables.length);
+
+ for(Orderable o:orderables) {
+ final String id = o.getOrderId();
+ if (StringUtil.isNotEmpty(id)) map.put(id, o);
+ LoadingOrder order = o.getOrder();
+ cachedMap.put(o, order);
+ if (order.myFirst) first.add(o);
+ if (order.myBefore.size() != 0) hasBefore.add(o);
}
DFSTBuilder<Orderable> builder = new DFSTBuilder<Orderable>(new GraphGenerator<Orderable>(new CachingSemiGraph<Orderable>(new GraphGenerator.SemiGraph<Orderable>() {
}
public Iterator<Orderable> getIn(final Orderable n) {
- final LoadingOrder order = n.getOrder();
+ final LoadingOrder order = cachedMap.get(n);
Set<Orderable> predecessors = new LinkedHashSet<Orderable>();
for (final String id : order.myAfter) {
}
String id = n.getOrderId();
- for (final Orderable orderable : orderables) {
- final LoadingOrder hisOrder = orderable.getOrder();
- if (StringUtil.isNotEmpty(id) && hisOrder.myBefore.contains(id) ||
- order.myLast && !hisOrder.myLast ||
- hisOrder.myFirst && !order.myFirst) {
+ if (StringUtil.isNotEmpty(id)) {
+ for (final Orderable orderable : hasBefore) {
+ final LoadingOrder hisOrder = cachedMap.get(orderable);
+ if (hisOrder.myBefore.contains(id)) {
+ predecessors.add(orderable);
+ }
+ }
+ }
+
+ if (order.myLast) {
+ for (final Orderable orderable : orderables) {
+ final LoadingOrder hisOrder = cachedMap.get(orderable);
+ if (!hisOrder.myLast) {
+ predecessors.add(orderable);
+ }
+ }
+ }
+
+ if (!order.myFirst) {
+ for(Orderable orderable:first) {
predecessors.add(orderable);
}
}
+
return predecessors.iterator();
}
})));
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileChooser.FileChooser;
import com.intellij.openapi.fileChooser.FileChooserDescriptor;
-import com.intellij.openapi.fileChooser.ex.FileChooserDialogImpl;
+import com.intellij.openapi.fileChooser.FileChooserDialog;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.fileTypes.FileTypes;
import com.intellij.openapi.project.Project;
myDisplayName = displayName;
myOrderRootType = orderRootType;
myDescriptor = descriptor;
- myDescriptor.putUserData(FileChooserDialogImpl.PREFER_LAST_OVER_TO_SELECT, Boolean.TRUE);
+ myDescriptor.putUserData(FileChooserDialog.PREFER_LAST_OVER_TO_SELECT, Boolean.TRUE);
myModel = createListModel();
}
* User: anna
* Date: 26-Dec-2007
*/
-package com.intellij.openapi.roots.ui.configuration;
+package com.intellij.openapi.roots.ui;
import com.intellij.openapi.projectRoots.Sdk;
import com.intellij.openapi.projectRoots.ui.PathEditor;
package com.intellij.psi.search;
import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiFileSystemItem;
import com.intellij.psi.PsiReference;
import com.intellij.util.Processor;
import com.intellij.util.containers.CollectionFactory;
}
public void searchWord(@NotNull String word, @NotNull SearchScope searchScope, boolean caseSensitive, @NotNull PsiElement searchTarget) {
- final short searchContext = UsageSearchContext.IN_CODE | UsageSearchContext.IN_FOREIGN_LANGUAGES | UsageSearchContext.IN_COMMENTS;
+ final short searchContext = (short)(UsageSearchContext.IN_CODE | UsageSearchContext.IN_FOREIGN_LANGUAGES | UsageSearchContext.IN_COMMENTS
+ | (searchTarget instanceof PsiFileSystemItem ? UsageSearchContext.IN_STRINGS : 0));
searchWord(word, searchScope, searchContext, caseSensitive, searchTarget);
}
import com.intellij.ide.util.PsiElementListCellRenderer;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.ui.popup.JBPopup;
import com.intellij.openapi.ui.popup.PopupChooserBuilder;
import com.intellij.psi.NavigatablePsiElement;
import com.intellij.psi.PsiElement;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.components.JBList;
+import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.event.MouseEvent;
}
public static void openTargets(MouseEvent e, NavigatablePsiElement[] targets, String title, ListCellRenderer listRenderer) {
- if (targets.length == 0) return;
- if (targets.length == 1){
+ JBPopup popup = navigateOrCreatePopup(targets, title, listRenderer);
+ if (popup != null) popup.show(new RelativePoint(e));
+ }
+
+ public static void openTargets(Editor e, NavigatablePsiElement[] targets, String title, ListCellRenderer listRenderer) {
+ JBPopup popup = navigateOrCreatePopup(targets, title, listRenderer);
+ if (popup != null) popup.showInBestPositionFor(e);
+ }
+
+ @Nullable
+ private static JBPopup navigateOrCreatePopup(NavigatablePsiElement[] targets, String title, ListCellRenderer listRenderer) {
+ if (targets.length == 0) return null;
+ if (targets.length == 1) {
targets[0].navigate(true);
+ return null;
}
- else{
- final JList list = new JBList(targets);
- list.setCellRenderer(listRenderer);
+ final JList list = new JBList(targets);
+ list.setCellRenderer(listRenderer);
- final PopupChooserBuilder builder = new PopupChooserBuilder(list);
- if (listRenderer instanceof PsiElementListCellRenderer) {
- ((PsiElementListCellRenderer)listRenderer).installSpeedSearch(builder);
- }
+ final PopupChooserBuilder builder = new PopupChooserBuilder(list);
+ if (listRenderer instanceof PsiElementListCellRenderer) {
+ ((PsiElementListCellRenderer)listRenderer).installSpeedSearch(builder);
+ }
- builder.
- setTitle(title).
- setMovable(true).
- setItemChoosenCallback(new Runnable() {
- public void run() {
- int[] ids = list.getSelectedIndices();
- if (ids == null || ids.length == 0) return;
- Object [] selectedElements = list.getSelectedValues();
- for (Object element : selectedElements) {
- PsiElement selected = (PsiElement) element;
- LOG.assertTrue(selected.isValid());
- ((NavigatablePsiElement)selected).navigate(true);
- }
+ return builder.
+ setTitle(title).
+ setMovable(true).
+ setItemChoosenCallback(new Runnable() {
+ public void run() {
+ int[] ids = list.getSelectedIndices();
+ if (ids == null || ids.length == 0) return;
+ Object[] selectedElements = list.getSelectedValues();
+ for (Object element : selectedElements) {
+ PsiElement selected = (PsiElement)element;
+ LOG.assertTrue(selected.isValid());
+ ((NavigatablePsiElement)selected).navigate(true);
}
- }).createPopup().
- show(new RelativePoint(e));
- }
+ }
+ }).createPopup();
}
}
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
+import com.intellij.psi.util.PsiUtilBase;
import org.jetbrains.annotations.Nullable;
import java.util.List;
Project project = PlatformDataKeys.PROJECT.getData(dataContext);
if (project == null) return false;
- PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
+ PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project);
if (file == null) return false;
nextAction.getTemplatePresentation().setText(getNextOccurenceActionName());
final AnAction switchSoftWrapsAction = new ToggleUseSoftWrapsToolbarAction(SoftWrapAppliancePlaces.CONSOLE) {
+
+ /**
+ * There is a possible case that more than console is open and user toggles soft wraps mode at one of them. We want
+ * to update another console(s) representation as well when they are switched on after that. Hence, we remember last
+ * used soft wraps mode and perform update if we see that the current value differs from the stored.
+ */
+ private boolean myLastIsSelected;
+
@Override
protected Editor getEditor(AnActionEvent e) {
return myEditor;
}
+ @Override
+ public boolean isSelected(AnActionEvent e) {
+ boolean result = super.isSelected(e);
+ if (result ^ myLastIsSelected) {
+ setSelected(null, result);
+ }
+ return myLastIsSelected = result;
+ }
+
@Override
public void setSelected(AnActionEvent e, final boolean state) {
super.setSelected(e, state);
import com.intellij.ide.IdeBundle;
import com.intellij.ide.favoritesTreeView.FavoritesManager;
import com.intellij.ide.favoritesTreeView.FavoritesTreeViewPanel;
-import com.intellij.openapi.actionSystem.AnAction;
-import com.intellij.openapi.actionSystem.AnActionEvent;
-import com.intellij.openapi.actionSystem.DataContext;
-import com.intellij.openapi.actionSystem.PlatformDataKeys;
+import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
public void update(AnActionEvent e) {
final DataContext dataContext = e.getDataContext();
- Project project = PlatformDataKeys.PROJECT.getData(dataContext);
+ final Project project = PlatformDataKeys.PROJECT.getData(dataContext);
+ final Presentation presentation = e.getPresentation();
if (project == null){
- e.getPresentation().setEnabled(false);
+ presentation.setEnabled(false);
return;
}
- String listName = FavoritesTreeViewPanel.FAVORITES_LIST_NAME_DATA_KEY.getData(dataContext);
- e.getPresentation().setEnabled(listName != null);
+ final String listName = FavoritesTreeViewPanel.FAVORITES_LIST_NAME_DATA_KEY.getData(dataContext);
+ presentation.setEnabled(false);
if (listName != null) {
- e.getPresentation().setText(IdeBundle.message("action.delete.all.favorites.lists.but.this",listName));
- e.getPresentation().setDescription(IdeBundle.message("action.delete.all.favorites.lists.but.this",listName));
+ final String[] favoritesLists = FavoritesManager.getInstance(project).getAvailableFavoritesLists();
+ if (listName.equals(project.getName())) {
+ presentation.setEnabled(favoritesLists.length > 1);
+ } else {
+ presentation.setEnabled(favoritesLists.length > 2);
+ }
+ presentation.setText(IdeBundle.message("action.delete.all.favorites.lists.but.this", listName));
+ presentation.setDescription(IdeBundle.message("action.delete.all.favorites.lists.but.this", listName));
}
}
}
import com.intellij.ide.scriptingContext.LangScriptingContextProvider;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
-import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.scripting.ScriptingLibraryManager;
import com.intellij.openapi.roots.libraries.scripting.ScriptingLibraryTable;
import com.intellij.ui.table.JBTable;
EditLibraryDialog editLibDialog = new EditLibraryDialog("New Library", myProvider, myProject);
editLibDialog.show();
if (editLibDialog.isOK()) {
- myLibTableModel.createLibrary(editLibDialog.getLibName(), editLibDialog.getSourceFiles(), editLibDialog.getCompactFiles());
+ myLibTableModel.createLibrary(editLibDialog.getLibName(), editLibDialog.getSourceFiles(), editLibDialog.getCompactFiles(), null);
}
}
EditLibraryDialog editLibDialog = new EditLibraryDialog("Edit Library", myProvider, myProject, lib);
editLibDialog.show();
if (editLibDialog.isOK()) {
- myLibTableModel.updateLibrary(libName, editLibDialog.getLibName(), editLibDialog.getSourceFiles(), editLibDialog.getCompactFiles());
+ myLibTableModel
+ .updateLibrary(libName, editLibDialog.getLibName(), editLibDialog.getSourceFiles(), editLibDialog.getCompactFiles(), null);
}
}
}
return "?";
}
- public void createLibrary(final String name, final VirtualFile[] sourceFiles, final VirtualFile[] compactFiles) {
+ public void createLibrary(final String name, final VirtualFile[] sourceFiles, final VirtualFile[] compactFiles, final String[] docUrls) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
- ScriptingLibraryTable.LibraryModel lib = myLibraryManager.createLibrary(name, sourceFiles, compactFiles);
+ ScriptingLibraryTable.LibraryModel lib = myLibraryManager.createLibrary(name, sourceFiles, compactFiles, docUrls);
if (lib != null) {
fireLibTableChanged();
}
}
}
- public void updateLibrary(final String oldName, final String name, final VirtualFile[] sourceFiles, final VirtualFile[] compactFiles) {
+ public void updateLibrary(final String oldName,
+ final String name,
+ final VirtualFile[] sourceFiles,
+ final VirtualFile[] compactFiles,
+ final String[] docUrls) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
- myLibraryManager.updateLibrary(oldName, name, sourceFiles, compactFiles);
+ myLibraryManager.updateLibrary(oldName, name, sourceFiles, compactFiles, docUrls);
fireLibTableChanged();
}
});
*/
public class GlobalPathReferenceProvider implements PathReferenceProvider {
- @NonNls private static final String MAILTO_PREFIX = "mailto:";
- @NonNls private static final String TEL_PREFIX = "tel:";
- @NonNls private static final String SMS_PREFIX = "sms:";
+ @NonNls private static final String[] PREFIXES = new String[] {
+ "mailto:", "tel:", "sms:", "skype:", "data:"
+ };
+
+ private static boolean startsWithAllowedPrefix(String s) {
+ for (String prefix : PREFIXES) {
+ if (s.startsWith(prefix)) {
+ return true;
+ }
+ }
+ return false;
+ }
public boolean createReferences(@NotNull PsiElement psiElement, final @NotNull List<PsiReference> references, final boolean soft) {
final ElementManipulator<PsiElement> manipulator = ElementManipulators.getManipulator(psiElement);
}
final TextRange range = manipulator.getRangeInElement(psiElement);
final String s = range.substring(psiElement.getText());
- if (s.contains("://") || s.startsWith(MAILTO_PREFIX) || s.startsWith(TEL_PREFIX) || s.startsWith(SMS_PREFIX) || s.startsWith("//")) {
+ if (s.contains("://") || s.startsWith("//") || startsWithAllowedPrefix(s)) {
final PsiReference reference = PsiReferenceBase.createSelfReference(psiElement, psiElement);
references.add(reference);
return true;
--- /dev/null
+/*
+ * Copyright 2000-2010 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.openapi.roots.libraries.doc;
+
+import com.intellij.openapi.roots.OrderRootType;
+import com.intellij.openapi.roots.PersistentOrderRootType;
+
+public class DocOrderRootType extends PersistentOrderRootType {
+
+ private DocOrderRootType() {
+ super("DOCUMENTATION", "docPath", "doc-paths", "docPathEntry");
+ }
+
+ public static OrderRootType getInstance() {
+ return getOrderRootType(DocOrderRootType.class);
+ }
+
+ public boolean collectFromDependentModules() {
+ return true;
+ }
+}
--- /dev/null
+/*
+ * Copyright 2000-2010 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.openapi.roots.libraries.doc;
+
+import com.intellij.openapi.project.ProjectBundle;
+import com.intellij.openapi.projectRoots.Sdk;
+import com.intellij.openapi.projectRoots.ui.PathEditor;
+import com.intellij.openapi.roots.ui.OrderRootTypeUIFactory;
+import com.intellij.openapi.util.IconLoader;
+import org.jetbrains.annotations.Nullable;
+
+import javax.swing.*;
+
+/**
+ * @author Rustam Vishnyakov
+ */
+public class DocOrderRootTypeUIFactory implements OrderRootTypeUIFactory {
+ private static final Icon ICON = IconLoader.getIcon("/nodes/javaDocFolder.png");
+
+ @Nullable
+ public PathEditor createPathEditor(Sdk sdk) {
+ return null;
+ }
+
+ @Override
+ public Icon getIcon() {
+ return ICON;
+ }
+
+ @Override
+ public String getNodeText() {
+ return ProjectBundle.message("library.docs.node");
+ }
+
+}
--- /dev/null
+/*
+ * Copyright 2000-2010 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.openapi.roots.libraries.doc;
+
+import com.intellij.openapi.project.ProjectBundle;
+import com.intellij.openapi.ui.InputValidator;
+import com.intellij.openapi.ui.Messages;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.openapi.vfs.VirtualFileManager;
+import org.jetbrains.annotations.Nullable;
+
+import javax.swing.*;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ * @author Rustam Vishnyakov
+ */
+public class DocUrlChooser {
+
+ private DocUrlChooser() {
+ }
+
+ @Nullable
+ public static VirtualFile showSpecifyDocUrlDialog(JComponent parent) {
+ return showSpecifyDocUrlDialog(parent, "");
+ }
+
+ @Nullable
+ public static VirtualFile showSpecifyDocUrlDialog(JComponent parent, String initialValue) {
+ final String url = Messages.showInputDialog(parent, ProjectBundle.message("sdk.configure.javadoc.url.prompt"),
+ ProjectBundle.message("sdk.configure.javadoc.url.title"), Messages.getQuestionIcon(),
+ initialValue, new InputValidator() {
+ public boolean checkInput(String inputString) {
+ return true;
+ }
+
+ public boolean canClose(String inputString) {
+ try {
+ new URL(inputString);
+ return true;
+ }
+ catch (MalformedURLException e1) {
+ Messages.showErrorDialog(e1.getMessage(), ProjectBundle.message("sdk.configure.javadoc.url.title"));
+ }
+ return false;
+ }
+ });
+ if (url == null) {
+ return null;
+ }
+ return VirtualFileManager.getInstance().findFileByUrl(url);
+ }
+}
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar;
import com.intellij.openapi.roots.libraries.LibraryType;
+//import com.intellij.openapi.roots.libraries.doc.DocOrderRootType;
import com.intellij.openapi.util.EmptyRunnable;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.Nullable;
LibraryTable libTable = getLibraryTable();
if (libTable != null) {
LibraryTable.ModifiableModel libTableModel = libTable.getModifiableModel();
- updateLibraries(libTableModel, OrderRootType.SOURCES);
- updateLibraries(libTableModel, OrderRootType.CLASSES);
+ updateLibraries(libTableModel);
libTableModel.commit();
}
myLibTable = null;
});
}
- private void updateLibraries(LibraryTable.ModifiableModel libTableModel, OrderRootType rootType) {
+ private void updateLibraries(LibraryTable.ModifiableModel libTableModel) {
+ //final OrderRootType docRootType = DocOrderRootType.getInstance();
for (Library library : libTableModel.getLibraries()) {
ScriptingLibraryTable.LibraryModel scriptingLibModel = myLibTable.getLibraryByName(library.getName());
if (scriptingLibModel == null) {
}
else {
Library.ModifiableModel libModel = library.getModifiableModel();
- for (VirtualFile libRoot : libModel.getFiles(rootType)) {
- libModel.removeRoot(libRoot.getUrl(), rootType);
- }
- for (VirtualFile newRoot : scriptingLibModel.getFiles(rootType)) {
- libModel.addRoot(newRoot, rootType);
+ removeRoots(libModel, OrderRootType.CLASSES);
+ removeRoots(libModel, OrderRootType.SOURCES);
+ /*
+ for (String docUrl : libModel.getUrls(DocOrderRootType.getInstance())) {
+ libModel.removeRoot(docUrl, docRootType);
}
+ */
+ addAllRoots(libModel, scriptingLibModel);
libModel.commit();
}
}
if (library == null && libTableModel instanceof LibraryTableBase.ModifiableModelEx) {
library = ((LibraryTableBase.ModifiableModelEx)libTableModel).createLibrary(scriptingLibModel.getName(), myLibraryType);
Library.ModifiableModel libModel = library.getModifiableModel();
- for (VirtualFile newRoot : scriptingLibModel.getFiles(rootType)) {
- libModel.addRoot(newRoot, rootType);
- }
+ addAllRoots(libModel, scriptingLibModel);
libModel.commit();
}
}
}
+
+ private static void removeRoots(Library.ModifiableModel libModel, OrderRootType rootType) {
+ for (VirtualFile libRoot : libModel.getFiles(rootType)) {
+ libModel.removeRoot(libRoot.getUrl(), rootType);
+ }
+ }
+
+ private static void addAllRoots(Library.ModifiableModel libModel, ScriptingLibraryTable.LibraryModel srcModel) {
+ //final OrderRootType docRootType = DocOrderRootType.getInstance();
+ addRoots(libModel, srcModel, OrderRootType.CLASSES);
+ addRoots(libModel, srcModel, OrderRootType.SOURCES);
+ /*
+ for (String docUrl : srcModel.getDocUrls()) {
+ libModel.addRoot(docUrl, docRootType);
+ }
+ */
+ }
+
+ private static void addRoots(Library.ModifiableModel libModel,
+ ScriptingLibraryTable.LibraryModel srcModel,
+ OrderRootType rootType) {
+ for (VirtualFile newRoot : srcModel.getFiles(rootType)) {
+ libModel.addRoot(newRoot, rootType);
+ }
+ }
public void reset() {
myLibTable = null;
}
@Nullable
- public ScriptingLibraryTable.LibraryModel createLibrary(String name, VirtualFile[] sourceFiles, VirtualFile[] compactFiles) {
+ public ScriptingLibraryTable.LibraryModel createLibrary(String name,
+ VirtualFile[] sourceFiles,
+ VirtualFile[] compactFiles,
+ String[] docUrls) {
if (ensureModel()) {
- return myLibTable.createLibrary(name, sourceFiles, compactFiles);
+ return myLibTable.createLibrary(name, sourceFiles, compactFiles, docUrls);
}
return null;
}
}
}
- public void updateLibrary(String oldName, String name, VirtualFile[] sourceFiles, VirtualFile[] compactFiles) {
+ public void updateLibrary(String oldName, String name, VirtualFile[] sourceFiles, VirtualFile[] compactFiles, String[] docUrls) {
if (ensureModel()) {
ScriptingLibraryTable.LibraryModel libModel = myLibTable.getLibraryByName(oldName);
if (libModel != null) {
libModel.setName(name);
libModel.setSourceFiles(sourceFiles);
libModel.setCompactFiles(compactFiles);
+ libModel.setDocUrls(docUrls);
myLibTable.invalidateCache();
}
}
assert myLibTable != null;
return myLibTable.isLibraryFile(file);
}
+
+ public String[] getDocUrlsFor(VirtualFile file) {
+ ensureModel();
+ assert myLibTable != null;
+ return myLibTable.getDocUrlsFor(file);
+ }
}
import com.intellij.openapi.roots.libraries.Library;
import com.intellij.openapi.roots.libraries.LibraryTable;
import com.intellij.openapi.roots.libraries.LibraryType;
+import com.intellij.openapi.roots.libraries.doc.DocOrderRootType;
import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.util.ArrayUtil;
import com.intellij.util.containers.HashSet;
import com.intellij.util.containers.hash.HashMap;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Set;
/**
* @author Rustam Vishnyakov
LibraryModel libModel = new LibraryModel(library.getName());
libModel.setSourceFiles(library.getFiles(SOURCE_ROOT_TYPE));
libModel.setCompactFiles(library.getFiles(COMPACT_ROOT_TYPE));
+ //libModel.setDocUrls(library.getUrls(DocOrderRootType.getInstance())); // TODO: Rustam, write tests first!
myLibraryModels.add(libModel);
}
}
return false;
}
+ public String[] getDocUrlsFor(VirtualFile file) {
+ Set<String> urls = new HashSet<String>();
+ for (LibraryModel libraryModel : myLibraryModels) {
+ if (libraryModel.containsFile(file)) {
+ urls.addAll(Arrays.asList(libraryModel.getDocUrls()));
+ }
+ }
+ return ArrayUtil.toStringArray(urls);
+ }
+
public boolean isCompactFile(VirtualFile file) {
if (myCompactFilesCache == null) {
myCompactFilesCache = new HashSet<VirtualFile>();
return libModel;
}
- public LibraryModel createLibrary(String libName, VirtualFile[] sourceFiles, VirtualFile[] compactFiles) {
- LibraryModel libModel = new LibraryModel(libName, sourceFiles, compactFiles);
+ public LibraryModel createLibrary(String libName, VirtualFile[] sourceFiles, VirtualFile[] compactFiles, String[] docUrls) {
+ LibraryModel libModel = new LibraryModel(libName, sourceFiles, compactFiles, docUrls);
myLibraryModels.add(libModel);
invalidateCache();
return libModel;
private String myName;
private ArrayList<VirtualFile> mySourceFiles = new ArrayList<VirtualFile>();
private ArrayList<VirtualFile> myCompactFiles = new ArrayList<VirtualFile>();
+ private ArrayList<String> myDocUrls = new ArrayList<String>();
- public LibraryModel(String name, VirtualFile[] sourceFiles, VirtualFile[] compactFiles) {
+ public LibraryModel(String name, VirtualFile[] sourceFiles, VirtualFile[] compactFiles, String[] docUrls) {
this(name);
mySourceFiles.addAll(Arrays.asList(sourceFiles));
myCompactFiles.addAll(Arrays.asList(compactFiles));
+ myDocUrls.addAll(Arrays.asList(docUrls));
}
public LibraryModel(String name) {
myCompactFiles.clear();
myCompactFiles.addAll(Arrays.asList(files));
}
+
+ public void setDocUrls(String[] docUrls) {
+ myDocUrls.clear();
+ myDocUrls.addAll(Arrays.asList(docUrls));
+ }
public VirtualFile[] getSourceFiles() {
return mySourceFiles.toArray(new VirtualFile[mySourceFiles.size()]);
public VirtualFile[] getCompactFiles() {
return myCompactFiles.toArray(new VirtualFile[myCompactFiles.size()]);
}
+
+ public String[] getDocUrls() {
+ return ArrayUtil.toStringArray(myDocUrls);
+ }
@NotNull
public VirtualFile[] getFiles(OrderRootType rootType) {
final IElementType contentElementType = getContentElementType();
if (!(contentElementType instanceof IStubFileElementType)) {
throw new AssertionError("A stub in a non-stub file '" + vFile +"'; isValid()=" + vFile.isValid() +
- " type: "+contentElementType+"; content:<<<\n"+
+ " type: "+contentElementType+";" +
+ " StubUpdatingIndex.canHaveStub(vFile)=" + StubUpdatingIndex.canHaveStub(vFile) +
+ " content:<<<\n"+
StringUtil.first(getViewProvider().getContents(),200,true)+
"\n>>>; stubs=" + stubHolder.getPlainList());
}
public FileReferenceSet(final @NotNull PsiElement element) {
myElement = element;
- final ElementManipulator<PsiElement> manipulator = ElementManipulators.getManipulator(element);
- final TextRange range = manipulator.getRangeInElement(element);
+ TextRange range = ElementManipulators.getValueTextRange(element);
myStartInElement = range.getStartOffset();
final String s = range.substring(element.getText());
myPathString = s.trim();
}
public static int toBuffer(ASTNode element, char[] buffer, int offset, TokenSet skipTypes) {
- if (element instanceof ForeignLeafPsiElement || skipTypes != null && skipTypes.contains(element.getElementType())) return offset;
+ if (element instanceof ForeignLeafPsiElement ||
+ skipTypes != null && skipTypes.contains(element.getElementType())) {
+ return offset;
+ }
+
if (element instanceof LeafElement) {
return ((LeafElement)element).copyTo(buffer, offset);
}
@NotNull
public char[] textToCharArray() {
char[] buffer = new char[getTextLength()];
- AstBufferUtil.toBuffer(this, buffer, 0);
+ walkCopyingText(buffer);
return buffer;
}
if (myCachedLength != NOT_CACHED) {
throw new AssertionError("Before walking: cached="+myCachedLength);
}
- TreeElement cur = this;
+ TreeElement cur = this;
while (cur != null) {
- cur = next(cur, cur.getCachedLength() == NOT_CACHED);
+ cur = next(cur, cur.getCachedLength() == NOT_CACHED, true);
}
if (myCachedLength < 0) {
}
}
+ private void walkCopyingText(char[] buffer) {
+ if (TreeUtil.isCollapsedChameleon(this)) {
+ AstBufferUtil.toBuffer(this, buffer, 0);
+ return;
+ }
+
+ int offset = 0;
+ TreeElement cur = this;
+ while ((cur = next(cur, cur instanceof CompositeElement && !TreeUtil.isCollapsedChameleon(cur), false)) != null) {
+ if (cur instanceof LeafElement || TreeUtil.isCollapsedChameleon(cur)) {
+ offset = AstBufferUtil.toBuffer(cur, buffer, offset);
+ }
+ }
+ }
+
@Nullable
- private TreeElement next(TreeElement cur, boolean down) {
+ private TreeElement next(TreeElement cur, boolean down, boolean update) {
if (down) {
CompositeElement composite = (CompositeElement)cur; // It's a composite or we won't be going down
TreeElement child = composite.firstChild;
return child;
}
- composite.myCachedLength = 0;
+ if (update) {
+ composite.myCachedLength = 0;
+ }
}
// up
while (cur != this) {
CompositeElement parent = cur.getTreeParent();
int curLength = cur.getCachedLength();
- LOG.assertTrue(curLength != NOT_CACHED, cur);
- parent.myCachedLength -= curLength;
+ if (update) {
+ LOG.assertTrue(curLength != NOT_CACHED, cur);
+ parent.myCachedLength -= curLength;
+ }
TreeElement next = cur.getTreeNext();
if (next != null) {
}
LOG.assertTrue(parent.lastChild == cur, parent);
- parent.myCachedLength = -parent.myCachedLength + NOT_CACHED;
+ if (update) {
+ parent.myCachedLength = -parent.myCachedLength + NOT_CACHED;
+ }
cur = parent;
}
return null;
}
-
public TreeElement getFirstChildNode() {
return firstChild;
}
if (parsedNode != null) {
rawAddChildren((TreeElement)parsedNode);
- /*
- if (getTextLength() != text.length()) {
- if (ApplicationManagerEx.getApplicationEx().isInternal() && !ApplicationManager.getApplication().isUnitTestMode()) {
- LOG.error("Inconsistent reparse: type=" + getElementType() + "; text=" + text + "; treeText=" + getText());
- } else {
- LOG.error("Inconsistent reparse: type=" + getElementType());
- }
- }
- */
+ //if (getNotCachedLength() != text.length()) {
+ // if (ApplicationManagerEx.getApplicationEx().isInternal()) {
+ // LOG.error("Inconsistent reparse: type=" + getElementType() + "; text=" + text + "; treeText=" + getText());
+ // } else {
+ // LOG.error("Inconsistent reparse: type=" + getElementType());
+ // }
+ //}
//ensure PSI is created all at once, to reduce contention of PsiLock in CompositeElement.getPsi()
((TreeElement)parsedNode).acceptTree(CREATE_PSI);
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.ex.EditorEx;
import com.intellij.openapi.editor.markup.TextAttributes;
-import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
private Editor myCallerEditor;
private Editor myCalleeEditor;
private boolean myInitDone;
+ private final String myFileName;
protected abstract MethodNodeBase<M> createTreeNode(M method, HashSet<M> called, Runnable cancelCallback);
protected abstract M[] findDeepestSuperMethods(M method);
- public CallerChooserBase(M method, Project project, String title, Tree previousTree, Consumer<Set<M>> callback) {
+ public CallerChooserBase(M method, Project project, String title, Tree previousTree, String fileName, Consumer<Set<M>> callback) {
super(true);
myMethod = method;
myProject = project;
myTree = previousTree;
+ myFileName = fileName;
myCallback = callback;
setTitle(title);
init();
final EditorFactory editorFactory = EditorFactory.getInstance();
final Document document = editorFactory.createDocument("");
final Editor editor = editorFactory.createViewer(document, myProject);
- ((EditorEx)editor).setHighlighter(HighlighterFactory.createHighlighter(myProject, StdFileTypes.JAVA));
+ ((EditorEx)editor).setHighlighter(HighlighterFactory.createHighlighter(myProject, myFileName));
return editor;
}
@Override
protected void canRun() throws ConfigurationException {
if (!areButtonsValid()) {
- throw new ConfigurationException("\'" + StringUtil.first(getNewName(), 10, true) + "\' is invalid identifier");
+ throw new ConfigurationException("\'" + getNewName() + "\' is invalid identifier");
}
}
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.refactoring.util.TextOccurrencesUtil;
import com.intellij.usageView.UsageInfo;
-import com.intellij.util.Consumer;
import com.intellij.util.PairProcessor;
import com.intellij.util.containers.MultiMap;
import com.intellij.util.containers.Stack;
*/
public class VariableInplaceRenamer {
public static final Key<VariableInplaceRenamer> INPLACE_RENAMER = Key.create("EditorInplaceRenamer");
- private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.inplace.VariableInplaceRenamer");
+ protected static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.inplace.VariableInplaceRenamer");
public static final LanguageExtension<ResolveSnapshotProvider> INSTANCE = new LanguageExtension<ResolveSnapshotProvider>(
"com.intellij.rename.inplace.resolveSnapshotProvider"
);
private final PsiNamedElement myElementToRename;
- @NonNls private static final String PRIMARY_VARIABLE_NAME = "PrimaryVariable";
+ @NonNls protected static final String PRIMARY_VARIABLE_NAME = "PrimaryVariable";
@NonNls private static final String OTHER_VARIABLE_NAME = "OtherVariable";
private ArrayList<RangeHighlighter> myHighlighters;
private final Editor myEditor;
}
public boolean performInplaceRename() {
- return performInplaceRename(true, null, null);
+ return performInplaceRename(true, null);
}
- public boolean performInplaceRename(boolean processTextOccurrences, LinkedHashSet<String> nameSuggestions, final Consumer<Boolean> moveOffsetAfterr) {
+ public boolean performInplaceRename(boolean processTextOccurrences, LinkedHashSet<String> nameSuggestions) {
if (InjectedLanguageUtil.isInInjectedLanguagePrefixSuffix(myElementToRename)) {
return false;
}
if (myNewName != null) {
performAutomaticRename(myNewName, PsiTreeUtil.getParentOfType(containingFile.findElementAt(renameOffset), PsiNameIdentifierOwner.class));
}
- if (moveOffsetAfterr != null) {
- moveOffsetAfterr.consume(true);
- }
+ moveOffsetAfter(true);
}
public void templateCancelled(Template template) {
finish();
- if (moveOffsetAfterr != null) {
- moveOffsetAfterr.consume(false);
- }
+ moveOffsetAfter(false);
}
});
return true;
}
+ protected void moveOffsetAfter(boolean success) {
+ }
+
protected void addAdditionalVariables(TemplateBuilderImpl builder) {
}
}
}
+ protected LookupElement[] createLookupItems(final LookupElement[] lookupItems, final String name) {
+ return lookupItems;
+ }
+
private class MyExpression extends Expression {
private final String myName;
private final LookupElement[] myLookupItems;
}
public LookupElement[] calculateLookupItems(ExpressionContext context) {
- return myLookupItems;
+ return createLookupItems(myLookupItems, myName);
}
public Result calculateQuickResult(ExpressionContext context) {
printWriter.close();
}
}
+ ourDisabledPlugins = null;
}
public static List<String> getDisabledPlugins() {
package com.intellij.openapi.actionSystem.ex;
import com.intellij.ide.DataManager;
-import com.intellij.openapi.actionSystem.AnAction;
-import com.intellij.openapi.actionSystem.AnActionEvent;
-import com.intellij.openapi.actionSystem.DefaultActionGroup;
-import com.intellij.openapi.actionSystem.Presentation;
+import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.ui.popup.ListPopup;
import com.intellij.openapi.util.IconLoader;
public abstract class ComboBoxAction extends AnAction implements CustomComponentAction {
private static final Icon ARROW_ICON = IconLoader.getIcon("/general/comboArrow.png");
private static final Icon DISABLED_ARROW_ICON = IconLoader.getDisabledIcon(ARROW_ICON);
+ private DataContext myDataContext;
protected ComboBoxAction() {
}
return panel;
}
+ @Override
+ public void update(AnActionEvent e) {
+ super.update(e);
+ myDataContext = e.getDataContext();
+ }
+
@NotNull
protected abstract DefaultActionGroup createPopupActionGroup(JComponent button);
protected ListPopup createPopup(Runnable onDispose) {
DefaultActionGroup group = createPopupActionGroup(this);
- final ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup(null, group, DataManager.getInstance().getDataContext(),
+
+ DataContext context = myDataContext == null ? DataManager.getInstance().getDataContext() : myDataContext;
+ myDataContext = null;
+ final ListPopup popup = JBPopupFactory.getInstance().createActionGroupPopup(null, group, context,
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false,
onDispose,
getMaxRows());
*/
package com.intellij.openapi.fileChooser;
+import com.intellij.openapi.actionSystem.DataKey;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public interface FileChooserDialog {
+ DataKey<Boolean> PREFER_LAST_OVER_TO_SELECT = DataKey.create("PREFER_LAST_OVER_TO_SELECT");
+
@NotNull
VirtualFile[] choose(@Nullable VirtualFile toSelect, @Nullable Project project);
}
\ No newline at end of file
*/
package com.intellij.ui;
-import com.intellij.openapi.wm.impl.content.GraphicsConfig;
import com.intellij.util.ui.UIUtil;
import javax.swing.*;
g.drawLine(0, lineY, lineX, lineY);
g.drawLine(lineX + fontWidth, lineY, getWidth() - 1, lineY);
- final GraphicsConfig config = new GraphicsConfig(g);
- config.setAntialiasing(true);
-
+ UIUtil.applyRenderingHints(g);
g.setColor(GroupedElementsRenderer.POPUP_SEPARATOR_TEXT_FOREGROUND);
g.drawString(myCaption, lineX + HGAP, baseline);
-
- config.restore();
}
else {
g.drawLine(0, VGAP, getWidth() - 1, VGAP);
final HintInfo info = myHintsStack.get(i);
if (!info.hint.isVisible()) {
myHintsStack.remove(i);
+
+ // We encountered situation when 'hint' instances use 'hide()' method as object destruction callback
+ // (e.g. LineTooltipRenderer creates hint that overrides keystroke of particular action that produces hint and
+ // de-registers it inside 'hide()'. That means that the hint can 'stuck' to old editor location if we just remove
+ // it but don't call hide())
+ info.hint.hide();
continue;
}
final HintInfo info = myHintsStack.get(i);
if (!info.hint.isVisible()) {
myHintsStack.remove(i);
+
+ // We encountered situation when 'hint' instances use 'hide()' method as object destruction callback
+ // (e.g. LineTooltipRenderer creates hint that overrides keystroke of particular action that produces hint and
+ // de-registers it inside 'hide()'. That means that the hint can 'stuck' to old editor location if we just remove
+ // it but don't call hide())
+ info.hint.hide();
continue;
}
import com.intellij.openapi.application.ApplicationInfo;
import com.intellij.openapi.application.ApplicationNamesInfo;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
+import com.intellij.openapi.application.impl.ApplicationInfoImpl;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.util.IconLoader;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFocusManager;
import com.intellij.openapi.wm.WindowManager;
-import com.intellij.openapi.wm.impl.content.GraphicsConfig;
import com.intellij.ui.LicenseeInfoProvider;
import com.intellij.util.ImageLoader;
import com.intellij.util.ui.UIUtil;
final long showTime = System.currentTimeMillis();
//final long delta = Patches.APPLE_BUG_ID_3716865 ? 100 : 0;
- final long delta = 100; //reproducible on Windows too
+ final long delta = 500; //reproducible on Windows too
dialog.addWindowFocusListener(new WindowFocusListener() {
public void windowGainedFocus(WindowEvent e) {
setOpaque(false);
//col = new Color(0xfa, 0xfa, 0xfa, 200);
col = Color.white;
- linkCol = Color.blue;
+ linkCol = ApplicationInfoImpl.getInstanceEx().getLogoTextColor();
setBackground(col);
ApplicationInfoEx ideInfo = (ApplicationInfoEx)ApplicationInfo.getInstance();
Calendar cal = ideInfo.getBuildDate();
protected void paintChildren(Graphics g) {
super.paintChildren(g);
Graphics2D g2 = (Graphics2D)g;
- GraphicsConfig config = new GraphicsConfig(g2);
- config.setAntialiasing(true);
+ UIUtil.applyRenderingHints(g);
Font labelFont = UIUtil.getLabelFont();
for (int labelSize = 10; labelSize != 6; labelSize -= 1) {
catch (TextRenderer.OverflowException ignore) {
}
}
-
- config.restore();
}
public class TextRenderer {
if (currentEvent == null) return currentEvent;
- currentEvent.updateAction(getDnDActionForPlatformAction(nativeAction));
+ final DnDAction dndAction = getDnDActionForPlatformAction(nativeAction);
+ if (dndAction == null) return null;
+
+ currentEvent.updateAction(dndAction);
currentEvent.setPoint(aPoint);
currentEvent.setHandlerComponent(aComponentOverDragging);
}
public void update(AnActionEvent e) {
+ super.update(e);
Presentation presentation = e.getPresentation();
DiffPanelEx diffPanel = DiffPanelImpl.fromDataContext(e.getDataContext());
if (diffPanel != null && diffPanel.getComponent().isDisplayable()) {
private Color myBackgroundColor = null;
private GutterDraggableObject myGutterDraggableObject;
private String myLastGutterToolTip = null;
-
+ private int myLastPreferredHeight = -1;
public EditorGutterComponentImpl(EditorImpl editor) {
myEditor = editor;
public Dimension getPreferredSize() {
int w = getLineNumberAreaWidth() + getLineMarkerAreaWidth() + getFoldingAreaWidth() + getAnnotationsAreaWidth();
- return new Dimension(w, myEditor.getPreferredHeight());
+ myLastPreferredHeight = myEditor.getPreferredHeight();
+ return new Dimension(w, myLastPreferredHeight);
}
protected void setUI(ComponentUI newUI) {
int oldAnnotationsWidth = myTextAnnotationGuttersSize;
calcIconAreaWidth();
calcAnnotationsSize();
- if (oldIconsWidth != myLineMarkerAreaWidth || oldAnnotationsWidth != myTextAnnotationGuttersSize) {
+ if (oldIconsWidth != myLineMarkerAreaWidth || oldAnnotationsWidth != myTextAnnotationGuttersSize
+ || myLastPreferredHeight != myEditor.getPreferredHeight())
+ {
fireResized();
}
repaint();
// optimization: do not do column calculations here since we are interested in line number only
public int offsetToVisualLine(int offset) {
+ int textLength = getDocument().getTextLength();
+ if (offset >= textLength) {
+ int result = getVisibleLineCount();
+ if (textLength > 0 && getDocument().getCharsSequence().charAt(textLength - 1) == '\n') {
+ result++;
+ }
+ return result;
+ }
int line = calcLogicalLineNumber(offset);
int lineStartOffset = myDocument.getLineStartOffset(line);
int result = logicalToVisualLine(line);
getFoldingModel().runBatchFoldingOperation(processor);
y = myGutterComponent.getHeadCenterY(range);
getScrollingModel().scrollVertically(y - scrollShift);
+ myGutterComponent.updateSize();
return;
}
}
private static final Logger LOG = Logger.getInstance("#" + SoftWrapModelImpl.class.getName());
- /** Upper boundary of time interval to check editor settings. */
- private static final long EDITOR_SETTINGS_CHECK_PERIOD_MILLIS = 10000;
-
private final OffsetToLogicalTask myOffsetToLogicalTask = new OffsetToLogicalTask();
private final VisualToLogicalTask myVisualToLogicalTask = new VisualToLogicalTask();
private final LogicalToVisualTask myLogicalToVisualTask = new LogicalToVisualTask();
private final EditorEx myEditor;
/** Holds number of 'active' calls, i.e. number of methods calls of the current object within the current call stack. */
private int myActive;
- /** Holds timestamp of the last editor settings check. */
- private long myLastSettingsCheckTimeMillis;
- private Boolean myLastUseSoftWraps;
+ private boolean myUseSoftWraps;
public SoftWrapModelImpl(@NotNull EditorEx editor) {
this(editor, new SoftWrapsStorage(), new CompositeSoftWrapPainter(editor));
myDocumentListeners.add(myApplianceManager);
myFoldListeners.add(myApplianceManager);
applianceManager.addListener(myVisualSizeManager);
+ myUseSoftWraps = myEditor.getSettings().isUseSoftWraps();
}
/**
* Called on editor settings change. Current model is expected to drop all cached information about the settings if any.
*/
public void reinitSettings() {
- myLastUseSoftWraps = null;
+ boolean softWrapsUsedBefore = myUseSoftWraps;
+ myUseSoftWraps = myEditor.getSettings().isUseSoftWraps();
+ if (myUseSoftWraps && !softWrapsUsedBefore) {
+ myApplianceManager.reset();
+ }
}
public boolean isSoftWrappingEnabled() {
return false;
}
- // Profiling shows that editor settings lookup have impact at overall performance if called often.
- // Hence, we cache value used last time.
- if (myLastUseSoftWraps != null && System.currentTimeMillis() - myLastSettingsCheckTimeMillis <= EDITOR_SETTINGS_CHECK_PERIOD_MILLIS) {
- return myLastUseSoftWraps == Boolean.TRUE;
- }
- myLastSettingsCheckTimeMillis = System.currentTimeMillis();
- return myLastUseSoftWraps = myEditor.getSettings().isUseSoftWraps();
+ return myUseSoftWraps;
}
@Nullable
myStorage.removeAll();
}
- public void refreshSettings() {
- myLastSettingsCheckTimeMillis = 0;
- }
-
public SoftWrapApplianceManager getApplianceManager() {
return myApplianceManager;
}
task, myDataMapper, myEditor.getDocument().getText(), Arrays.toString(myEditor.getFoldingModel().fetchTopLevel())), e);
}
myDataMapper.release();
- myApplianceManager.release();
+ myApplianceManager.reset();
+ myStorage.removeAll();
try {
task.run(true);
}
}
@Nullable
- protected FoldingData getFoldRegionData(FoldRegion foldRegion) {
+ protected FoldingData getFoldRegionData(@NotNull FoldRegion foldRegion) {
int i = MappingUtil.getCacheEntryIndexForOffset(foldRegion.getStartOffset(), myEditor.getDocument(), myCache);
if (i < 0 || i >= myCache.size()) {
return null;
}
CacheEntry cacheEntry = myCache.get(i);
- return cacheEntry.getFoldingData().get(foldRegion.getStartOffset());
+ return cacheEntry.getFoldingData(foldRegion);
}
@Override
protected abstract T buildIfExceeds(EditorPosition position, int offset);
@Override
- public T processFoldRegion(EditorPosition position, FoldRegion foldRegion) {
+ public T processFoldRegion(EditorPosition position, @NotNull FoldRegion foldRegion) {
T result = buildIfExceeds(position, foldRegion);
if (result != null) {
return result;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.FoldRegion;
import com.intellij.openapi.editor.impl.EditorTextRepresentationHelper;
+import com.intellij.openapi.util.Ref;
import gnu.trove.TIntObjectHashMap;
import gnu.trove.TIntObjectProcedure;
+import gnu.trove.TObjectProcedure;
import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
return result;
}
- public TIntObjectHashMap<FoldingData> getFoldingData() {
- return myFoldingData;
+ @Nullable
+ public FoldingData getFoldingData(@NotNull final FoldRegion region) {
+ FoldingData candidate = myFoldingData.get(region.getStartOffset());
+ if (candidate != null) {
+ return candidate;
+ }
+
+ // Folding implementation is known to postpone actual fold region offsets update on document change, i.e. it performs
+ // fold data caching with its further replace by up-to-date info. Hence, there is a possible case that soft wraps processing
+ // advances fold region offset but folding model still provides old cached values. Hence, we're trying to match exact given
+ // fold region against the cached data here.
+ final Ref<FoldingData> result = new Ref<FoldingData>();
+ myFoldingData.forEachValue(new TObjectProcedure<FoldingData>() {
+ @Override
+ public boolean execute(FoldingData data) {
+ if (data.getFoldRegion().equals(region)) {
+ result.set(data);
+ return false;
+ }
+ return true;
+ }
+ });
+ return result.get();
}
public void store(FoldRegion foldRegion, int startX) {
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.FoldRegion;
import com.intellij.openapi.editor.impl.EditorTextRepresentationHelper;
+import org.jetbrains.annotations.NotNull;
/**
* Caches information about number of logical columns inside the collapsed single line folding.
private final EditorTextRepresentationHelper myRepresentationHelper;
private final FoldRegion myFoldRegion;
- FoldingData(FoldRegion foldRegion, int startX, EditorTextRepresentationHelper representationHelper, Editor editor) {
+ FoldingData(@NotNull FoldRegion foldRegion, int startX, @NotNull EditorTextRepresentationHelper representationHelper,
+ @NotNull Editor editor)
+ {
myFoldRegion = foldRegion;
this.startX = startX;
myRepresentationHelper = representationHelper;
return widthInColumns;
}
+
+ @NotNull
+ public FoldRegion getFoldRegion() {
+ return myFoldRegion;
+ }
}
* <code>null</code> otherwise
*/
@Nullable
- T processFoldRegion(EditorPosition position, FoldRegion foldRegion);
+ T processFoldRegion(EditorPosition position, @NotNull FoldRegion foldRegion);
/**
* Notifies current strategy that tabulation symbols is encountered during the processing. Tabulation symbols
private boolean myCustomIndentUsedLastTime;
private int myCustomIndentValueUsedLastTime;
private int myVisibleAreaWidth;
- private long myLastDocumentStamp;
private boolean myInProgress;
public SoftWrapApplianceManager(@NotNull SoftWrapsStorage storage,
recalculateIfNecessary();
}
- public void release() {
+ public void reset() {
myEventsStorage.release();
myEventsStorage.add(myEditor.getDocument(), new IncrementalCacheUpdateEvent(myEditor.getDocument()));
+ }
+
+ public void release() {
+ myEventsStorage.release();
myLineWrapPositionStrategy = null;
}
return;
}
- myLastDocumentStamp = myEditor.getDocument().getModificationStamp();
// There is a possible case that new dirty regions are encountered during processing, hence, we iterate on regions snapshot here.
List<IncrementalCacheUpdateEvent> events = new ArrayList<IncrementalCacheUpdateEvent>(myEventsStorage.getEvents());
myEventsStorage.release();
myContext.softWrapStartOffset = softWrap.getStart() + 1;
}
- public void recalculateIfNecessary() {
- recalculateIfNecessary(myEditor.getDocument().getModificationStamp());
- }
-
/**
* There is a possible case that we need to reparse the whole document (e.g. visible area width is changed or user-defined
* soft wrap indent is changed etc). This method encapsulates that logic, i.e. it checks if necessary conditions are satisfied
* and updates internal state as necessary.
- *
- * @param documentStamp document modification stamp to use if document was changed while soft wrapping was off
*/
- public void recalculateIfNecessary(long documentStamp) {
+ public void recalculateIfNecessary() {
if (myInProgress) {
return;
}
// Check if we need to recalculate soft wraps due to visible area width change.
int currentVisibleAreaWidth = myWidthProvider.getVisibleAreaWidth();
- if (!indentChanged && myVisibleAreaWidth == currentVisibleAreaWidth && documentStamp == myLastDocumentStamp) {
+ if (!indentChanged && myVisibleAreaWidth == currentVisibleAreaWidth) {
recalculateSoftWraps(); // Recalculate existing dirty regions if any.
return;
}
// Drop information about processed lines then.
- myEventsStorage.release();
- myEventsStorage.add(myEditor.getDocument(), new IncrementalCacheUpdateEvent(myEditor.getDocument()));
+ reset();
myStorage.removeAll();
myVisibleAreaWidth = currentVisibleAreaWidth;
recalculateSoftWraps();
@Override
public void documentChanged(DocumentEvent event) {
- recalculateIfNecessary(event.getOldTimeStamp());
+ recalculateIfNecessary();
}
/**
import java.util.List;
import java.util.Map;
-public class FileChooserDialogImpl extends DialogWrapper implements FileChooserDialog, FileLookup {
- public static final DataKey<Boolean> PREFER_LAST_OVER_TO_SELECT = DataKey.create("PREFER_LAST_OVER_TO_SELECT");
+public class FileChooserDialogImpl extends DialogWrapper implements FileChooserDialog, FileLookup {
private final FileChooserDescriptor myChooserDescriptor;
protected FileSystemTreeImpl myFileSystemTree;
import com.intellij.openapi.components.ServiceBean;
import com.intellij.openapi.components.SettingsSavingComponent;
import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import java.io.File;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.options.SchemesManagerFactoryImpl");
- private final Collection<SchemesManagerImpl> myRegisteredManagers = new ArrayList<SchemesManagerImpl>();
+ private final Collection<SchemesManagerImpl> myRegisteredManagers = ContainerUtil.createEmptyCOWList();
public <T extends Scheme, E extends ExternalizableScheme> SchemesManager<T, E> createSchemesManager(final String fileSpec,
final SchemeProcessor<E> processor, final RoamingType roamingType) {
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
-import com.intellij.openapi.util.registry.Registry;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.openapi.vfs.impl.win32.Win32LocalFileSystem;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
import com.intellij.openapi.vfs.newvfs.RefreshQueue;
if (myWatcher.isOperational()) {
new StoreRefreshStatusThread().start();
}
- if (SystemInfo.isWindows &&
- Win32LocalFileSystem.isAvailable() &&
- Registry.is("filesystem.useNative")) {
- myNativeFileSystem = null; //Win32LocalFileSystem.getWin32Instance();
- }
- else {
- myNativeFileSystem = null;
- }
+ myNativeFileSystem = null;
}
public void initComponent() {
}
}
- ApplicationManager.getApplication().runWriteAction(new Runnable() {
- public void run() {
- refresh(false);
- }
- });
+ // grand VFS refresh significantly slows down local tests and generally not needed
+ //ApplicationManager.getApplication().runWriteAction(new Runnable() {
+ // public void run() {
+ // refresh(false);
+ // }
+ //});
myRootsToWatch.clear();
public static boolean showLicenseeInfo(Graphics g, int x, int y, final int height, final Color textColor) {
if (ApplicationInfoImpl.getShadowInstance().showLicenseeInfo()) {
- GraphicsConfig config = new GraphicsConfig(g);
- config.setAntialiasing(true);
+ UIUtil.applyRenderingHints(g);
g.setFont(new Font(UIUtil.ARIAL_FONT_NAME, Font.BOLD, 11));
g.setColor(textColor);
LicenseeInfoProvider provider = LicenseeInfoProvider.getInstance();
g.drawString(licensedToMessage, x + 21, y + height - 49);
g.drawString(licenseRestrictionsMessage, x + 21, y + height - 33);
}
- config.restore();
return true;
}
return false;
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import com.intellij.openapi.diagnostic.Logger;
-import gnu.trove.TIntArrayList;
-import org.jetbrains.annotations.NotNull;
-
-import java.io.IOException;
-
-public class ByteBufferIntObjectMap<V> {
- private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.ByteBufferMap");
-
- private final RandomAccessDataInput myBuffer;
- private final int myStartOffset;
- private final ByteBufferMap.ValueProvider<V> myValueProvider;
- private int myMod;
- private final int myEndOffset;
-
- public ByteBufferIntObjectMap(@NotNull MappedBufferWrapper buffer,
- int startOffset,
- int endOffset,
- @NotNull ByteBufferMap.ValueProvider<V> valueProvider) {
- assert startOffset < endOffset;
-
- myBuffer = new ByteBufferRADataInput(buffer);
- myStartOffset = startOffset;
- myEndOffset = endOffset;
- myValueProvider = valueProvider;
-
- myBuffer.setPosition(startOffset);
- try {
- myMod = myBuffer.readInt();
- }
- catch (IOException e) {
- LOG.error(e);
- }
- }
-
- public V get(int key) {
- int hash = hash(key);
- int keyGroupOffset = readKeyGroupOffset(hash);
- if (keyGroupOffset == -1) return null;
- if (!(myStartOffset < keyGroupOffset && keyGroupOffset < myEndOffset)){
- LOG.error("keyGroupOffset = " + keyGroupOffset + " myStartOffset = " + myStartOffset + " myEndOffset = " + myEndOffset);
- }
-
- try {
- myBuffer.setPosition(keyGroupOffset);
- int keyGroupSize = myBuffer.readInt();
- assert (keyGroupSize > 0);
- for (int i = 0; i < keyGroupSize; i++) {
- if (key == myBuffer.readInt()) {
- int valueOffset = myBuffer.readInt();
- assert (valueOffset > 0);
-
- myBuffer.setPosition(myStartOffset + valueOffset);
- return myValueProvider.get(myBuffer);
- }
- else {
- myBuffer.readInt(); //read offset;
- }
- }
- }
- catch (IOException e) {
- LOG.error(e);
- }
-
- return null;
- }
-
- public TIntArrayList getKeys() {
- TIntArrayList result = new TIntArrayList();
- getKeys(result);
- return result;
- }
-
- public void getKeys(TIntArrayList dst) {
- try {
- myBuffer.setPosition(myStartOffset + 4 /* mod */);
-
- int firstKeyGroupOffset = -1;
- int lastKeyGroupOffset = -1;
- for (int i = 0; i < myMod; i++) {
- int value = myBuffer.readInt();
- if (value != -1) {
- int offset = value + myStartOffset;
- if (firstKeyGroupOffset == -1) firstKeyGroupOffset = offset;
- lastKeyGroupOffset = offset;
- }
- }
- if (firstKeyGroupOffset == -1) {
- return;
- }
- assert (firstKeyGroupOffset > myStartOffset);
- assert (lastKeyGroupOffset > myStartOffset);
- assert (lastKeyGroupOffset >= firstKeyGroupOffset);
-
- int firstValueOffset = -1;
-
- myBuffer.setPosition(firstKeyGroupOffset);
- while (myBuffer.getPosition() <= lastKeyGroupOffset) {
- int groupSize = myBuffer.readInt();
- for (int i = 0; i < groupSize; i++) {
- dst.add(myBuffer.readInt());
-
- int valueOffset = myBuffer.readInt(); /* value offset */
- if( firstValueOffset == -1 ) firstValueOffset = valueOffset + myStartOffset;
- }
- }
- assert myBuffer.getPosition() == firstValueOffset;
- }
- catch (IOException e) {
- LOG.error(e);
- }
- }
-
- private int readKeyGroupOffset(int hash) {
- myBuffer.setPosition(myStartOffset + 4 /* mod */ + 4 * hash);
- int offset = -1;
- try {
- offset = myBuffer.readInt();
- }
- catch (IOException e) {
- LOG.error(e);
- }
- if (offset == -1) return -1;
- return offset + myStartOffset;
- }
-
- private int hash(int hashCode) {
- return Math.abs(hashCode) % myMod;
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import com.intellij.openapi.diagnostic.Logger;
-import org.jetbrains.annotations.NotNull;
-
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.IOException;
-import java.lang.reflect.Array;
-import java.util.ArrayList;
-import java.util.Collection;
-
-public class ByteBufferMap<K,V> {
- private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.ByteBufferMap");
-
- private final RandomAccessDataInput myBuffer;
- private final int myStartOffset;
- private final KeyProvider<K> myKeyProvider;
- private final ValueProvider<V> myValueProvider;
- private int myMod;
- private final int myEndOffset;
-
- public static interface KeyProvider<K> {
- int hashCode(K key);
-
- void write(DataOutput out, K key) throws IOException;
-
- int length(K key);
-
- K get(DataInput in) throws IOException;
-
- /**
- * Should move the buffer pointer to the key end.
- */
- boolean equals(DataInput in, K key) throws IOException;
- }
-
- public static interface ValueProvider<V> {
- void write(DataOutput out, V value) throws IOException;
-
- int length(V value);
-
- V get(DataInput in) throws IOException;
- }
-
- public static <V> void writeMap(DataOutput stream,
- ValueProvider<V> valueProvider,
- WriteableMap<V> map,
- double searchFactor) throws IOException {
- new ByteBufferMapWriteHandler<V>(stream, valueProvider, map, searchFactor).execute();
- }
-
- public static <V> int calcMapLength(ValueProvider<V> valueProvider,
- WriteableMap<V> map,
- double searchFactor) throws IOException {
- return new ByteBufferMapWriteHandler<V>(null, valueProvider, map, searchFactor).calcLength();
- }
-
- public ByteBufferMap(@NotNull MappedBufferWrapper holder,
- int startOffset,
- int endOffset,
- @NotNull KeyProvider<K> keyProvider,
- @NotNull ValueProvider<V> valueProvider) {
- this(new ByteBufferRADataInput(holder), startOffset, endOffset, keyProvider, valueProvider);
- }
-
- public ByteBufferMap(@NotNull RandomAccessDataInput buffer,
- int startOffset,
- int endOffset,
- @NotNull KeyProvider<K> keyProvider,
- @NotNull ValueProvider<V> valueProvider) {
- assert startOffset < endOffset;
-
- myBuffer = buffer;
- myStartOffset = startOffset;
- myEndOffset = endOffset;
- myKeyProvider = keyProvider;
- myValueProvider = valueProvider;
-
- buffer.setPosition(startOffset);
- try {
- myMod = buffer.readInt();
- }
- catch (IOException e) {
- LOG.error(e);
- }
- }
-
- public V get(K key) {
- int hash = hash(myKeyProvider.hashCode(key));
- int keyGroupOffset = readKeyGroupOffset(hash);
- if (keyGroupOffset == -1) return null;
- if (!(myStartOffset < keyGroupOffset && keyGroupOffset < myEndOffset)){
- LOG.error("keyGroupOffset = " + keyGroupOffset + " myStartOffset = " + myStartOffset + " myEndOffset = " + myEndOffset);
- }
-
- try {
- myBuffer.setPosition(keyGroupOffset);
- int keyGroupSize = myBuffer.readInt();
- assert (keyGroupSize > 0);
- for (int i = 0; i < keyGroupSize; i++) {
- if (myKeyProvider.equals(myBuffer, key)) {
- int valueOffset = myBuffer.readInt();
- assert (valueOffset > 0);
-
- myBuffer.setPosition(myStartOffset + valueOffset);
- return myValueProvider.get(myBuffer);
- }
- else {
- myBuffer.readInt(); //read offset;
- }
- }
- }
- catch (IOException e) {
- LOG.error(e);
- }
-
- return null;
- }
-
- @SuppressWarnings({"unchecked"})
- public K[] getKeys(Class<K> keyClass) {
- ArrayList<K> result = new ArrayList<K>();
- getKeys(keyClass, result);
- return result.toArray((K[])Array.newInstance(keyClass, result.size()));
- }
-
- public void getKeys(Class<K> keyClass, Collection<K> dst) {
- try {
- myBuffer.setPosition(myStartOffset + 4 /* mod */);
-
- int firstKeyGroupOffset = -1;
- int lastKeyGroupOffset = -1;
- for (int i = 0; i < myMod; i++) {
- int value = myBuffer.readInt();
- if (value != -1) {
- int offset = value + myStartOffset;
- if (firstKeyGroupOffset == -1) firstKeyGroupOffset = offset;
- lastKeyGroupOffset = offset;
- }
- }
- if (firstKeyGroupOffset == -1) {
- return;
- }
- assert (firstKeyGroupOffset > myStartOffset);
- assert (lastKeyGroupOffset > myStartOffset);
- assert (lastKeyGroupOffset >= firstKeyGroupOffset);
-
- int firstValueOffset = -1;
-
- myBuffer.setPosition(firstKeyGroupOffset);
- while (myBuffer.getPosition() <= lastKeyGroupOffset) {
- int groupSize = myBuffer.readInt();
- for (int i = 0; i < groupSize; i++) {
- dst.add(myKeyProvider.get(myBuffer));
-
- int valueOffset = myBuffer.readInt(); /* value offset */
- if( firstValueOffset == -1 ) firstValueOffset = valueOffset + myStartOffset;
- }
- }
- assert myBuffer.getPosition() == firstValueOffset;
- }
- catch (IOException e) {
- LOG.error(e);
- }
- }
-
- private int readKeyGroupOffset(int hash) {
- myBuffer.setPosition(myStartOffset + 4 /* mod */ + 4 * hash);
- int offset = -1;
- try {
- offset = myBuffer.readInt();
- }
- catch (IOException e) {
- LOG.error(e);
- }
- if (offset == -1) return -1;
- return offset + myStartOffset;
- }
-
- private int hash(int hashCode) {
- return Math.abs(hashCode) % myMod;
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import com.intellij.openapi.diagnostic.Logger;
-
-import java.io.DataOutput;
-import java.io.IOException;
-import java.util.Arrays;
-
-class ByteBufferMapWriteHandler<V> {
- private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.ByteBufferMapWriteHandler");
-
- private final ByteBufferMap.ValueProvider<V> myValueProvider;
- private final WriteableMap<V> myMap;
-
- private final int[] myKeyHashes;
- private final int myMod;
- private final DataOutput myOut;
-
- public ByteBufferMapWriteHandler(DataOutput stream, /*ByteBufferMap.KeyProvider keyProvider, */ByteBufferMap.ValueProvider<V> valueProvider, WriteableMap<V> map, double searchFactor) {
- myValueProvider = valueProvider;
- myMap = map;
-
- myKeyHashes = myMap.getHashCodesArray();
- int mod = (int)(myKeyHashes.length / searchFactor);
- myMod = mod != 0 ? mod : 1;
- myOut = stream;
- }
-
- public void execute() throws IOException {
-
- executeImpl( true );
- }
-
- public int calcLength() throws IOException {
- return executeImpl( false );
- }
-
- public int executeImpl( boolean write ) throws IOException {
- if( write ) myOut.writeInt(myMod);
- int offset = 4;
-
- int[] overflowList = new int[myKeyHashes.length];
- int[] firstOverflowElem = new int[myMod];
- int[] occurs = new int[myMod];
- Arrays.fill(firstOverflowElem, -1);
-
- // Creating hash table and overflow lists
- for( int i = myKeyHashes.length-1; i >= 0; i-- ) {
- int hashhash = hash(myKeyHashes[i]);
- overflowList[i] = firstOverflowElem[hashhash];
- firstOverflowElem[hashhash] = i;
- occurs[hashhash]++;
- }
-
- offset += 4 * myMod; // hash table size
- // writing hash table
- for( int i = 0; i < myMod; i++ ) {
- if( write ) myOut.writeInt( occurs[i] != 0 ? offset : -1 );
- if( occurs[i] != 0 ) offset += 4; // key group size, if key group present
- int occurs_i = 0;
- for( int j = firstOverflowElem[i]; j != -1; j = overflowList[j] ) {
- offset += myMap.getKeyLength( j ) + 4 /* value offset */;
- occurs_i++;
- }
- LOG.assertTrue( occurs_i == occurs[i] );
- }
-
- // writing key table
- for( int i = 0; i < myMod; i++ ) {
- if( occurs[i] == 0 ) continue;
-
- if( write ) myOut.writeInt( occurs[i] );
- for( int j = firstOverflowElem[i]; j != -1; j = overflowList[j] ) {
- if( write ) {
- myMap.writeKey( myOut, j );
- myOut.writeInt( offset );
- }
- V value = myMap.getValue(j);
- offset += myValueProvider.length(value);
- }
- }
-
- // writing value table
- for( int i = 0; i < myMod; i++ ) {
- for( int j = firstOverflowElem[i]; j != -1; j = overflowList[j] ) {
- V value = myMap.getValue(j);
- if( write ) myValueProvider.write( myOut, value );
- }
- }
-
- return offset; // total resulting length
- }
-
- private int hash(int hashCode){
- return Math.abs(hashCode) % myMod;
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import com.intellij.openapi.diagnostic.Logger;
-
-import java.io.DataInputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-
-/**
- * @author max
- */
-public class ByteBufferRADataInput implements RandomAccessDataInput {
- private static final Logger LOG = Logger.getInstance("com.intellij.util.io.ByteBufferRADataInput");
-
- private final MappedBufferWrapper myBuffer;
-
- public ByteBufferRADataInput(MappedBufferWrapper buffer) {
- myBuffer = buffer;
- }
-
- public void setPosition(int pos) {
- getBuffer().position(pos);
- }
-
- public int getPosition() {
- return getBuffer().position();
- }
-
- public void readFully(byte[] b) throws IOException {
- getBuffer().get(b);
- }
-
- public void readFully(byte[] b, int off, int len) throws IOException {
- getBuffer().get(b, off, len);
- }
-
- public int skipBytes(int n) throws IOException {
- int newPos = getPosition() + n;
- setPosition(newPos);
- return newPos;
- }
-
- public boolean readBoolean() throws IOException {
- return getBuffer().get() == 1;
- }
-
- public byte readByte() throws IOException {
- return getBuffer().get();
- }
-
- public int readUnsignedByte() throws IOException {
- return 0xFF & ((int)getBuffer().get());
- }
-
- public short readShort() throws IOException {
- return getBuffer().getShort();
- }
-
- public int readUnsignedShort() throws IOException {
- return 0xFFFF & ((int)getBuffer().getShort());
- }
-
- public char readChar() throws IOException {
- return getBuffer().getChar();
- }
-
- public int readInt() throws IOException {
- return getBuffer().getInt();
- }
-
- public long readLong() throws IOException {
- return getBuffer().getLong();
- }
-
- public float readFloat() throws IOException {
- return getBuffer().getFloat();
- }
-
- public double readDouble() throws IOException {
- return getBuffer().getDouble();
- }
-
- public String readLine() throws IOException {
- LOG.error("Not implemented");
- return null;
- }
-
- public String readUTF() throws IOException {
- return DataInputStream.readUTF(this);
- }
-
- public ByteBuffer getBuffer() {
- return myBuffer.buf();
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.vfs.VirtualFile;
-import gnu.trove.TObjectIntHashMap;
-
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.IOException;
-
-public class FileKeyProvider implements ByteBufferMap.KeyProvider<VirtualFile>{
- private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.FileKeyProvider");
-
- private final VirtualFile[] myFileIndex;
- private final TObjectIntHashMap<VirtualFile> myFileToIndexMap;
-
- public FileKeyProvider(VirtualFile[] fileIndex, TObjectIntHashMap<VirtualFile> fileToIndexMap) {
- myFileIndex = fileIndex;
- myFileToIndexMap = fileToIndexMap;
- }
-
- public int hashCode(VirtualFile key) {
- int index = myFileToIndexMap.get(key) - 1;
- return index;
- }
-
- public void write(DataOutput out, VirtualFile key) throws IOException {
- int index = myFileToIndexMap.get(key) - 1;
- LOG.assertTrue(index >= 0);
- out.writeInt(index);
- }
-
- public int length(VirtualFile key) {
- return 4;
- }
-
- public VirtualFile get(DataInput in) throws IOException {
- int index = in.readInt();
- return myFileIndex[index];
- }
-
- public boolean equals(DataInput in, VirtualFile key) throws IOException {
- int index = in.readInt();
- return key.equals(myFileIndex[index]);
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.util.ArrayUtil;
-
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.IOException;
-
-public class IntArrayValueProvider implements ByteBufferMap.ValueProvider<int[]> {
- private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.IntArrayValueProvider");
- public static final IntArrayValueProvider INSTANCE = new IntArrayValueProvider(-1);
-
- private final int myArraySize;
-
- public IntArrayValueProvider(int arraySize) {
- myArraySize = arraySize;
- }
-
- public void write(DataOutput out, int[] value) throws IOException {
- //if (value instanceof IntArrayList) {
- // IntArrayList list = (IntArrayList) value;
- // LOG.assertTrue(myArraySize == -1 || list.size() == myArraySize);
- // if (myArraySize == -1) out.writeInt(list.size());
- // for (int i = 0; i < list.size(); i++) {
- // out.writeInt(list.get(i));
- // }
- //} else if (value instanceof TIntArrayList) {
- // TIntArrayList list = (TIntArrayList) value;
- // LOG.assertTrue(myArraySize == -1 || list.size() == myArraySize);
- // if (myArraySize == -1) out.writeInt(list.size());
- // for (int i = 0; i < list.size(); i++) {
- // out.writeInt(list.get(i));
- // }
- //} else {
- int[] array = (int[])value;
- LOG.assertTrue(myArraySize == -1 || array.length == myArraySize);
- if (myArraySize == -1) out.writeInt(array.length);
- for(int i = 0; i < array.length; i++){
- out.writeInt(array[i]);
- }
- //}
- }
-
- public int length(int[] value) {
- //if (value instanceof IntArrayList) {
- // IntArrayList list = (IntArrayList) value;
- // LOG.assertTrue(myArraySize == -1 || list.size() == myArraySize);
- //
- // if (myArraySize == -1) return 4 * (list.size() + 1);
- //
- // return 4 * myArraySize;
- //} else if (value instanceof TIntArrayList) {
- // TIntArrayList list = (TIntArrayList) value;
- // LOG.assertTrue(myArraySize == -1 || list.size() == myArraySize);
- //
- // if (myArraySize == -1) return 4 * (list.size() + 1);
- //
- // return 4 * myArraySize;
- //} else {
- int[] array = (int[])value;
- LOG.assertTrue(myArraySize == -1 || array.length == myArraySize);
-
- if (myArraySize == -1) return 4 * (array.length + 1);
-
- return 4 * myArraySize;
- //}
- }
-
- public int[] get(DataInput in) throws IOException {
- final int[] result;
-
- if (myArraySize >= 0) {
- result = ArrayUtil.newIntArray(myArraySize);
- } else {
- result = ArrayUtil.newIntArray(in.readInt());
- }
-
- for(int i = 0; i < result.length; i++){
- result[i] = in.readInt();
- }
- return result;
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.IOException;
-
-/**
- * @author max
- */
-public class IntValueProvider implements ByteBufferMap.ValueProvider<Integer> {
- public static IntValueProvider INSTANCE = new IntValueProvider();
-
- private IntValueProvider() {
- }
-
- public void write(DataOutput out, Integer value) throws IOException {
- out.writeInt(((Integer)value).intValue());
- }
-
- public int length(Integer value) {
- return 4;
- }
-
- public Integer get(DataInput in) throws IOException {
- return new Integer(in.readInt());
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import com.intellij.openapi.diagnostic.Logger;
-
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.IOException;
-
-/**
- * @deprecated use {@link ByteBufferIntObjectMap} instead
- */
-public class IntegerKeyProvider implements ByteBufferMap.KeyProvider<Integer> {
- private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.StringKeyProvider");
-
- public static final IntegerKeyProvider INSTANCE = new IntegerKeyProvider();
-
- private IntegerKeyProvider() {
- }
-
- public int hashCode(Integer key) {
- return key.hashCode();
- }
-
- public void write(DataOutput out, Integer key) throws IOException {
- out.writeInt(key.intValue());
- }
-
- public int length(Integer key) {
- return 4;
- }
-
- public Integer get(DataInput in) throws IOException {
- return new Integer(in.readInt());
- }
-
- public boolean equals(DataInput in, Integer key) throws IOException {
- return key.intValue() == in.readInt();
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import com.intellij.openapi.diagnostic.Logger;
-
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-
-import org.jetbrains.annotations.NonNls;
-
-public class StringKeyProvider implements ByteBufferMap.KeyProvider<String>{
- private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.StringKeyProvider");
-
- public static final StringKeyProvider INSTANCE = new StringKeyProvider();
- @NonNls public static final String UTF_8_CHARSET_NAME = "UTF-8";
-
- private StringKeyProvider() {
- }
-
- public int hashCode(String key) {
- return key.hashCode();
- }
-
- public void write(DataOutput out, String key) throws IOException {
- String keyString = (String)key;
- byte[] keyBytes = keyString.getBytes(UTF_8_CHARSET_NAME);
- out.writeInt(keyBytes.length);
- out.write(keyBytes);
- }
-
- public int length(String key) {
- try{
- String keyString = (String)key;
- byte[] keyBytes = keyString.getBytes(UTF_8_CHARSET_NAME);
- return 4 + keyBytes.length;
- }
- catch(UnsupportedEncodingException e){
- LOG.error(e);
- return 0;
- }
- }
-
- public String get(DataInput in) throws IOException {
- int length = in.readInt();
- byte[] bytes = new byte[length];
- in.readFully(bytes);
- try {
- return new String(bytes, UTF_8_CHARSET_NAME);
- }
- catch (UnsupportedEncodingException e) {
- LOG.error(e);
- return null;
- }
- }
-
- public boolean equals(DataInput in, String key) throws IOException {
- try {
- String keyString = (String)key;
- byte[] keyBytes = keyString.getBytes(UTF_8_CHARSET_NAME);
-
- int length = in.readInt();
- byte[] inputBytes = new byte[length];
- in.readFully(inputBytes);
- if (length != keyBytes.length) return false;
- for (int i = 0; i < length; i++) {
- if (keyBytes[i] != inputBytes[i]) return false;
- }
-
- return true;
- }
- catch (UnsupportedEncodingException e) {
- LOG.error(e);
- return false;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import java.io.DataOutput;
-import java.io.IOException;
-import java.util.Map;
-
-/**
- * @author max
- */
-public class WriteableMapAdapter<K,V> implements WriteableMap<V> {
- private final Map<K,V> myMap;
- private final ByteBufferMap.KeyProvider myKeyProvider;
- private final K[] myKeys;
-
- public WriteableMapAdapter(Map<K,V> map, ByteBufferMap.KeyProvider provider) {
- myMap = map;
- myKeyProvider = provider;
- myKeys = (K[]) myMap.keySet().toArray();
- }
-
- public int[] getHashCodesArray() {
- int[] keyHashCodes = new int[ myKeys.length ];
- for( int i = 0; i < myKeys.length; i++ )
- keyHashCodes[i] = myKeyProvider.hashCode(myKeys[i]);
- return keyHashCodes;
- }
-
- public V getValue( int n ) {
- return myMap.get( myKeys[n] );
- }
-
- public int getKeyLength( int n ) {
- return myKeyProvider.length( myKeys[n] );
- }
-
- public void writeKey( DataOutput out, int n ) throws IOException {
- myKeyProvider.write( out, myKeys[n] );
- }
-}
init(fileText);
myEditor.getSettings().setUseSoftWraps(true);
SoftWrapModelImpl model = (SoftWrapModelImpl)myEditor.getSoftWrapModel();
- model.refreshSettings();
+ model.reinitSettings();
SoftWrapApplianceManager applianceManager = model.getApplianceManager();
applianceManager.setWidthProvider(new SoftWrapApplianceManager.VisibleAreaWidthProvider() {
aboutbox.vendor=Vendor: {0}
aboutbox.maintenance.due=Entitled for free updates and upgrades until {0,date,MMMM dd,yyyy}
title.warning=Warning
-message.upgrade.from.previous.required=Your license is not valid for use with this version of {0}. <br/> For information on how to upgrade your license please go to {1}
-title.upgrade.needed=Upgrade Needed
+message.upgrade.from.previous.required=Your license is not valid for use with this version of {0}. <br/> For information on how to upgrade your license please go to {1} <br/> You can also opt for a free time-limited evaluation.
+title.upgrade.needed=License Upgrade Needed
message.evaluation.has.expired=Your {0} evaluation has expired. Your session will be limited to 30 minutes.<br>{1}
title.evaluation.license.expired=Evaluation License Expired
message.evaluation.license.expired=Your evaluation license has expired. {0} will now exit.
scripting.lib.usageScope.caption=Specify which libraries are used in specific files and/or directories.
scripting.lib.usageScope.tableTitle=Library
scripting.lib.usageScope.override.question=Override library settings for child directories and files?
-scripting.lib.usageScope.override.title=Override Library Settings
\ No newline at end of file
+scripting.lib.usageScope.override.title=Override Library Settings
project.new.wizard.import.footnote=Import from external model is available from New Project Wizard only
loading.components.for=Loading components for ''{0}''
initializing.components=Initializing components
+
+library.docs.node=Documentation
\ No newline at end of file
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.openapi.vfs.impl.VirtualFilePointerManagerImpl;
import com.intellij.openapi.vfs.impl.local.LocalFileSystemImpl;
import com.intellij.openapi.vfs.newvfs.ManagingFS;
protected void setUp() throws Exception {
super.setUp();
if (ourTestCase != null) {
- String message = "Previous test " + ourTestCase +
- " hasn't called tearDown(). Probably overriden without super call.";
+ String message = "Previous test " + ourTestCase + " hasn't called tearDown(). Probably overridden without super call.";
ourTestCase = null;
fail(message);
}
public static File createTempDir(@NonNls final String prefix) throws IOException {
final File tempDirectory = FileUtil.createTempDirectory(TEST_DIR_PREFIX + prefix, null);
myFilesToDelete.add(tempDirectory);
- ApplicationManager.getApplication().runWriteAction(new Runnable() {
- @Override
- public void run() {
- VirtualFileManager.getInstance().refresh(false);
- }
- });
return tempDirectory;
}
private synchronized File getFile() {
if (myFile == null) {
try {
- final File tempFile = FileUtil.createTempFile("frst", "scd");
+ final File tempFile = FileUtil.createTempFile("idea_test_", ".out");
if (tempFile.exists()) {
myFile = tempFile;
return myFile;
if (myFile != null) FileUtil.delete(myFile);
}
+ public synchronized boolean hasOutput() {
+ return myFile != null;
+ }
+
public void flush(final List<Printable> printables) {
if (printables.isEmpty()) return;
final ArrayList<Printable> currentPrintables = new ArrayList<Printable>(printables);
}
public void printOn(final Printer console, final List<Printable> printables) {
- final File file = getFile();
- if (file == null) return;
+ final File file = hasOutput() ? getFile() : null;
final Runnable request = new Runnable() {
@Override
public void run() {
private class MyFileContentPrinter {
- public void printFileContent(Printer printer, File file, List<Printable> nestedPrintables) {
- DataInputStream reader = null;
- try {
- reader = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
- int lineNum = 0;
- while (reader.available() > 0 && !wasPrintableChanged(printer)) {
- if (lineNum == CompositePrintable.this.getExceptionMark() && lineNum > 0) printer.mark();
- final String line = IOUtil.readString(reader);
- boolean printed = false;
- for (ConsoleViewContentType contentType : ConsoleViewContentType.OUTPUT_TYPES) {
- final String prefix = contentType.toString();
- if (line.startsWith(prefix)) {
- printer.print(line.substring(prefix.length()), contentType);
- myLastSelected = contentType;
- printed = true;
- break;
- }
- }
- if (!printed) {
- if (line.startsWith(HYPERLINK)) {
- new DiffHyperlink(IOUtil.readString(reader), IOUtil.readString(reader), IOUtil.readString(reader)).printOn(printer);
+ public void printFileContent(Printer printer, @Nullable File file, List<Printable> nestedPrintables) {
+ if (file != null) {
+ DataInputStream reader = null;
+ try {
+ reader = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
+ int lineNum = 0;
+ while (reader.available() > 0 && !wasPrintableChanged(printer)) {
+ if (lineNum == CompositePrintable.this.getExceptionMark() && lineNum > 0) printer.mark();
+ final String line = IOUtil.readString(reader);
+ boolean printed = false;
+ for (ConsoleViewContentType contentType : ConsoleViewContentType.OUTPUT_TYPES) {
+ final String prefix = contentType.toString();
+ if (line.startsWith(prefix)) {
+ printer.print(line.substring(prefix.length()), contentType);
+ myLastSelected = contentType;
+ printed = true;
+ break;
+ }
}
- else {
- printer.print(line, myLastSelected != null ? myLastSelected : ConsoleViewContentType.NORMAL_OUTPUT);
+ if (!printed) {
+ if (line.startsWith(HYPERLINK)) {
+ new DiffHyperlink(IOUtil.readString(reader), IOUtil.readString(reader), IOUtil.readString(reader)).printOn(printer);
+ }
+ else {
+ printer.print(line, myLastSelected != null ? myLastSelected : ConsoleViewContentType.NORMAL_OUTPUT);
+ }
}
+ lineNum++;
}
- lineNum++;
- }
-
- for (int i = 0; i < nestedPrintables.size(); i++) {
- if (i == getExceptionMark() && i > 0) printer.mark();
- nestedPrintables.get(i).printOn(printer);
- }
- }
- catch (FileNotFoundException e) {
- LOG.info(e);
- }
- catch (IOException e) {
- LOG.error(e);
- }
- finally {
- try {
- if (reader != null) {
- reader.close();
- }
}
catch (FileNotFoundException e) {
LOG.info(e);
catch (IOException e) {
LOG.error(e);
}
+ finally {
+ try {
+ if (reader != null) {
+ reader.close();
+ }
+ }
+ catch (FileNotFoundException e) {
+ LOG.info(e);
+ }
+ catch (IOException e) {
+ LOG.error(e);
+ }
+ }
+ }
+ for (int i = 0; i < nestedPrintables.size(); i++) {
+ if (i == getExceptionMark() && i > 0) printer.mark();
+ nestedPrintables.get(i).printOn(printer);
}
}
import org.jetbrains.annotations.NonNls;
import java.io.File;
+import java.io.IOException;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
myLength = length;
}
- protected abstract MappedByteBuffer map();
+ protected abstract MappedByteBuffer map() throws IOException;
private static final int MAX_FORCE_ATTEMPTS = 10;
return myBuffer;
}
- public ByteBuffer buf() {
+ public ByteBuffer buf() throws IOException {
if (myBuffer == null) {
myBuffer = map();
}
+++ /dev/null
-/*
- * Copyright 2000-2009 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.intellij.util.io;
-
-import com.intellij.openapi.Forceable;
-import com.intellij.openapi.diagnostic.Logger;
-import org.jetbrains.annotations.NonNls;
-
-import java.io.*;
-import java.nio.ByteBuffer;
-import java.nio.MappedByteBuffer;
-
-/**
- * @author max
- */
-public class MappedFile implements Forceable {
- private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.MappedFile");
-
- private MappedBufferWrapper myHolder;
- private final File myFile;
-
- private long myRealSize;
- private long mySize;
- private long myPosition;
- private boolean myIsDirty = false;
-
- @NonNls private static final String UTF_8_CHARSET_NAME = "UTF-8";
- @NonNls private static final String RW = "rw";
- private final byte[] buffer = new byte[8];
-
- public MappedFile(File file, int initialSize) throws IOException {
- myFile = file;
- if (!file.exists() || file.length() == 0) {
- writeLength(0);
- }
-
- myPosition = 0;
- map();
-
- mySize = readLength();
- if (mySize == 0) {
- resize(initialSize);
- }
- }
-
- private long readLength() {
- File lengthFile = getLengthFile();
- DataInputStream stream = null;
- try {
- stream = new DataInputStream(new FileInputStream(lengthFile));
- return stream.readLong();
- }
- catch (IOException e) {
- writeLength(myRealSize);
- return myRealSize;
- }
- finally {
- if (stream != null) {
- try {
- stream.close();
- }
- catch (IOException e) {
- LOG.error(e);
- }
- }
- }
- }
-
- private File getLengthFile() {
- return new File(myFile.getPath() + ".len");
- }
-
- private void writeLength(final long len) {
- File lengthFile = getLengthFile();
- DataOutputStream stream = null;
- try {
- stream = new DataOutputStream(new FileOutputStream(lengthFile));
- stream.writeLong(len);
- }
- catch (FileNotFoundException e) {
- LOG.error(e);
- }
- catch (IOException e) {
- LOG.error(e);
- }
- finally {
- if (stream != null) {
- try {
- stream.close();
- }
- catch (IOException e) {
- LOG.error(e);
- }
- }
- }
- }
-
- private void map() {
- myHolder = new ReadWriteMappedBufferWrapper(myFile);
- myRealSize = myFile.length();
- if (LOG.isDebugEnabled()) {
- LOG.assertTrue(myPosition > 0L && myPosition < myRealSize || myPosition == 0 && myRealSize == 0, "myPosition=" + myPosition + ", myRealSize=" + myRealSize);
- }
- myHolder.buf().position((int)myPosition);
- }
-
- public short getShort(int index) throws IOException {
- seek(index);
- return readShort();
- }
-
- public short readShort() throws IOException {
- get(buffer, 0, 2);
-
- return Bits.getShort(buffer, 0);
- }
-
- public void putShort(int index, short value) throws IOException {
- seek(index);
- writeShort(value);
- }
-
- public void writeShort(int value) throws IOException {
- Bits.putShort(buffer, 0, (short)value);
- put(buffer, 0, 2);
- }
-
- public int getInt(int index) throws IOException {
- seek(index);
- return readInt();
- }
-
- public long getLong(final int index) throws IOException {
- seek(index);
- return readLong();
- }
-
- public void putInt(int index, int value) throws IOException {
- seek(index);
- writeInt(value);
- }
-
- public void putLong(final int index, final long value) throws IOException {
- seek(index);
- writeLong(value);
- }
-
- public byte get(int index) throws IOException {
- seek(index);
- return readByte();
- }
-
- public void put(int index, byte value) throws IOException {
- seek(index);
- writeByte(value);
- }
-
- public void get(int index, byte[] dst, int offset, int length) throws IOException {
- seek(index);
- get(dst, offset, length);
- }
-
- public void get(final byte[] dst, final int offset, final int length) throws IOException {
- if (myPosition + length > mySize) {
- throw new EOFException();
- }
-
- buf().get(dst, offset, length);
- myPosition += length;
- }
-
- public void put(int index, byte[] src, int offset, int length) throws IOException {
- seek(index);
- put(src, offset, length);
- }
-
- public void seek(long pos) throws IOException {
- ensureSize(pos);
- buf().position((int)pos);
- myPosition = pos;
- if (pos > mySize) {
- mySize = pos;
- }
- }
-
- private ByteBuffer buf() {
- if (!isMapped()) {
- map();
- }
-
- return myHolder.buf();
- }
-
- private void ensureSize(final long pos) throws IOException {
- while (pos >= myRealSize) {
- expand();
- }
- }
-
- private void expand() throws IOException {
- resize((int)((myRealSize + 1) * 13) >> 3);
- }
-
- public void put(final byte[] src, final int offset, final int length) throws IOException {
- ensureSize(myPosition + length);
- myIsDirty = true;
- buf().put(src, offset, length);
- myPosition += length;
- if (myPosition > mySize) {
- mySize = myPosition;
- }
- }
-
- public void flush() {
- if (myIsDirty) {
- writeLength(mySize);
- final ByteBuffer buf = buf();
- if (buf instanceof MappedByteBuffer) {
- MappedBufferWrapper.tryForce(buf);
- }
- myIsDirty = false;
- }
- }
-
- public void force() {
- flush();
- }
-
- public boolean isDirty() {
- return myIsDirty;
- }
-
- public void close() {
- if (myIsDirty) {
- writeLength(mySize);
- }
- unmap();
- }
-
- public void resize(int size) throws IOException {
- final int current = (int)myRealSize;
- if (current == size) return;
- unmap();
- RandomAccessFile raf = new RandomAccessFile(myFile, RW);
- try {
- raf.setLength(size);
- }
- finally {
- raf.close();
- }
- map();
- }
-
- public final long length() {
- return mySize;
- }
-
- public long getFilePointer() {
- return myPosition;
- }
-
- public int readInt() throws IOException {
- get(buffer, 0, 4);
- return Bits.getInt(buffer, 0);
- }
-
- public long readLong() throws IOException {
- get(buffer, 0, 8);
- return Bits.getLong(buffer, 0);
- }
-
- public void writeInt(int value) throws IOException {
- Bits.putInt(buffer, 0, value);
- put(buffer, 0, 4);
- }
-
- public void writeLong(long value) throws IOException {
- Bits.putLong(buffer, 0, value);
- put(buffer, 0, 8);
- }
-
- public String readUTF() throws IOException {
- try {
- int len = readInt();
- byte[] bytes = new byte[ len ];
- get(bytes, 0, len);
- return new String(bytes, UTF_8_CHARSET_NAME);
- }
- catch (UnsupportedEncodingException e) {
- // Can't be
- return "";
- }
- }
-
- public void writeUTF(String value) throws IOException {
- try {
- final byte[] bytes = value.getBytes(UTF_8_CHARSET_NAME);
- writeInt(bytes.length);
- put(bytes, 0, bytes.length);
- }
- catch (UnsupportedEncodingException e) {
- // Can't be
- }
- }
-
- public int readUnsignedShort() throws IOException {
- get(buffer, 0, 2);
-
- int ch1 = buffer[0] & 0xff;
- int ch2 = buffer[1] & 0xff;
- return (ch1 << 8) + ch2;
- }
-
- public char readChar() throws IOException {
- return (char)readUnsignedShort();
- }
-
- public void writeChar(char value) throws IOException {
- writeShort(value);
- }
-
- public byte readByte() throws IOException {
- get(buffer, 0, 1);
- return buffer[0];
- }
-
- public void writeByte(byte value) throws IOException {
- buffer[0] = value;
- put(buffer, 0, 1);
- }
-
- private void unmap() {
- if (myHolder != null) {
- /* flush(); TODO: Don't commit... */
- myHolder.unmap();
- }
- }
-
- public boolean isMapped() {
- return myHolder.isMapped();
- }
-}
package com.intellij.util.io;
import com.intellij.openapi.Forceable;
+import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.containers.hash.LinkedHashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
* @author max
*/
public class PagedFileStorage implements Forceable {
- private final static int BUFFER_SIZE = 10 * 1024 * 1024; // 10M
+
+ protected static final Logger LOG = Logger.getInstance("#com.intellij.util.io.PagedFileStorage");
+ private static final int MEGABYTE = 1024 * 1024;
+ private final static int BUFFER_SIZE = 10 * MEGABYTE;
+ private final static int UPPER_LIMIT = 200 * MEGABYTE;
+ private final static int LOWER_LIMIT = 100 * MEGABYTE;
private final StorageLock myLock;
final BuffersCache myBuffersCache = new BuffersCache();
private class BuffersCache extends MyCache {
+
public BuffersCache() {
- super(20 * BUFFER_SIZE);
+ super(UPPER_LIMIT);
}
@NotNull
if (off > key.owner.length()) {
throw new IndexOutOfBoundsException("off=" + off + " key.owner.length()=" + key.owner.length());
}
- return new ReadWriteMappedBufferWrapper(key.owner.myFile, off, Math.min((int)(key.owner.length() - off), BUFFER_SIZE));
+ ReadWriteMappedBufferWrapper wrapper =
+ new ReadWriteMappedBufferWrapper(key.owner.myFile, off, Math.min((int)(key.owner.length() - off), BUFFER_SIZE));
+ IOException oome = null;
+ while (true) {
+ try {
+ // ensure it's allocated
+ wrapper.buf();
+ if (oome != null) {
+ LOG.error("Successfully recovered OOME in memory mapping: -Xmx=" + Runtime.getRuntime().maxMemory() / MEGABYTE + "MB " +
+ "new size limit: " + mySizeLimit / MEGABYTE + "MB " +
+ "trying to allocate " + wrapper.myLength + " block");
+ }
+ return wrapper;
+ }
+ catch (IOException e) {
+ if (e.getCause() instanceof OutOfMemoryError) {
+ oome = e;
+ if (mySizeLimit > LOWER_LIMIT) {
+ mySizeLimit -= BUFFER_SIZE;
+ }
+ long newSize = getSize() - BUFFER_SIZE;
+ if (newSize >= 0) {
+ ensureSize(newSize);
+ continue; // next try
+ }
+ else {
+ throw new MappingFailedException("Cannot recover from OOME in memory mapping: -Xmx=" + Runtime.getRuntime().maxMemory() / MEGABYTE + "MB " +
+ "new size limit: " + mySizeLimit / MEGABYTE + "MB " +
+ "trying to allocate " + wrapper.myLength + " block", e);
+ }
+ }
+ throw new MappingFailedException("Cannot map buffer", e);
+ }
+ }
}
public void onDropFromCache(PageKey key, MappedBufferWrapper buf) {
private final byte[] myTypedIOBuffer = new byte[8];
private boolean isDirty = false;
private final File myFile;
- private long mySize = -1;
+ protected long mySize = -1;
@NonNls private static final String RW = "rw";
public PagedFileStorage(File file, StorageLock lock) throws IOException {
put(addr, myTypedIOBuffer, 0, 8);
}
+ @SuppressWarnings({"UnusedDeclaration"})
public void putByte(final int addr, final byte b) {
myTypedIOBuffer[0] = b;
put(addr, myTypedIOBuffer, 0, 1);
}
private ByteBuffer getBuffer(int page) {
- return myLock.myBuffersCache.get(new PageKey(this, page)).buf();
+ try {
+ return myLock.myBuffersCache.get(new PageKey(this, page)).buf();
+ }
+ catch (IOException e) {
+ throw new MappingFailedException("Cannot map buffer", e);
+ }
}
public void force() {
private static abstract class MyCache {
privat