Merge remote-tracking branch 'origin/master'

This commit is contained in:
Roman Shevchenko
2015-12-08 21:36:33 +01:00
125 changed files with 1311 additions and 901 deletions
+22
View File
@@ -648,6 +648,28 @@
<replaceConfiguration name="StringUtil.stripQuotesAroundValue" text="com.intellij.openapi.util.text.StringUtil.stripQuotesAroundValue($Parameter$)" recursive="false" caseInsensitive="false" type="JAVA" reformatAccordingToStyle="true" shortenFQN="true" replacement="com.intellij.openapi.util.text.StringUtil.unquoteString($Parameter$)">
<constraint name="Parameter" within="" contains="" />
</replaceConfiguration>
<replaceConfiguration name="can use StringUtil.trimStart" text="if ($s$.startsWith($e$)) {&#10; $s$ = $s$.substring($e$.length());&#10;}" recursive="false" caseInsensitive="true" type="JAVA" reformatAccordingToStyle="true" shortenFQN="true" replacement="$s$ = com.intellij.openapi.util.text.StringUtil.trimStart($s$, $e$);&#10;">
<constraint name="s" within="" contains="" />
<constraint name="e" within="" contains="" />
<constraint name="__context__" script="&quot;import com.intellij.psi.*&#10;import com.intellij.psi.search.GlobalSearchScope&#10;import com.intellij.psi.util.PsiUtil&#10;&#10;def stringUtil = JavaPsiFacade.getInstance(e.getProject()).findClass(&quot;com.intellij.openapi.util.text.StringUtil&quot;, GlobalSearchScope.allScope(e.getProject()));&#10;def strVirtualFile = PsiUtil.getVirtualFile(stringUtil);&#10;&#10;e.getParent().getParent().getParent() instanceof PsiIfStatement &amp;&amp;&#10;((PsiIfStatement)e.getParent().getParent().getParent()).getElseBranch() == null &amp;&amp;&#10;strVirtualFile != null &amp;&amp; &#10;e.getContainingFile().getResolveScope().contains(strVirtualFile)&#10;&quot;" target="true" within="" contains="" />
</replaceConfiguration>
<replaceConfiguration name="can use StringUtil.trimEnd" text="if ($s$.endsWith($e$)) {&#10; $s$ = $s$.substring(0, $s$.length() - $e$.length());&#10;}" recursive="false" caseInsensitive="true" type="JAVA" reformatAccordingToStyle="true" shortenFQN="true" replacement="$s$ = com.intellij.openapi.util.text.StringUtil.trimEnd($s$, $e$);&#10;">
<constraint name="s" within="" contains="" />
<constraint name="e" within="" contains="" />
<constraint name="__context__" script="&quot;import com.intellij.psi.*&#10;import com.intellij.psi.search.GlobalSearchScope&#10;import com.intellij.psi.util.PsiUtil&#10;&#10;def stringUtil = JavaPsiFacade.getInstance(e.getProject()).findClass(&quot;com.intellij.openapi.util.text.StringUtil&quot;, GlobalSearchScope.allScope(e.getProject()));&#10;def strVirtualFile = PsiUtil.getVirtualFile(stringUtil);&#10;&#10;e instanceof PsiLiteralExpression &amp;&amp;&#10;e.getParent().getParent().getParent() instanceof PsiIfStatement &amp;&amp;&#10;((PsiIfStatement)e.getParent().getParent().getParent()).getElseBranch() == null &amp;&amp;&#10;strVirtualFile != null &amp;&amp; &#10;e.getResolveScope().contains(strVirtualFile)&#10;&#10;&quot;" target="true" within="" contains="" />
</replaceConfiguration>
<replaceConfiguration name="can use StringUtil.trimStart() with constant" text="if ($s$.startsWith(&quot;$e$&quot;)) {&#10; $s$ = $s$.substring($n$);&#10;}" recursive="false" caseInsensitive="true" type="JAVA" reformatAccordingToStyle="true" shortenFQN="true" replacement="$s$ = com.intellij.openapi.util.text.StringUtil.trimStart($s$, &quot;$e$&quot;);&#10;">
<constraint name="s" within="" contains="" />
<constraint name="e" within="" contains="" />
<constraint name="n" within="" contains="" />
<constraint name="__context__" script="&quot;import com.intellij.psi.*&#10;import com.intellij.psi.search.GlobalSearchScope&#10;import com.intellij.psi.util.PsiUtil&#10;&#10;def stringUtil = JavaPsiFacade.getInstance(e.getProject()).findClass(&quot;com.intellij.openapi.util.text.StringUtil&quot;, GlobalSearchScope.allScope(e.getProject()));&#10;def strVirtualFile = PsiUtil.getVirtualFile(stringUtil);&#10;&#10;e instanceof PsiLiteralExpression &amp;&amp;&#10;n instanceof PsiLiteralExpression &amp;&amp;&#10;((PsiLiteralExpression)e).getValue() instanceof String &amp;&amp;&#10;((PsiLiteralExpression)n).getValue() instanceof Integer &amp;&amp;&#10;((String)((PsiLiteralExpression)e).getValue()).length() ==&#10;((Integer)((PsiLiteralExpression)n).getValue()).intValue() &amp;&amp;&#10;e.getParent().getParent().getParent() instanceof PsiIfStatement &amp;&amp;&#10;((PsiIfStatement)e.getParent().getParent().getParent()).getElseBranch() == null &amp;&amp; &#10;strVirtualFile != null &amp;&amp; &#10;e.getResolveScope().contains(strVirtualFile)&quot;" target="true" within="" contains="" />
</replaceConfiguration>
<replaceConfiguration name="can use StringUtil.trimEnd() with constant" text="if ($s$.endsWith(&quot;$e$&quot;)) {&#10; $s$ = $s$.substring(0,$s$.length()-$n$);&#10;}" recursive="false" caseInsensitive="true" type="JAVA" reformatAccordingToStyle="true" shortenFQN="true" replacement="$s$ = com.intellij.openapi.util.text.StringUtil.trimEnd($s$, &quot;$e$&quot;);&#10;">
<constraint name="s" within="" contains="" />
<constraint name="e" within="" contains="" />
<constraint name="n" within="" contains="" />
<constraint name="__context__" script="&quot;import com.intellij.psi.*&#10;import com.intellij.psi.search.GlobalSearchScope&#10;import com.intellij.psi.util.PsiUtil&#10;&#10;def stringUtil = JavaPsiFacade.getInstance(e.getProject()).findClass(&quot;com.intellij.openapi.util.text.StringUtil&quot;, GlobalSearchScope.allScope(e.getProject()));&#10;def strVirtualFile = PsiUtil.getVirtualFile(stringUtil);&#10;&#10;e instanceof PsiLiteralExpression &amp;&amp;&#10;n instanceof PsiLiteralExpression &amp;&amp;&#10;((PsiLiteralExpression)e).getValue() instanceof String &amp;&amp;&#10;((PsiLiteralExpression)n).getValue() instanceof Integer &amp;&amp;&#10;((String)((PsiLiteralExpression)e).getValue()).length() ==&#10;((Integer)((PsiLiteralExpression)n).getValue()).intValue() &amp;&amp;&#10;e.getParent().getParent().getParent() instanceof PsiIfStatement &amp;&amp;&#10;((PsiIfStatement)e.getParent().getParent().getParent()).getElseBranch() == null &amp;&amp; &#10;strVirtualFile != null &amp;&amp; &#10;e.getResolveScope().contains(strVirtualFile)&quot;" target="true" within="" contains="" />
</replaceConfiguration>
</inspection_tool>
<inspection_tool class="SeamAnnotationIncorrectSignatureInspection" enabled="false" level="ERROR" enabled_by_default="false" />
<inspection_tool class="SeamAnnotationsInconsistencyInspection" enabled="false" level="ERROR" enabled_by_default="false" />
+1
View File
@@ -88,6 +88,7 @@
<module fileurl="file://$PROJECT_DIR$/platform/extensions/extensions.iml" filepath="$PROJECT_DIR$/platform/extensions/extensions.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/platform/external-system-api/external-system-api.iml" filepath="$PROJECT_DIR$/platform/external-system-api/external-system-api.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/platform/external-system-impl/external-system-impl.iml" filepath="$PROJECT_DIR$/platform/external-system-impl/external-system-impl.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/platform/external-system-rt/external-system-rt.iml" filepath="$PROJECT_DIR$/platform/external-system-rt/external-system-rt.iml" group="platform"/>
<module fileurl="file://$PROJECT_DIR$/java/compiler/forms-compiler/forms-compiler.iml" filepath="$PROJECT_DIR$/java/compiler/forms-compiler/forms-compiler.iml" group="java/compiler" />
<module fileurl="file://$PROJECT_DIR$/platform/forms_rt/forms_rt.iml" filepath="$PROJECT_DIR$/platform/forms_rt/forms_rt.iml" group="platform" />
<module fileurl="file://$PROJECT_DIR$/plugins/git4idea/git4idea.iml" filepath="$PROJECT_DIR$/plugins/git4idea/git4idea.iml" group="plugins/VCS" />
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.lang.regexp;
import com.intellij.openapi.util.text.StringUtil;
@@ -134,22 +149,21 @@ public final class DefaultRegExpPropertiesProvider {
}
public boolean isValidCategory(@NotNull String category) {
if (category.startsWith("In")) {
try {
return Character.UnicodeBlock.forName(category.substring(2)) != null;
} catch (IllegalArgumentException e) {
return false;
}
if (category.startsWith("In")) {
try {
return Character.UnicodeBlock.forName(category.substring(2)) != null;
}
if (category.startsWith("Is")) {
category = category.substring(2);
catch (IllegalArgumentException e) {
return false;
}
for (String[] name : myPropertyNames) {
if (name[0].equals(category)) {
return true;
}
}
category = StringUtil.trimStart(category, "Is");
for (String[] name : myPropertyNames) {
if (name[0].equals(category)) {
return true;
}
return false;
}
return false;
}
@Nullable
+2
View File
@@ -44,6 +44,8 @@
1.8 => redist/annotations-java8.jar
1.3 => plugins/junit/lib/junit-rt.jar
1.6 => lib/external-system-rt.jar
1.6 => plugins/gradle/lib/gradle-tooling-extension-api.jar
1.6 => plugins/gradle/lib/gradle-tooling-extension-impl.jar
+2
View File
@@ -181,6 +181,8 @@ def layoutFull(String home, String targetDirectory, String patchedDescriptorDir
jar("extensions.jar") { module("extensions")}
jar("external-system-rt.jar") { module("external-system-rt")}
jar([name: "idea.jar", duplicate: "preserve"]) {
implementationModules.each { module it}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import com.intellij.compiler.ant.taskdefs.PathRef;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.intellij.util.ArrayUtil;
@@ -163,9 +164,7 @@ public class ModuleChunkClasspath extends Path {
// Module source entry?
for (String url : getCompilationClasses(module, ((GenerationOptionsImpl)genOptions), generateRuntimeClasspath,
generateTestClasspath, dependencyLevel == 0)) {
if (url.endsWith(JarFileSystem.JAR_SEPARATOR)) {
url = url.substring(0, url.length() - JarFileSystem.JAR_SEPARATOR.length());
}
url = StringUtil.trimEnd(url, JarFileSystem.JAR_SEPARATOR);
final String propertyRef = genOptions.getPropertyRefForUrl(url);
if (propertyRef != null) {
pathItems.add(new PathElementItem(propertyRef));
@@ -29,6 +29,7 @@ import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.JavaCodeStyleManager;
@@ -89,9 +90,7 @@ public class UsedIconsListingAction extends AnAction {
String str = (String)value;
if (str.startsWith("\"")) {
str = str.substring(0);
if (str.endsWith("\"")) {
str = str.substring(0, str.length() - 1);
}
str = StringUtil.trimEnd(str, "\"");
}
if (!str.startsWith("/")) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import com.intellij.openapi.application.ApplicationActivationListener;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.IdeFrame;
import com.intellij.util.Alarm;
@@ -77,9 +78,7 @@ public class UnscrambleListener extends ApplicationActivationListener.Adapter {
for (String line : stacktrace.split("\n")) {
line = line.trim();
if (line.length() == 0) continue;
if (line.endsWith("\r")) {
line = line.substring(0, line.length() - 1);
}
line = StringUtil.trimEnd(line, "\r");
if (STACKTRACE_LINE.matcher(line).matches()) {
linesCount++;
}
@@ -40,6 +40,7 @@ import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
import com.intellij.codeInspection.htmlInspections.RequiredAttributesInspectionBase;
import com.intellij.codeInspection.varScopeCanBeNarrowed.FieldCanBeLocalInspection;
import com.intellij.diagnostic.PerformanceWatcher;
import com.intellij.diagnostic.ThreadDumper;
import com.intellij.execution.filters.TextConsoleBuilderFactory;
import com.intellij.execution.ui.ConsoleView;
import com.intellij.execution.ui.ConsoleViewContentType;
@@ -2118,13 +2119,19 @@ public class DaemonRespondToChangesTest extends DaemonAnalyzerTestCase {
}
private void waitForDaemon() {
long deadline = System.currentTimeMillis() + 10000;
long deadline = System.currentTimeMillis() + 60_000;
while (!myDaemonCodeAnalyzer.isRunning()) {
if (System.currentTimeMillis() > deadline) fail("Too long waiting for daemon to start");
if (System.currentTimeMillis() > deadline) {
System.out.println(ThreadDumper.dumpThreadsToString());
fail("Too long waiting for daemon to start");
}
UIUtil.dispatchAllInvocationEvents();
}
while (myDaemonCodeAnalyzer.isRunning()) {
if (System.currentTimeMillis() > deadline) fail("Too long waiting for daemon to finish");
if (System.currentTimeMillis() > deadline) {
System.out.println(ThreadDumper.dumpThreadsToString());
fail("Too long waiting for daemon to finish");
}
UIUtil.dispatchAllInvocationEvents();
}
}
@@ -149,17 +149,13 @@ public class IndentTest extends LightIdeaTestCase {
});
}
}, null, null);
String textAfter = loadFile(fileNameAfter);
String fileText = file.getText();
if (textAfter.startsWith("\n")) {
textAfter = textAfter.substring(1);
}
if (fileText.startsWith("\n")) {
fileText = fileText.substring(1);
}
textAfter = StringUtil.trimStart(textAfter, "\n");
fileText = StringUtil.trimStart(fileText, "\n");
assertEquals(textAfter, fileText);
}
@@ -128,7 +128,7 @@ public class TabIndentingTest extends LightIdeaTestCase {
doTest("SCR6197.java", "SCR6197_after.java");
}
private void doTest(String fileNameBefore, String fileNameAfter) throws Exception{
private void doTest(String fileNameBefore, String fileNameAfter) throws Exception {
String text = loadFile(fileNameBefore);
final PsiFile file = createFile(fileNameBefore, text);
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@@ -147,18 +147,14 @@ public class TabIndentingTest extends LightIdeaTestCase {
});
}
}, null, null);
String textAfter = loadFile(fileNameAfter);
String fileText = file.getText();
if (textAfter.startsWith("\n")) {
textAfter = textAfter.substring(1);
}
if (fileText.startsWith("\n")) {
fileText = fileText.substring(1);
}
textAfter = StringUtil.trimStart(textAfter, "\n");
fileText = StringUtil.trimStart(fileText, "\n");
if (!textAfter.equals(fileText)) {
System.err.println("Expected:");
System.err.println(textAfter);
@@ -17,6 +17,7 @@ package com.intellij.psi.formatter.java;
import com.intellij.lang.java.JavaLanguage;
import com.intellij.openapi.fileTypes.StdFileTypes;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
public class WrapperTest extends JavaFormatterTestCase {
@@ -28,9 +29,7 @@ public class WrapperTest extends JavaFormatterTestCase {
@Override
protected String prepareText(final String text) {
String result = text;
if (result.startsWith("\n")) {
result = result.substring(1);
}
result = StringUtil.trimStart(result, "\n");
return result;
}
@@ -308,9 +308,7 @@ public abstract class CodeInsightTestCase extends PsiTestCase {
List<OutputStream> streamsToClose = new ArrayList<OutputStream>();
for (String relativePath : relativePaths) {
if (relativePath.startsWith("/")) {
relativePath = relativePath.substring(1);
}
relativePath = StringUtil.trimStart(relativePath, "/");
final VirtualFile fromFile = fromDir.findFileByRelativePath(relativePath);
assertNotNull(fromDir.getPath() + "/" + relativePath, fromFile);
VirtualFile toFile = toDir.findFileByRelativePath(relativePath);
@@ -17,6 +17,7 @@ package com.intellij.testFramework.fixtures;
import com.intellij.lang.Language;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.impl.ComplementaryFontsRegistry;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
@@ -102,6 +103,10 @@ public abstract class LightCodeInsightFixtureTestCase extends UsefulTestCase {
myFixture.setTestDataPath(getTestDataPath());
myModule = myFixture.getModule();
// various tests can use different mocking techniques for font-related code
// so we must reset our font cache, to avoid potential impact of tests on other tests
ComplementaryFontsRegistry.resetCaches();
}
/**
@@ -16,6 +16,7 @@
package com.siyeh.ig;
import com.intellij.codeInspection.InspectionProfileEntry;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
import com.intellij.util.ArrayUtil;
import org.intellij.lang.annotations.Language;
@@ -107,9 +108,7 @@ public abstract class LightInspectionTestCase extends LightCodeInsightFixtureTes
basePath.append(word).append('/');
}
String lastWord = words[lastWordIndex];
if (lastWord.endsWith("Inspection")) {
lastWord = lastWord.substring(0, lastWord.length() - 10);
}
lastWord = StringUtil.trimEnd(lastWord, "Inspection");
final int length = lastWord.length();
boolean upperCase = false;
for (int i = 0; i < length; i++) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,7 @@
*/
package com.intellij.psi.search.scope.packageSet;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
@@ -22,7 +23,7 @@ public class NamedPackageSetReference extends PackageSetBase {
private final String myName;
public NamedPackageSetReference(String name) {
myName = name.startsWith("$") ? name.substring(1) : name;
myName = StringUtil.trimStart(name, "$");
}
@Override
@@ -24,6 +24,7 @@ import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeRegistry;
import com.intellij.openapi.util.BuildNumber;
import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.PlatformUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;
@@ -83,9 +84,7 @@ class AboutHttpService extends RestService {
if (!PlatformUtils.isIdeaUltimate()) {
String productName = ApplicationNamesInfo.getInstance().getProductName();
appName = appName.replace(productName + " (" + productName + ")", productName);
if (appName.startsWith("JetBrains ")) {
appName = appName.substring("JetBrains ".length());
}
appName = StringUtil.trimStart(appName, "JetBrains ");
}
writer.name("name").value(appName);
@@ -550,9 +550,7 @@ public class VfsUtilCore {
uri = uri.substring("file:/".length());
if (!SystemInfo.isWindows) uri = "/" + uri;
}
else if (uri.startsWith("file:")) {
uri = uri.substring("file:".length());
}
else uri = StringUtil.trimStart(uri, "file:");
VirtualFile file = null;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,6 @@
*/
package com.intellij.concurrency;
public abstract class JobSchedulerImpl {
public class JobSchedulerImpl extends JobScheduler {
public static final int CORES_COUNT = Runtime.getRuntime().availableProcessors();
}
@@ -15,6 +15,7 @@
*/
package com.intellij.psi.impl;
import com.intellij.concurrency.JobSchedulerImpl;
import com.intellij.diagnostic.ThreadDumper;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationAdapter;
@@ -35,28 +36,33 @@ import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiFile;
import com.intellij.util.Processor;
import com.intellij.util.SmartList;
import com.intellij.util.concurrency.BoundedTaskExecutorService;
import com.intellij.util.containers.Queue;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.ide.PooledThreadExecutor;
import javax.swing.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
public class DocumentCommitThread extends DocumentCommitProcessor implements Runnable, Disposable {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.DocumentCommitThread");
private static final String NAME = "Document commit thread";
private final ExecutorService executor = new BoundedTaskExecutorService(PooledThreadExecutor.INSTANCE, JobSchedulerImpl.CORES_COUNT, this);
private final Queue<CommitTask> documentsToCommit = new Queue<CommitTask>(10);
private final List<CommitTask> documentsToApplyInEDT = new ArrayList<CommitTask>(10); // guarded by documentsToCommit
private final ApplicationEx myApplication;
private volatile boolean isDisposed;
private CommitTask currentTask; // guarded by documentsToCommit
private volatile boolean threadFinished;
private volatile boolean myEnabled; // true if we can do commits. set to false temporarily during the write action.
private int runningWriteActions; // accessed in EDT only
@@ -108,9 +114,6 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
}
});
log("Starting thread", null, false);
Thread thread = new Thread(this, NAME);
thread.setDaemon(true);
thread.start();
}
@Override
@@ -120,17 +123,6 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
documentsToCommit.clear();
}
cancel("Stop thread");
wakeUpQueue();
while (!threadFinished) {
wakeUpQueue();
synchronized (documentsToCommit) {
try {
documentsToCommit.wait(10);
}
catch (InterruptedException ignored) {
}
}
}
}
private void disable(@NonNls Object reason) {
@@ -146,10 +138,8 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
log("Enabled", null, false, reason);
}
private void wakeUpQueue() {
synchronized (documentsToCommit) {
documentsToCommit.notifyAll();
}
private Future<?> wakeUpQueue() {
return executor.submit(this);
}
private void cancel(@NonNls @NotNull Object reason) {
@@ -220,8 +210,14 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
s += "; Uncommitted: " + task.document;
}
}
synchronized (documentsToCommit) {
int size = documentsToCommit.size();
if (size != 0) {
s += " (" + size + " documents are still in queue)";
}
}
// System.err.println(s);
//System.out.println(s);
synchronized (log) {
log.append(s).append("\n");
@@ -291,26 +287,19 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
@Override
public void run() {
threadFinished = false;
try {
while (!isDisposed) {
try {
pollQueue();
}
catch(Throwable e) {
LOG.error(e);
}
while (!isDisposed) {
try {
boolean polled = pollQueue();
if (!polled) break;
}
catch(Throwable e) {
LOG.error(e);
}
}
finally {
threadFinished = true;
}
// ping the thread waiting for close
wakeUpQueue();
log("Good bye", null, false);
}
private void pollQueue() {
// returns true if queue changed
private boolean pollQueue() {
boolean success = false;
Document document = null;
Project project = null;
@@ -319,8 +308,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
ProgressIndicator indicator;
synchronized (documentsToCommit) {
if (!myEnabled || documentsToCommit.isEmpty()) {
documentsToCommit.wait(1000);
return;
return false;
}
task = documentsToCommit.pullFirst();
document = task.document;
@@ -331,11 +319,11 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
if (project.isDisposed() || !((PsiDocumentManagerBase)PsiDocumentManager.getInstance(project)).isInUncommittedSet(document)) {
log("Abandon and proceed to next",task, false);
return;
return true;
}
if (task.removed) {
return; // document has been marked as removed, e.g. by synchronous commit
return true; // document has been marked as removed, e.g. by synchronous commit
}
startNewTask(task, "Pulled new task");
@@ -373,11 +361,6 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
log("PCE", task, false, e);
success = false;
}
catch (InterruptedException e) {
// app must be closing
log("IE", task, false, e);
cancel(e);
}
catch (Throwable e) {
LOG.error(e);
cancel(e);
@@ -389,6 +372,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
}
currentTask = null; // do not cancel, it's being invokeLatered
}
return true;
}
@Override
@@ -491,7 +475,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
return null;
}
Runnable finishRunnable = new Runnable() {
return new Runnable() {
@Override
public void run() {
myApplication.assertIsDispatchThread();
@@ -539,7 +523,6 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
}
}
};
return finishRunnable;
}
@NotNull
@@ -584,6 +567,6 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run
@Override
public String toString() {
return "Document commit thread; application: "+myApplication+"; isDisposed: "+isDisposed+"; threadFinished: "+threadFinished+"; myEnabled: "+myEnabled+"; runningWriteActions: "+runningWriteActions;
return "Document commit thread; application: "+myApplication+"; isDisposed: "+isDisposed+"; myEnabled: "+myEnabled+"; runningWriteActions: "+runningWriteActions;
}
}
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_6" inherit-compiler-output="true">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
@@ -14,5 +14,6 @@
<orderEntry type="module" module-name="platform-api" />
<orderEntry type="module" module-name="lang-api" />
<orderEntry type="module" module-name="compiler-openapi" />
<orderEntry type="module" module-name="external-system-rt" exported="" />
</component>
</module>
@@ -88,6 +88,11 @@ public class ModuleData extends AbstractNamedData implements Named, ExternalConf
.toCanonicalPath(myModuleFileDirectoryPath + "/" + getInternalName() + ModuleFileType.DOT_DEFAULT_EXTENSION);
}
@NotNull
public String getModuleFileDirectoryPath() {
return myModuleFileDirectoryPath;
}
public void setModuleFileDirectoryPath(@NotNull String path) {
myModuleFileDirectoryPath = path;
}
@@ -95,11 +95,14 @@ public abstract class AbstractModuleDataService<E extends ModuleData> extends Ab
final ModifiableModuleModel modifiableModel = modelsProvider.getModifiableModuleModel();
final String[] groupPath;
if (isOneToOneMapping || node.getData().getIdeModuleGroup() == null || projectData == null) {
if (isOneToOneMapping || projectData == null) {
groupPath = node.getData().getIdeModuleGroup();
}
else {
groupPath = ArrayUtil.prepend(projectData.getInternalName() + " modules", node.getData().getIdeModuleGroup());
final String externalProjectGroup = projectData.getInternalName() + " modules";
groupPath = node.getData().getIdeModuleGroup() == null
? new String[]{externalProjectGroup}
: ArrayUtil.prepend(externalProjectGroup, node.getData().getIdeModuleGroup());
}
modifiableModel.setModuleGroupPath(module, groupPath);
ModifiableRootModel modifiableRootModel = modelsProvider.getModifiableRootModel(module);
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_6" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="annotations" />
</component>
</module>
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,7 @@
*/
package com.intellij.psi.search;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -81,9 +82,7 @@ public class IndexPattern {
}
myPattern = Pattern.compile(myPatternString, flags);
String optimizedPattern = myPatternString;
if (optimizedPattern.startsWith(".*")) {
optimizedPattern = optimizedPattern.substring(".*".length());
}
optimizedPattern = StringUtil.trimStart(optimizedPattern, ".*");
myOptimizedIndexingPattern = Pattern.compile(optimizedPattern, flags);
}
catch(PatternSyntaxException e){
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -66,6 +66,7 @@ public final class LookupElementBuilder extends LookupElement {
this(lookupString, object, null, null, null, Collections.singleton(lookupString), true);
}
@NotNull
public static LookupElementBuilder create(@NotNull String lookupString) {
return new LookupElementBuilder(lookupString, lookupString);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.InputValidator;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import org.jetbrains.annotations.NonNls;
@@ -115,9 +116,7 @@ public abstract class CreateElementActionBase extends AnAction {
public static String filterMessage(String message) {
if (message == null) return null;
@NonNls final String ioExceptionPrefix = "java.io.IOException:";
if (message.startsWith(ioExceptionPrefix)) {
message = message.substring(ioExceptionPrefix.length());
}
message = StringUtil.trimStart(message, ioExceptionPrefix);
return message;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -32,6 +32,7 @@ import com.intellij.openapi.util.Conditions;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.*;
import com.intellij.ui.components.JBList;
import com.intellij.util.containers.hash.HashSet;
@@ -211,9 +212,7 @@ class BeforeRunStepsPanel extends JPanel {
Map.Entry<BeforeRunTaskProvider, Integer> entry = iterator.next();
BeforeRunTaskProvider provider = entry.getKey();
String name = provider.getName();
if (name.startsWith("Run ")) {
name = name.substring(4);
}
name = StringUtil.trimStart(name, "Run ");
if (sb.length() > 0) {
sb.append(", ");
}
@@ -1330,9 +1330,7 @@ public class SearchEverywhereAction extends AnAction implements CustomComponentA
}
hit = hit.replace(" ", " "); //avoid extra spaces from mnemonics and xml conversion
String text = hit.trim();
if (text.endsWith(":")) {
text = text.substring(0, text.length() - 1);
}
text = StringUtil.trimEnd(text, ":");
return text;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@ package com.intellij.ide.fileTemplates.impl;
import com.intellij.ide.fileTemplates.FileTemplate;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.io.URLUtil;
import java.io.BufferedInputStream;
@@ -87,9 +88,7 @@ public class UrlUtil {
private static List<String> getChildPathsFromJar(URL root) throws IOException {
final List<String> paths = new ArrayList<String>();
String file = root.getFile();
if (file.startsWith(FILE_PROTOCOL_PREFIX)) {
file = file.substring(FILE_PROTOCOL_PREFIX.length());
}
file = StringUtil.trimStart(file, FILE_PROTOCOL_PREFIX);
final int jarSeparatorIndex = file.indexOf(JAR_SEPARATOR);
assert jarSeparatorIndex > 0;
@@ -1,3 +1,18 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.execution.process;
import com.intellij.execution.ui.ConsoleViewContentType;
@@ -7,6 +22,7 @@ import com.intellij.openapi.editor.colors.TextAttributesKey;
import com.intellij.openapi.editor.markup.EffectType;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
@@ -76,12 +92,8 @@ public class ColoredOutputTypeRegistry {
if (attribute.startsWith("\u001B[")) {
attribute = attribute.substring(2);
}
else if (attribute.startsWith("[")) {
attribute = attribute.substring(1);
}
if (attribute.endsWith("m")) {
attribute = attribute.substring(0, attribute.length() - 1);
}
else attribute = StringUtil.trimStart(attribute, "[");
attribute = StringUtil.trimEnd(attribute, "m");
if (attribute.equals("0")) {
return ProcessOutputTypes.STDOUT;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,7 @@
*/
package com.intellij.openapi.roots.ui;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
@@ -70,9 +71,7 @@ public class LightFilePointer implements VirtualFilePointer {
public static String toPresentableUrl(String url) {
String path = VirtualFileManager.extractPath(url);
if (path.endsWith(JarFileSystem.JAR_SEPARATOR)) {
path = path.substring(0, path.length() - JarFileSystem.JAR_SEPARATOR.length());
}
path = StringUtil.trimEnd(path, JarFileSystem.JAR_SEPARATOR);
return path.replace('/', File.separatorChar);
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@ import com.intellij.openapi.application.PathMacros;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Couple;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.JBColor;
import com.intellij.util.ui.Table;
@@ -128,7 +129,7 @@ public class PathMacroTable extends Table {
final String value = pair.getSecond();
if (value != null && value.trim().length() > 0) {
String path = value.replace(File.separatorChar, '/');
if (path.endsWith("/")) path = path.substring(0, path.length() - 1);
path = StringUtil.trimEnd(path, "/");
myPathMacros.setMacro(pair.getFirst(), path);
}
}
@@ -149,7 +149,7 @@ public class CreateLauncherScriptAction extends DumbAwareAction {
String runPath = PathManager.getHomePath();
String productName = ApplicationNamesInfo.getInstance().getProductName().toLowerCase(Locale.US);
if (!SystemInfo.isMac) runPath += "/bin/" + productName + ".sh";
else if (runPath.endsWith(CONTENTS)) runPath = runPath.substring(0, runPath.length() - CONTENTS.length());
else runPath = StringUtil.trimEnd(runPath, CONTENTS);
ClassLoader loader = CreateLauncherScriptAction.class.getClassLoader();
assert loader != null;
@@ -61,7 +61,7 @@ public abstract class EditorGutterComponentEx extends JComponent implements Edit
public abstract int getAnnotationsAreaWidth();
@Nullable
public abstract Point getPoint(GutterIconRenderer renderer);
public abstract Point getCenterPoint(GutterIconRenderer renderer);
public abstract void setLineNumberConvertor(@NotNull TIntFunction lineNumberConvertor);
@@ -15,6 +15,7 @@
*/
package com.intellij.openapi.editor.impl;
import com.intellij.diagnostic.Dumpable;
import com.intellij.diagnostic.LogMessageEx;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.ApplicationManager;
@@ -47,7 +48,7 @@ import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.util.List;
public class CaretImpl extends UserDataHolderBase implements Caret {
public class CaretImpl extends UserDataHolderBase implements Caret, Dumpable {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.CaretImpl");
private final EditorImpl myEditor;
@@ -1484,6 +1485,33 @@ public class CaretImpl extends UserDataHolderBase implements Caret {
return myEditor.myUseNewRendering && myEditor.myView.isAtBidiRunBoundary(myVisibleCaret);
}
@NotNull
@Override
public String dumpState() {
return "{valid: " + isValid +
", offset: " + myOffset +
", logical pos: " + myLogicalCaret +
", visual pos: " + myVisibleCaret +
", visual line start: " + myVisualLineStart +
", visual line end: " + myVisualLineEnd +
", savedBeforeBulkCaretMarker: " + savedBeforeBulkCaretMarker +
", skip change requests: " + mySkipChangeRequests +
", desired selection start column: " + myDesiredSelectionStartColumn +
", desired selection end column: " + myDesiredSelectionEndColumn +
", report caret moves: " + myReportCaretMoves +
", desired x: " + myDesiredX +
", selection marker: " + mySelectionMarker +
", rangeMarker start position: " + myRangeMarkerStartPosition +
", rangeMarker end position: " + myRangeMarkerEndPosition +
", rangeMarker end position is lead: " + myRangeMarkerEndPositionIsLead +
", selection start before change: " + startBefore +
", selection end after change: " + endBefore +
", unknown direction: " + myUnknownDirection +
", virtual space offset: " + myVirtualSpaceOffset +
", virtual selection start offset: " + myStartVirtualOffset +
", virtual selection end offset: " + myEndVirtualOffset + '}';
}
/**
* Encapsulates information about target vertical range info - its <code>'y'</code> coordinate and height in pixels.
*/
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,7 @@
*/
package com.intellij.openapi.editor.impl;
import com.intellij.diagnostic.Dumpable;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.*;
@@ -36,12 +37,14 @@ import com.intellij.openapi.editor.impl.event.DocumentEventImpl;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.EventDispatcher;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, Disposable {
public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener, Disposable, Dumpable {
private final EditorImpl myEditor;
private final EventDispatcher<CaretListener> myCaretListeners = EventDispatcher.create(CaretListener.class);
@@ -512,6 +515,21 @@ public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener,
myCaretListeners.getMulticaster().caretRemoved(new CaretEvent(myEditor, caret, caret.getLogicalPosition(), caret.getLogicalPosition()));
}
@NotNull
@Override
public String dumpState() {
return "[in update: " + myIsInUpdate +
", document changed: " + isDocumentChanged +
", perform caret merging: " + myPerformCaretMergingAfterCurrentOperation +
", current caret: " + myCurrentCaret +
", all carets: " + ContainerUtil.map(myCarets, new Function<CaretImpl, String>() {
@Override
public String fun(CaretImpl caret) {
return caret.dumpState();
}
}) + "]";
}
private static class VisualPositionComparator implements Comparator<VisualPosition> {
private static final VisualPositionComparator INSTANCE = new VisualPositionComparator();
@@ -57,10 +57,7 @@ import com.intellij.openapi.wm.impl.IdeGlassPaneImpl;
import com.intellij.ui.HintHint;
import com.intellij.ui.JBColor;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.util.Function;
import com.intellij.util.IconUtil;
import com.intellij.util.NullableFunction;
import com.intellij.util.SmartList;
import com.intellij.util.*;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
@@ -242,14 +239,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
if (clip.height < 0) return;
Graphics2D g = IdeBackgroundUtil.withEditorBackground(g_, this);
AffineTransform old = g.getTransform();
if (isMirrored()) {
final AffineTransform transform = new AffineTransform(old);
transform.scale(-1, 1);
transform.translate(-getWidth(), 0);
g.setTransform(transform);
}
AffineTransform old = setMirrorTransformIfNeeded(g, 0, getWidth());
EditorUIUtil.setupAntialiasing(g);
Color backgroundColor = getBackground();
@@ -277,7 +267,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, hint);
}
g.setTransform(old);
if (old != null) g.setTransform(old);
}
finally {
((ApplicationImpl)ApplicationManager.getApplication()).editorPaintFinish();
@@ -379,8 +369,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
if (w == 0) return;
AffineTransform old = g.getTransform();
g.setTransform(getMirrorTransform(old, x, w));
AffineTransform old = setMirrorTransformIfNeeded(g, x, w);
try {
Color color = myEditor.getColorsScheme().getColor(EditorColors.ANNOTATIONS_COLOR);
g.setColor(color != null ? color : JBColor.blue);
@@ -422,7 +411,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
}
finally {
g.setTransform(old);
if (old != null) g.setTransform(old);
}
}
@@ -498,8 +487,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
g.setColor(color != null ? color : JBColor.blue);
g.setFont(myEditor.getColorsScheme().getFont(EditorFontType.PLAIN));
AffineTransform old = g.getTransform();
g.setTransform(getMirrorTransform(old, getLineNumberAreaOffset(), getLineNumberAreaWidth()));
AffineTransform old = setMirrorTransformIfNeeded(g, getLineNumberAreaOffset(), getLineNumberAreaWidth());
try {
for (int i = startLineNumber; i < endLineNumber; i++) {
LogicalPosition logicalPosition = myEditor.visualToLogicalPosition(new VisualPosition(i, 0));
@@ -526,7 +514,7 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
}
}
finally {
g.setTransform(old);
if (old != null) g.setTransform(old);
}
}
@@ -810,13 +798,12 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
public void process(int x, int y, GutterMark renderer) {
Icon icon = scaleIcon(renderer.getIcon());
AffineTransform old = g.getTransform();
g.setTransform(getMirrorTransform(old, x, icon.getIconWidth()));
AffineTransform old = setMirrorTransformIfNeeded(g, x, icon.getIconWidth());
try {
icon.paintIcon(EditorGutterComponentImpl.this, g, x, y);
}
finally {
g.setTransform(old);
if (old != null) g.setTransform(old);
}
}
});
@@ -875,7 +862,10 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
private Icon scaleIcon(Icon icon) {
if (Registry.is("editor.scale.gutter.icons") && icon instanceof ScalableIcon) {
return ((ScalableIcon)icon).scale((float)myEditor.getLineHeight() / JBUI.scale(17f));
float scale = myEditor.getLineHeight() / JBUI.scale(16f);
if (Math.abs(1f - scale) > 0.10f) {
return ((ScalableIcon)icon).scale(scale);
}
}
return icon;
}
@@ -1261,10 +1251,11 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
return myEditor.getVerticalScrollbarOrientation() != EditorEx.VERTICAL_SCROLLBAR_RIGHT;
}
@NotNull
private AffineTransform getMirrorTransform(@NotNull AffineTransform old, int offset, int width) {
final AffineTransform transform = new AffineTransform(old);
@Nullable
private AffineTransform setMirrorTransformIfNeeded(Graphics2D g, int offset, int width) {
if (isMirrored()) {
AffineTransform old = g.getTransform();
AffineTransform transform = new AffineTransform(old);
//transform.translate(getWidth(), 0); // revert mirroring transform
//transform.scale(-1, 1); // revert mirroring transform
//transform.translate(getWidth() - offset - width, 0); // move range start to the X==0
@@ -1272,8 +1263,12 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
transform.scale(-1, 1);
transform.translate(-offset * 2 - width, 0);
g.setTransform(transform);
return old;
}
else {
return null;
}
return transform;
}
@Nullable
@@ -1579,14 +1574,15 @@ class EditorGutterComponentImpl extends EditorGutterComponentEx implements Mouse
@Override
@Nullable
public Point getPoint(final GutterIconRenderer renderer) {
public Point getCenterPoint(final GutterIconRenderer renderer) {
final Ref<Point> result = Ref.create();
for (int line : myLineToGutterRenderers.keys()) {
processIconsRow(line, myLineToGutterRenderers.get(line), new LineGutterIconRendererProcessor() {
@Override
public void process(int x, int y, GutterMark r) {
if (result.isNull() && r.equals(renderer)) {
result.set(new Point(x, y));
Icon icon = scaleIcon(r.getIcon());
result.set(new Point(x + icon.getIconWidth() / 2, y + icon.getIconHeight() / 2));
}
}
}, true);
@@ -3149,6 +3149,7 @@ public final class EditorImpl extends UserDataHolderBase implements EditorEx, Hi
+ "', allow caret inside tab: " + mySettings.isCaretInsideTabs()
+ ", allow caret after line end: " + mySettings.isVirtualSpace()
+ ", soft wraps: " + (mySoftWrapModel.isSoftWrappingEnabled() ? "on" : "off")
+ ", caret model: " + getCaretModel().dumpState()
+ ", soft wraps data: " + getSoftWrapModel().dumpState()
+ "\n\nfolding data: " + getFoldingModel().dumpState()
+ (myDocument instanceof DocumentImpl ? "\n\ndocument info: " + ((DocumentImpl)myDocument).dumpState() : "")
@@ -362,6 +362,8 @@ class EditorSizeManager implements PrioritizedDocumentListener, Disposable, Fold
@NotNull
@Override
public String dumpState() {
return "[line widths: " + myLineWidths + "]";
return "[cached width: " + myWidthInPixels +
", max line with extension width: " + myMaxLineWithExtensionWidth +
", line widths: " + myLineWidths + "]";
}
}
@@ -469,6 +469,14 @@ public class EditorView implements TextDrawingCallback, Disposable, Dumpable {
@NotNull
@Override
public String dumpState() {
return "[Size manager: " + mySizeManager.dumpState() + "]";
return "[prefix text: " + myPrefixText +
", prefix attributes: " + myPrefixAttributes +
", space width: " + myPlainSpaceWidth +
", line height: " + myLineHeight +
", descent: " + myDescent +
", char height: " + myCharHeight +
", max char width: " + myMaxCharWidth +
", tab size: " + myTabSize +
" ,size manager: " + mySizeManager.dumpState() + "]";
}
}
@@ -21,7 +21,6 @@ import com.intellij.ide.plugins.PluginManager;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.TransferToPooledThreadQueue;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
@@ -51,6 +50,7 @@ import com.intellij.openapi.vfs.newvfs.impl.StubVirtualFile;
import com.intellij.psi.SingleRootFileViewProvider;
import com.intellij.testFramework.LightVirtualFile;
import com.intellij.util.*;
import com.intellij.util.concurrency.BoundedTaskExecutorService;
import com.intellij.util.containers.ConcurrentPackedBitsArray;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.io.URLUtil;
@@ -63,12 +63,15 @@ import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import org.jetbrains.ide.PooledThreadExecutor;
import java.io.*;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
@@ -245,7 +248,10 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements Persistent
if (toLog()) {
log("F: after() queued to redetect: " + files);
}
reDetectQueue.offerIfAbsent(files);
if (filesToRedetect.addAll(files)) {
awakeReDetectExecutor();
}
}
}
});
@@ -340,23 +346,38 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements Persistent
System.out.println(message + " - "+Thread.currentThread());
}
private final TransferToPooledThreadQueue<Collection<VirtualFile>> reDetectQueue = new TransferToPooledThreadQueue<Collection<VirtualFile>>("File type re-detect", Conditions.alwaysFalse(), -1, new Processor<Collection<VirtualFile>>() {
@Override
public boolean process(Collection<VirtualFile> files) {
reDetect(files);
return true;
}
});
private final BoundedTaskExecutorService reDetectExecutor = new BoundedTaskExecutorService(PooledThreadExecutor.INSTANCE, 1, this);
private final BlockingQueue<VirtualFile> filesToRedetect = new LinkedBlockingDeque<VirtualFile>();
private void awakeReDetectExecutor() {
reDetectExecutor.submit(new Runnable() {
private static final int CHUNK = 10;
@Override
public void run() {
List<VirtualFile> files = new ArrayList<VirtualFile>();
int drained = filesToRedetect.drainTo(files, CHUNK);
reDetect(files);
if (drained == CHUNK) {
awakeReDetectExecutor();
}
}
});
}
@TestOnly
public void drainReDetectQueue() {
reDetectQueue.waitFor();
try {
reDetectExecutor.waitAllTasksExecuted();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@TestOnly
@NotNull
Collection<VirtualFile> dumpReDetectQueue() {
return ContainerUtil.flatten(reDetectQueue.dump());
return new ArrayList<VirtualFile>(filesToRedetect);
}
@TestOnly
@@ -603,6 +624,7 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements Persistent
private volatile FileAttribute autoDetectedAttribute;
// read auto-detection flags from the persistent FS file attributes. If file attributes are absent, return 0 for flags
// returns three bits value for AUTO_DETECTED_AS_TEXT_MASK, AUTO_DETECTED_AS_BINARY_MASK and AUTO_DETECT_WAS_RUN_MASK bits
// protected for Upsource
protected byte readFlagsFromCache(@NotNull VirtualFile file) {
DataInputStream stream = autoDetectedAttribute.readAttribute(file);
boolean wasAutoDetectRun = false;
@@ -627,6 +649,7 @@ public class FileTypeManagerImpl extends FileTypeManagerEx implements Persistent
// store auto-detection flags to the persistent FS file attributes
// writes AUTO_DETECTED_AS_TEXT_MASK, AUTO_DETECTED_AS_BINARY_MASK bits only
// protected for Upsource
protected void writeFlagsToCache(@NotNull VirtualFile file, int flags) {
DataOutputStream stream = autoDetectedAttribute.writeAttribute(file);
try {
@@ -17,6 +17,7 @@ package com.intellij.openapi.project.impl;
import com.intellij.ide.impl.ProjectUtil;
import com.intellij.openapi.application.JBProtocolCommand;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import org.jetbrains.annotations.NotNull;
@@ -36,9 +37,7 @@ public class JBProtocolOpenProjectCommand extends JBProtocolCommand {
@Override
public void perform(String target, Map<String, String> parameters) {
String path = URLDecoder.decode(target);
if (path.startsWith(LocalFileSystem.PROTOCOL_PREFIX)) {
path = path.substring(LocalFileSystem.PROTOCOL_PREFIX.length());
}
path = StringUtil.trimStart(path, LocalFileSystem.PROTOCOL_PREFIX);
ProjectUtil.openProject(path, null, true);
}
}
@@ -22,9 +22,9 @@
*/
package com.intellij.openapi.vfs.encoding;
import com.intellij.concurrency.JobSchedulerImpl;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.impl.TransferToPooledThreadQueue;
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
@@ -48,13 +48,14 @@ import com.intellij.openapi.vfs.CharsetToolkit;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Alarm;
import com.intellij.util.ObjectUtils;
import com.intellij.util.Processor;
import com.intellij.util.concurrency.BoundedTaskExecutorService;
import com.intellij.util.xmlb.annotations.Attribute;
import gnu.trove.Equality;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.ide.PooledThreadExecutor;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
@@ -99,19 +100,7 @@ public class EncodingManagerImpl extends EncodingManager implements PersistentSt
private final Alarm updateEncodingFromContent = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, this);
private static final Key<Charset> CACHED_CHARSET_FROM_CONTENT = Key.create("CACHED_CHARSET_FROM_CONTENT");
private final TransferToPooledThreadQueue<Reference<Document>> myChangedDocuments = new TransferToPooledThreadQueue<Reference<Document>>(
"Encoding detection thread",
ApplicationManager.getApplication().getDisposed(),
-1, // drain the whole queue, do not reschedule
new Processor<Reference<Document>>() {
@Override
public boolean process(Reference<Document> ref) {
Document document = ref.get();
if (document == null) return true; // document gced, don't bother
handleDocument(document);
return true;
}
});
private final BoundedTaskExecutorService changedDocumentExecutor = new BoundedTaskExecutorService(PooledThreadExecutor.INSTANCE, JobSchedulerImpl.CORES_COUNT, this);
public EncodingManagerImpl(@NotNull EditorFactory editorFactory) {
editorFactory.getEventMulticaster().addDocumentListener(new DocumentAdapter() {
@@ -130,15 +119,22 @@ public class EncodingManagerImpl extends EncodingManager implements PersistentSt
@NonNls public static final String PROP_CACHED_ENCODING_CHANGED = "cachedEncoding";
private static final Key<String> DETECTING_ENCODING_KEY = Key.create("DETECTING_ENCODING_KEY");
private void handleDocument(@NotNull final Document document) {
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile == null) return;
Project project = guessProject(virtualFile);
if (project != null && project.isDisposed()) return;
Charset charset = LoadTextUtil.charsetFromContentOrNull(project, virtualFile, document.getImmutableCharSequence());
Charset oldCached = getCachedCharsetFromContent(document);
if (!Comparing.equal(charset, oldCached)) {
setCachedCharsetFromContent(charset, oldCached, document);
if (document.getUserData(DETECTING_ENCODING_KEY) == null) return;
try {
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile == null) return;
Project project = guessProject(virtualFile);
if (project != null && project.isDisposed()) return;
Charset charset = LoadTextUtil.charsetFromContentOrNull(project, virtualFile, document.getImmutableCharSequence());
Charset oldCached = getCachedCharsetFromContent(document);
if (!Comparing.equal(charset, oldCached)) {
setCachedCharsetFromContent(charset, oldCached, document);
}
}
finally {
document.putUserData(DETECTING_ENCODING_KEY, null);
}
}
@@ -178,7 +174,23 @@ public class EncodingManagerImpl extends EncodingManager implements PersistentSt
}
void queueUpdateEncodingFromContent(@NotNull Document document) {
myChangedDocuments.offerIfAbsent(new WeakReference<Document>(document), REFERENCE_EQUALITY);
document.putUserData(DETECTING_ENCODING_KEY, "");
changedDocumentExecutor.execute(new DocumentEncodingDetectRequest(document));
}
private static class DocumentEncodingDetectRequest implements Runnable {
private final Reference<Document> ref;
private DocumentEncodingDetectRequest(@NotNull Document document) {
ref = new WeakReference<Document>(document);
}
@Override
public void run() {
Document document = ref.get();
if (document == null) return; // document gced, don't bother
((EncodingManagerImpl)getInstance()).handleDocument(document);
}
}
@Override
@@ -220,7 +232,7 @@ public class EncodingManagerImpl extends EncodingManager implements PersistentSt
}
public void clearDocumentQueue() {
myChangedDocuments.stop();
changedDocumentExecutor.clearAndCancelAll();
}
@Nullable
@@ -158,9 +158,7 @@ public abstract class LocalFileSystemBase extends LocalFileSystem {
final String[] names = new String[roots.length];
for (int i = 0; i < names.length; i++) {
String name = roots[i].getPath();
if (name.endsWith(File.separator)) {
name = name.substring(0, name.length() - File.separator.length());
}
name = StringUtil.trimEnd(name, File.separator);
names[i] = name;
}
return names;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,7 @@
*/
package com.intellij.openapi.vfs.newvfs;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.application.AccessToken;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
@@ -26,11 +27,12 @@ import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.DumbAwareRunnable;
import com.intellij.openapi.vfs.VfsBundle;
import com.intellij.openapi.vfs.newvfs.events.VFileEvent;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.concurrency.BoundedTaskExecutorService;
import com.intellij.util.io.storage.HeavyProcessLatch;
import gnu.trove.TLongObjectHashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.ide.PooledThreadExecutor;
import java.util.Collections;
import java.util.concurrent.ExecutorService;
@@ -38,10 +40,10 @@ import java.util.concurrent.ExecutorService;
/**
* @author max
*/
public class RefreshQueueImpl extends RefreshQueue {
public class RefreshQueueImpl extends RefreshQueue implements Disposable {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vfs.newvfs.RefreshQueueImpl");
private final ExecutorService myQueue = ConcurrencyUtil.newSingleThreadExecutor("FS Synchronizer");
private final ExecutorService myQueue = new BoundedTaskExecutorService(PooledThreadExecutor.INSTANCE, 1, this);
private final ProgressIndicator myRefreshIndicator = RefreshProgress.create(VfsBundle.message("file.synchronize.progress"));
private final TLongObjectHashMap<RefreshSession> mySessions = new TLongObjectHashMap<RefreshSession>();
private final FrequentEventDetector myEventCounter = new FrequentEventDetector(100, 100, FrequentEventDetector.Level.ERROR);
@@ -149,4 +151,9 @@ public class RefreshQueueImpl extends RefreshQueue {
return !refreshQueue.mySessions.isEmpty();
}
}
@Override
public void dispose() {
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@ import com.intellij.openapi.ui.TextComponentAccessor;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.DocumentAdapter;
import org.jetbrains.annotations.NotNull;
@@ -88,9 +89,7 @@ public class LocationNameFieldsBinding {
}
myModifyingLocation = true;
String path = locationField.getText().trim();
if (path.endsWith(File.separator)) {
path = path.substring(0, path.length() - File.separator.length());
}
path = StringUtil.trimEnd(path, File.separator);
int ind = path.lastIndexOf(File.separator);
if (ind != -1) {
String projectName = path.substring(ind + 1, path.length());
@@ -15,6 +15,7 @@
*/
package com.intellij.openapi.editor;
import com.intellij.diagnostic.Dumpable;
import com.intellij.openapi.application.ex.PathManagerEx;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.intellij.openapi.editor.event.DocumentEvent;
@@ -52,6 +53,7 @@ public class EditorPaintingTest extends AbstractEditorTest {
public void testWholeLineHighlighterAtDocumentEnd() throws Exception {
initText("foo");
addLineHighlighter(0, 3, HighlighterLayer.WARNING, null, Color.red);
System.out.println(((Dumpable)myEditor).dumpState()); // temporary code to find the cause of blinking
checkResult();
}
@@ -0,0 +1,174 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.concurrency;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.ConcurrencyUtil;
import com.intellij.util.TimeoutUtil;
import junit.framework.TestCase;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class BoundedTaskExecutorTest extends TestCase {
public void testReallyBound() throws InterruptedException, ExecutionException {
for (int maxTasks=1; maxTasks<5;maxTasks++) {
System.out.println("maxTasks = " + maxTasks);
ExecutorService backendExecutor = Executors.newCachedThreadPool(ConcurrencyUtil.newNamedThreadFactory("maxTasks = " + maxTasks));
BoundedTaskExecutorService executor = new BoundedTaskExecutorService(backendExecutor, maxTasks);
AtomicInteger running = new AtomicInteger();
AtomicInteger max = new AtomicInteger();
AtomicInteger executed = new AtomicInteger();
int N = 10000;
for (int i = 0; i < N; i++) {
executor.execute(() -> {
int r = running.incrementAndGet();
try {
TimeoutUtil.sleep(1);
max.accumulateAndGet(r, Math::max);
executed.incrementAndGet();
}
finally {
running.decrementAndGet();
}
});
}
executor.waitAllTasksExecuted();
assertEquals(0, executor.shutdownNow().size());
assertTrue(executor.awaitTermination(10, TimeUnit.SECONDS));
backendExecutor.shutdownNow();
assertTrue(backendExecutor.awaitTermination(100, TimeUnit.SECONDS));
assertEquals(maxTasks, max.get());
assertEquals(N, executed.get());
}
}
public void testCallableReallyReturnsValue() throws Exception{
ExecutorService backendExecutor = Executors.newCachedThreadPool(ConcurrencyUtil.newNamedThreadFactory(getName()));
BoundedTaskExecutorService executor = new BoundedTaskExecutorService(backendExecutor, 1);
Future<Integer> f1 = executor.submit(() -> 42);
Integer result = f1.get();
assertEquals(42, result.intValue());
executor.shutdownNow();
assertTrue(executor.awaitTermination(1, TimeUnit.SECONDS));
backendExecutor.shutdownNow();
assertTrue(backendExecutor.awaitTermination(100, TimeUnit.SECONDS));
}
public void testEarlyCancelPreventsRunning() throws ExecutionException, InterruptedException {
AtomicBoolean run = new AtomicBoolean();
ExecutorService backendExecutor = Executors.newCachedThreadPool(ConcurrencyUtil.newNamedThreadFactory(getName()));
BoundedTaskExecutorService executor = new BoundedTaskExecutorService(backendExecutor, 1);
int delay = 500;
Future<?> s1 = executor.submit((Runnable)() -> TimeoutUtil.sleep(delay));
Future<Integer> f1 = executor.submit(() -> {
run.set(true);
return 42;
});
f1.cancel(false);
TimeoutUtil.sleep(delay+200);
assertTrue(f1.isDone());
assertTrue(f1.isCancelled());
assertFalse(run.get());
assertTrue(s1.isDone());
executor.shutdownNow();
assertTrue(executor.awaitTermination(1, TimeUnit.SECONDS));
backendExecutor.shutdownNow();
assertTrue(backendExecutor.awaitTermination(100, TimeUnit.SECONDS));
}
public void testStressWhenSomeTasksCallOtherTasksGet() throws ExecutionException, InterruptedException {
ExecutorService backendExecutor = Executors.newCachedThreadPool(ConcurrencyUtil.newNamedThreadFactory(getName()));
for (int maxSimultaneousTasks = 1; maxSimultaneousTasks<20;maxSimultaneousTasks++) {
final Disposable myDisposable = Disposer.newDisposable();
BoundedTaskExecutorService executor = new BoundedTaskExecutorService(backendExecutor, maxSimultaneousTasks, myDisposable);
AtomicInteger running = new AtomicInteger();
AtomicInteger maxThreads = new AtomicInteger();
try {
int N = 5000;
Future[] futures = new Future[N];
Random random = new Random();
for (int i = 0; i < N; i++) {
final int finalI = i;
final int finalMaxSimultaneousTasks = maxSimultaneousTasks;
futures[i] = executor.submit((Runnable)() -> {
maxThreads.accumulateAndGet(running.incrementAndGet(), Math::max);
try {
int r = random.nextInt(finalMaxSimultaneousTasks);
int prev = finalI - r;
if (prev != finalI && prev >= 0) {
try {
futures[prev].get();
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
TimeoutUtil.sleep(r);
}
finally {
running.decrementAndGet();
}
});
}
executor.waitAllTasksExecuted();
for (Future future : futures) {
assertTrue(future.isDone());
}
}
finally {
Disposer.dispose(myDisposable);
assertTrue(executor.isShutdown());
}
assertTrue("Max threads was: "+maxThreads+" but bound was: "+maxSimultaneousTasks, maxThreads.get() <= maxSimultaneousTasks);
}
backendExecutor.shutdownNow();
assertTrue(backendExecutor.awaitTermination(100, TimeUnit.SECONDS));
}
public void testSequentialSubmitsMustExecuteSequentially() throws ExecutionException, InterruptedException {
ExecutorService backendExecutor = Executors.newCachedThreadPool(ConcurrencyUtil.newNamedThreadFactory(getName()));
BoundedTaskExecutorService executor = new BoundedTaskExecutorService(backendExecutor, 1);
int N = 100000;
StringBuffer log = new StringBuffer(N*4);
StringBuffer expected = new StringBuffer(N*4);
Future[] futures = new Future[N];
for (int i = 0; i < N; i++) {
final int finalI = i;
futures[i] = executor.submit(() -> log.append(finalI).append(" "));
}
for (int i = 0; i < N; i++) {
expected.append(i).append(" ");
futures[i].get();
}
String logs = log.toString();
assertEquals(expected.toString(), logs);
executor.shutdownNow();
assertTrue(executor.awaitTermination(1, TimeUnit.SECONDS));
backendExecutor.shutdownNow();
assertTrue(backendExecutor.awaitTermination(100, TimeUnit.SECONDS));
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -83,9 +83,7 @@ public class ProjectUtilCore {
}
String projectName = FileUtil.toSystemIndependentName(location);
if (projectName.endsWith("/")) {
projectName = projectName.substring(0, projectName.length() - 1);
}
projectName = StringUtil.trimEnd(projectName, "/");
final int lastSlash = projectName.lastIndexOf('/');
if (lastSlash >= 0 && lastSlash + 1 < projectName.length()) {
@@ -17,6 +17,7 @@
package com.intellij.openapi.projectRoots.impl;
import com.intellij.openapi.projectRoots.ex.ProjectRoot;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
@@ -58,9 +59,7 @@ public class SimpleProjectRoot implements ProjectRoot {
@NotNull
public String getPresentableString() {
String path = VirtualFileManager.extractPath(myUrl);
if (path.endsWith(URLUtil.JAR_SEPARATOR)) {
path = path.substring(0, path.length() - URLUtil.JAR_SEPARATOR.length());
}
path = StringUtil.trimEnd(path, URLUtil.JAR_SEPARATOR);
return path.replace('/', File.separatorChar);
}
@@ -39,8 +39,8 @@ import java.util.concurrent.atomic.AtomicBoolean
abstract class DebugProcessImpl<C : VmConnection<*>>(session: XDebugSession,
val connection: C,
private val editorsProvider: XDebuggerEditorsProvider,
private val smartStepIntoHandler: XSmartStepIntoHandler<*>?,
protected val executionResult: ExecutionResult?) : XDebugProcess(session) {
private val smartStepIntoHandler: XSmartStepIntoHandler<*>? = null,
protected val executionResult: ExecutionResult? = null) : XDebugProcess(session) {
protected val repeatStepInto: AtomicBoolean = AtomicBoolean()
@Volatile protected var lastStep: StepAction? = null
@Volatile protected var lastCallFrame: CallFrame? = null
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -237,11 +237,9 @@ public class TestsPresentationUtil {
}
if (parentStartsWith) {
presentationCandidate = name.substring(parentName.length());
// remove "." separator
if (presentationCandidate.startsWith(".")) {
presentationCandidate = presentationCandidate.substring(1);
}
presentationCandidate = StringUtil.trimStart(presentationCandidate, ".");
}
}
}
@@ -45,7 +45,7 @@ import com.intellij.openapi.command.undo.UndoManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
import com.intellij.openapi.editor.impl.ComplementaryFontsRegistry;
import com.intellij.openapi.editor.impl.EditorFactoryImpl;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.extensions.Extensions;
@@ -303,7 +303,9 @@ public abstract class LightPlatformTestCase extends UsefulTestCase implements Da
VirtualFilePointerManagerImpl filePointerManager = (VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance();
filePointerManager.storePointers();
System.out.println("soft wraps enabled: " + EditorSettingsExternalizable.getInstance().isUseSoftWraps()); // temporary code to find out cause of test blinking
// various tests can use different mocking techniques for font-related code
// so we must reset our font cache, to avoid potential impact of tests on other tests
ComplementaryFontsRegistry.resetCaches();
}
});
}
@@ -79,6 +79,7 @@ public class ThreadTracker {
wellKnownOffenders.add("IDEA Test Case Thread");
wellKnownOffenders.add("Image Fetcher ");
wellKnownOffenders.add("Java2D Disposer");
wellKnownOffenders.add("JDI Target VM Interface");
wellKnownOffenders.add("JobScheduler FJ pool ");
wellKnownOffenders.add("JPS thread pool");
wellKnownOffenders.add("Keep-Alive-Timer");
@@ -149,10 +149,6 @@ public abstract class UsefulTestCase extends TestCase {
ApplicationInfoImpl.setInPerformanceTest(isPerformanceTest);
// turn off Disposer debugging for performance tests
oldDisposerDebug = Disposer.setDebugMode(Disposer.isDebugMode() && !isPerformanceTest);
// various tests can use different mocking techniques for font-related code
// so we must reset our font cache, to avoid potential impact of tests on other tests
ComplementaryFontsRegistry.resetCaches();
}
@Override
@@ -91,12 +91,12 @@ class ProjectRule() : ExternalResource() {
}
}
override final fun before() {
override public final fun before() {
IdeaTestApplication.getInstance()
TestRunnerUtil.replaceIdeEventQueueSafely()
}
override fun after() {
override public fun after() {
if (projectOpened.compareAndSet(true, false)) {
sharedProject?.let { runInEdtAndWait { (ProjectManager.getInstance() as ProjectManagerImpl).closeProject(it, false, false, false) } }
}
@@ -433,18 +433,19 @@ public final class IconLoader {
scaledIcons = new HashMap<Float, Icon>(1);
}
Icon result = scaledIcons.get(scaleFactor);
// TODO: consider clearing the cache on SCALE change
Icon result = scaledIcons.get(scaleFactor * SCALE);
if (result != null) {
return result;
}
final Image image = ImageLoader.loadFromUrl(myUrl, UIUtil.isUnderDarcula(), scaleFactor >= 1.5f, filter);
final Image image = ImageLoader.loadFromUrl(myUrl, UIUtil.isUnderDarcula(), (scaleFactor * SCALE) >= 1.5f, filter);
if (image != null) {
int width = (int)(getIconWidth() * scaleFactor);
int height = (int)(getIconHeight() * scaleFactor);
final BufferedImage resizedImage = Scalr.resize(ImageUtil.toBufferedImage(image), Scalr.Method.ULTRA_QUALITY, width, height);
result = getIcon(resizedImage);
scaledIcons.put(scaleFactor, result);
scaledIcons.put(scaleFactor * SCALE, result);
return result;
}
@@ -1,9 +1,25 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.util.io;
import com.intellij.openapi.util.text.StringUtil;
import gnu.trove.THashMap;
import gnu.trove.TIntObjectHashMap;
import java.util.*;
import java.util.Map;
/**
* @author yole
@@ -40,12 +56,12 @@ public class UniqueNameBuilder<T> {
private final Node myRootNode = new Node('\0', null);
public void addPath(T key, String value) {
if (value.startsWith(myRoot)) value = value.substring(myRoot.length());
value = StringUtil.trimStart(value, myRoot);
myPaths.put(key, value);
Node current = myRootNode;
for(int i = value.length() - 1; i >=0; --i) {
for (int i = value.length() - 1; i >= 0; --i) {
char ch = value.charAt(i);
Node node = current.myChildren.get(ch);
if (node == null) current.myChildren.put(ch, node = new Node(ch, current));
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -19,6 +19,7 @@
*/
package com.intellij.ui;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -108,9 +109,7 @@ public class ColorUtil {
* @return Color object
*/
public static Color fromHex(String str) {
if (str.startsWith("#")) {
str = str.substring(1);
}
str = StringUtil.trimStart(str, "#");
if (str.length() == 3) {
return new Color(
17 * Integer.valueOf(String.valueOf(str.charAt(0)), 16).intValue(),
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,90 +15,180 @@
*/
package com.intellij.util.concurrency;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Disposer;
import com.intellij.util.Function;
import com.intellij.util.ReflectionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;
import java.util.Queue;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class BoundedTaskExecutor implements Executor {
protected final Executor myBackendExecutor;
/**
* ExecutorService which limits the number of tasks running simultaneously.
* The number of submitted tasks is unrestricted.
*/
public class BoundedTaskExecutor extends AbstractExecutorService {
private volatile boolean myShutdown;
private final Executor myBackendExecutor;
private final int myMaxTasks;
private final AtomicInteger myInProgress = new AtomicInteger(0);
private final Queue<FutureTask> myTaskQueue = new LinkedBlockingQueue<FutureTask>();
private final Runnable USER_TASK_RUNNER = new Runnable() {
@Override
public void run() {
final FutureTask task = myTaskQueue.poll();
try {
if (task != null && !task.isCancelled()) {
task.run();
}
}
finally {
myInProgress.decrementAndGet();
if (!myTaskQueue.isEmpty()) {
processQueue();
}
}
}
};
// number of tasks running (or trying to run)
private final AtomicInteger myInProgress = new AtomicInteger();
private final BlockingQueue<Runnable> myTaskQueue = new LinkedBlockingQueue<Runnable>();
public BoundedTaskExecutor(@NotNull Executor backendExecutor, int maxSimultaneousTasks) {
myBackendExecutor = backendExecutor;
assert maxSimultaneousTasks >= 1 : maxSimultaneousTasks;
myMaxTasks = Math.max(maxSimultaneousTasks, 1);
if (maxSimultaneousTasks < 1) {
throw new IllegalArgumentException("maxSimultaneousTasks must be >=1 but got: "+maxSimultaneousTasks);
}
myMaxTasks = maxSimultaneousTasks;
}
/**
* Constructor which automatically shuts down this executor when {@code parent} is disposed.
*/
public BoundedTaskExecutor(@NotNull Executor backendExecutor, int maxSimultaneousTasks, @NotNull Disposable parent) {
this(backendExecutor, maxSimultaneousTasks);
Disposer.register(parent, new Disposable() {
@Override
public void dispose() {
shutdownNow();
}
});
}
// for diagnostics
public static Object info(Object task) {
if (task instanceof FutureTask) {
task = ReflectionUtil.getField(task.getClass(), task, Callable.class, "callable");
}
if (task instanceof Callable && task.getClass().getName().equals("java.util.concurrent.Executors$RunnableAdapter")) {
task = ReflectionUtil.getField(task.getClass(), task, Runnable.class, "task");
}
return task;
}
@Override
public void shutdown() {
if (myShutdown) throw new IllegalStateException("Already shutdown");
myShutdown = true;
}
@NotNull
@Override
public List<Runnable> shutdownNow() {
shutdown();
return clearAndCancelAll();
}
@Override
public boolean isShutdown() {
return myShutdown;
}
@Override
public boolean isTerminated() {
return myShutdown;
}
@Override
public boolean awaitTermination(long timeout, @NotNull TimeUnit unit) throws InterruptedException {
if (!isShutdown()) throw new IllegalStateException("you must call shutdown() first");
return true;
}
@Override
public void execute(@NotNull Runnable task) {
submit(task);
myTaskQueue.offer(task);
int inProgress = myInProgress.incrementAndGet();
tryToPollAndExecuteNext(inProgress);
}
public Future<?> submit(@NotNull Runnable task) {
return this.<Void>submit(task, null);
}
@NotNull
public <T> Future<T> submit(Runnable task, T result) {
final RunnableFuture<T> future = queueTask(new FutureTask<T>(task, result));
if (future == null) {
throw new RuntimeException("Failed to queue task: " + task);
}
return future;
}
@NotNull
public <T> Future<T> submit(@NotNull Callable<T> task) {
final RunnableFuture<T> future = queueTask(new FutureTask<T>(task));
if (future == null) {
throw new RuntimeException("Failed to queue task: " + task);
}
return future;
}
@Nullable
private <T> RunnableFuture<T> queueTask(@NotNull FutureTask<T> futureTask) {
if (myTaskQueue.offer(futureTask)) {
processQueue();
return futureTask;
}
return null;
}
protected void processQueue() {
while (true) {
final int count = myInProgress.get();
if (count >= myMaxTasks) {
return;
}
if (myInProgress.compareAndSet(count, count + 1)) {
private void tryToPollAndExecuteNext(int inProgress) {
while (!isShutdown()) {
assert inProgress > 0 : inProgress;
Runnable next;
if (inProgress <= myMaxTasks && (next = myTaskQueue.poll()) != null) {
myBackendExecutor.execute(wrap(next));
break;
}
if (myInProgress.compareAndSet(inProgress, inProgress-1)) {
break;
}
inProgress = myInProgress.get();
}
myBackendExecutor.execute(USER_TASK_RUNNER);
}
@NotNull
private Runnable wrap(@NotNull final Runnable task) {
return new Runnable() {
@Override
public void run() {
try {
task.run();
}
finally {
tryToPollAndExecuteNext(myInProgress.get());
}
}
@Override
public String toString() {
return String.valueOf(info(task));
}
};
}
@TestOnly
public void waitAllTasksExecuted() throws ExecutionException, InterruptedException {
final CountDownLatch started = new CountDownLatch(myMaxTasks);
final CountDownLatch readyToFinish = new CountDownLatch(1);
// start myMaxTasks runnables which will spread to all available executor threads
// and wait for them all to finish
List<Future> futures = ContainerUtil.map(Collections.nCopies(myMaxTasks, null), new Function<Object, Future>() {
@Override
public Future fun(Object o) {
return submit(new Runnable() {
@Override
public void run() {
try {
started.countDown();
readyToFinish.await();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
}
});
try {
started.await();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
readyToFinish.countDown();
for (Future future : futures) {
future.get();
}
}
@NotNull
public List<Runnable> clearAndCancelAll() {
List<Runnable> queued = new ArrayList<Runnable>();
myTaskQueue.drainTo(queued);
for (Runnable task : queued) {
if (task instanceof FutureTask) {
((FutureTask) task).cancel(false);
}
}
return queued;
}
}
@@ -15,145 +15,20 @@
*/
package com.intellij.util.concurrency;
import com.intellij.util.SmartList;
import com.intellij.openapi.Disposable;
import org.jetbrains.annotations.NotNull;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.ExecutorService;
/**
* @author Eugene Zhuravlev
* Date: 16-Sep-15
*/
public class BoundedTaskExecutorService extends BoundedTaskExecutor implements ExecutorService{
public class BoundedTaskExecutorService extends BoundedTaskExecutor {
public BoundedTaskExecutorService(@NotNull ExecutorService backendExecutor, int maxSimultaneousTasks) {
super(backendExecutor, maxSimultaneousTasks);
}
@Override
public void shutdown() {
getBackendExecutor().shutdown();
public BoundedTaskExecutorService(@NotNull ExecutorService backendExecutor, int maxSimultaneousTasks, @NotNull Disposable parent) {
super(backendExecutor, maxSimultaneousTasks, parent);
}
@NotNull
@Override
public List<Runnable> shutdownNow() {
return getBackendExecutor().shutdownNow();
}
@Override
public boolean isShutdown() {
return getBackendExecutor().isShutdown();
}
@Override
public boolean isTerminated() {
return getBackendExecutor().isTerminated();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return getBackendExecutor().awaitTermination(timeout, unit);
}
@NotNull
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
final List<Future<T>> futures = new SmartList<Future<T>>();
for (Callable<T> task : tasks) {
futures.add(submit(task));
}
boolean done = false;
try {
for (Future<T> future : futures) {
if (!future.isDone()) {
try {
future.get();
}
catch (ExecutionException ignored) {
}
}
}
done = true;
return futures;
}
finally {
if (!done) {
for (Future<T> future : futures) {
future.cancel(true);
}
}
}
}
@NotNull
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException {
long nanos = unit.toNanos(timeout);
final List<Future<T>> futures = new SmartList<Future<T>>();
boolean done = false;
try {
long lastCheck = System.nanoTime();
for (Callable<T> task : tasks) {
futures.add(submit(task));
}
long now = System.nanoTime();
nanos -= now - lastCheck;
if (nanos <= 0) {
return futures;
}
lastCheck = now;
for (Future<T> future : futures) {
if (!future.isDone()) {
if (nanos <= 0) {
return futures;
}
try {
future.get(nanos, TimeUnit.NANOSECONDS);
}
catch (ExecutionException ignored) {
}
catch (TimeoutException e) {
return futures;
}
now = System.nanoTime();
nanos -= now - lastCheck;
lastCheck = now;
}
}
done = true;
return futures;
}
finally {
if (!done) {
for (Future<T> future : futures) {
future.cancel(true);
}
}
}
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
throw new RuntimeException("invokeAny is not supported by this ExecutorService implementation");
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException {
throw new RuntimeException("invokeAny is not supported by this ExecutorService implementation");
}
@NotNull
private ExecutorService getBackendExecutor() {
return (ExecutorService)myBackendExecutor;
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -201,9 +201,7 @@ public class ClasspathCache {
}
static String transformName(String name) {
if (name.endsWith("/")) {
name = name.substring(0, name.length() - 1);
}
name = StringUtil.trimEnd(name, "/");
name = name.substring(name.lastIndexOf('/') + 1);
if (name.endsWith(UrlClassLoader.CLASS_EXTENSION)) {
@@ -16,6 +16,7 @@
package com.intellij.util.lang;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
@@ -69,7 +70,7 @@ class FileLoader extends Loader {
private String getRelativeResourcePath(final String absFilePath) {
String relativePath = absFilePath.substring(myRootDirAbsolutePath.length());
relativePath = relativePath.replace(File.separatorChar, '/');
if (relativePath.startsWith("/")) relativePath = relativePath.substring(1);
relativePath = StringUtil.trimStart(relativePath, "/");
return relativePath;
}
@@ -20,6 +20,7 @@ import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.win32.IdeaWin32;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.WeakStringInterner;
@@ -273,7 +274,7 @@ public class UrlClassLoader extends ClassLoader {
@Nullable
private Resource _getResource(final String name) {
String n = name;
if (n.startsWith("/")) n = n.substring(1);
n = StringUtil.trimStart(n, "/");
return getClassPath().getResource(n, true);
}
@@ -73,15 +73,19 @@ public class UnifiedDiffWriter {
lineSeparator);
for(PatchLine line: hunk.getLines()) {
char prefixChar = ' ';
switch(line.getType()) {
case ADD: prefixChar = '+'; break;
case REMOVE: prefixChar = '-'; break;
case CONTEXT: prefixChar = ' '; break;
switch (line.getType()) {
case ADD:
prefixChar = '+';
break;
case REMOVE:
prefixChar = '-';
break;
case CONTEXT:
prefixChar = ' ';
break;
}
String text = line.getText();
if (text.endsWith("\n")) {
text = text.substring(0, text.length()-1);
}
text = StringUtil.trimEnd(text, "\n");
writeLine(writer, text, prefixChar);
if (line.isSuppressNewLine()) {
writer.write(lineSeparator + NO_NEWLINE_SIGNATURE + lineSeparator);
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -25,6 +25,7 @@ import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.CheckinProjectPanel;
import com.intellij.openapi.vcs.CodeSmellDetector;
import com.intellij.openapi.vcs.VcsBundle;
@@ -33,13 +34,11 @@ import com.intellij.openapi.vcs.changes.CommitExecutor;
import com.intellij.openapi.vcs.ui.RefreshableOnComponent;
import com.intellij.ui.NonFocusableCheckBox;
import com.intellij.util.PairConsumer;
import com.intellij.util.PlatformUtils;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.text.MessageFormat;
import java.util.List;
/**
@@ -97,14 +96,14 @@ public class CodeAnalysisBeforeCheckinHandler extends CheckinHandler {
int errorCount = collectErrors(codeSmells);
int warningCount = codeSmells.size() - errorCount;
String commitButtonText = executor != null ? executor.getActionText() : myCheckinPanel.getCommitActionName();
if (commitButtonText.endsWith("...")) {
commitButtonText = commitButtonText.substring(0, commitButtonText.length()-3);
}
commitButtonText = StringUtil.trimEnd(commitButtonText, "...");
final int answer = Messages.showYesNoCancelDialog(myProject,
VcsBundle.message("before.commit.files.contain.code.smells.edit.them.confirm.text", errorCount, warningCount),
VcsBundle.message("code.smells.error.messages.tab.name"), VcsBundle.message("code.smells.review.button"),
commitButtonText, CommonBundle.getCancelButtonText(), UIUtil.getWarningIcon());
VcsBundle.message("before.commit.files.contain.code.smells.edit.them.confirm.text",
errorCount, warningCount),
VcsBundle.message("code.smells.error.messages.tab.name"),
VcsBundle.message("code.smells.review.button"),
commitButtonText, CommonBundle.getCancelButtonText(), UIUtil.getWarningIcon());
if (answer == Messages.YES) {
CodeSmellDetector.getInstance(myProject).showCodeSmellErrors(codeSmells);
return ReturnResult.CLOSE_WINDOW;
@@ -33,6 +33,7 @@ import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.CheckinProjectPanel;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.VcsConfiguration;
@@ -174,9 +175,7 @@ public class TodoCheckinHandler extends CheckinHandler {
private ReturnResult showResults(final TodoCheckinHandlerWorker worker, CommitExecutor executor) {
String commitButtonText = executor != null ? executor.getActionText() : myCheckinProjectPanel.getCommitActionName();
if (commitButtonText.endsWith("...")) {
commitButtonText = commitButtonText.substring(0, commitButtonText.length()-3);
}
commitButtonText = StringUtil.trimEnd(commitButtonText, "...");
final String text = createMessage(worker);
final String[] buttons;
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2012 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -54,11 +54,10 @@ public abstract class EditBreakpointActionHandler extends DebuggerActionHandler
public void editBreakpoint(@NotNull Project project, @NotNull Editor editor, @NotNull Object breakpoint, @NotNull GutterIconRenderer breakpointGutterRenderer) {
if (BreakpointsDialogFactory.getInstance(project).isBreakpointPopupShowing()) return;
EditorGutterComponentEx gutterComponent = ((EditorEx)editor).getGutterComponentEx();
Point point = gutterComponent.getPoint(breakpointGutterRenderer);
if (point == null) return;
final Icon icon = breakpointGutterRenderer.getIcon();
Point whereToShow = new Point(point.x + icon.getIconWidth() / 2, point.y + icon.getIconHeight() / 2);
doShowPopup(project, gutterComponent, whereToShow, breakpoint);
Point point = gutterComponent.getCenterPoint(breakpointGutterRenderer);
if (point != null) {
doShowPopup(project, gutterComponent, point, breakpoint);
}
}
public void editBreakpoint(@NotNull Project project, @NotNull JComponent parent, @NotNull Point whereToShow, @NotNull BreakpointItem breakpoint) {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,6 +15,7 @@
*/
package com.siyeh.ipp.integer;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiLiteralExpression;
import com.intellij.psi.PsiType;
@@ -39,9 +40,7 @@ class ConvertToScientificNotationPredicate implements PsiElementPredicate {
return false;
}
text = text.toLowerCase();
if (text.startsWith("-")) {
text = text.substring(1);
}
text = StringUtil.trimStart(text, "-");
if (!text.contains(".") && text.startsWith("0")) {
return false; //Octal integer
}
@@ -44,6 +44,7 @@ import com.intellij.openapi.util.Clock;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VirtualFileManager;
@@ -468,9 +469,7 @@ public final class AntBuildMessageView extends JPanel implements DataProvider, O
}
private static AntMessage createErrorMessage(int priority, String text) {
if (text.startsWith(FILE_PREFIX)) {
text = text.substring(FILE_PREFIX.length());
}
text = StringUtil.trimStart(text, FILE_PREFIX);
int afterLineNumberIndex = text.indexOf(": "); // end of file_name_and_line_number sequence
if (afterLineNumberIndex != -1) {
@@ -30,7 +30,10 @@ import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VfsUtilCore;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiPackage;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.rt.coverage.data.ClassData;
import com.intellij.rt.coverage.data.LineCoverage;
@@ -523,7 +526,7 @@ public class PackageAnnotator {
private static String getSourceToplevelFQName(String classFQVMName) {
final int index = classFQVMName.indexOf('$');
if (index > 0) classFQVMName = classFQVMName.substring(0, index);
if (classFQVMName.startsWith("/")) classFQVMName = classFQVMName.substring(1);
classFQVMName = StringUtil.trimStart(classFQVMName, "/");
return classFQVMName.replaceAll("/", ".");
}
@@ -660,22 +660,17 @@ public class CvsUtil {
}
public static String getRelativeRepositoryPath(String repository, String serverRoot) {
public static String getRelativeRepositoryPath(String repository, String serverRoot) {
repository = repository.replace(File.separatorChar, '/');
serverRoot = serverRoot.replace(File.separatorChar, '/');
if (repository.startsWith(serverRoot)) {
repository = repository.substring(serverRoot.length());
if (repository.startsWith("/")) {
repository = repository.substring(1);
}
repository = StringUtil.trimStart(repository, "/");
}
if (repository.startsWith("./")) {
repository = repository.substring(2);
}
repository = StringUtil.trimStart(repository, "./");
return repository;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,6 +16,7 @@
package com.intellij.cvsSupport2.changeBrowser;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.Nullable;
import org.netbeans.lib.cvsclient.command.log.LogInformation;
@@ -66,12 +67,8 @@ public class LogInformationWrapper {
private static LogInformationWrapper buildWrapper(LogInformation log, String rcsFileName, int length) {
String relativePath = rcsFileName.substring(length);
if (relativePath.startsWith("/")) {
relativePath = relativePath.substring(1);
}
if (relativePath.endsWith(CVS_REPOSITORY_FILE_POSTFIX)) {
relativePath = relativePath.substring(0, relativePath.length() - CVS_REPOSITORY_FILE_POSTFIX.length());
}
relativePath = StringUtil.trimStart(relativePath, "/");
relativePath = StringUtil.trimEnd(relativePath, CVS_REPOSITORY_FILE_POSTFIX);
return new LogInformationWrapper(relativePath, log.getRevisionList(), log.getAllSymbolicNames());
}
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2011 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -189,9 +189,7 @@ public class CvsApplicationLevelConfiguration implements NamedComponent, JDOMExt
try {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith("/1 ")) {
line = line.substring(3);
}
line = StringUtil.trimStart(line, "/1 ");
final int sepPosition = line.indexOf(' ');
if (sepPosition > 0) {
final String cvsRoot = line.substring(0, sepPosition);
@@ -1,5 +1,5 @@
/*
* Copyright 2011-2013 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@ package com.intellij.cvsSupport2.ui;
import com.intellij.CvsBundle;
import com.intellij.openapi.ui.InputException;
import com.intellij.openapi.ui.TextFieldWithBrowseButton;
import com.intellij.openapi.util.text.StringUtil;
import javax.swing.*;
@@ -44,9 +45,7 @@ public class FormUtils {
private static String getLabelText(JComponent field) {
final JLabel label = (JLabel)field.getClientProperty("labeledBy");
String text = label.getText();
if (text.endsWith(":")) {
text = text.substring(0, text.length() - 1);
}
text = StringUtil.trimEnd(text, ":");
return text;
}
@@ -12,6 +12,8 @@
*/
package org.netbeans.lib.cvsclient.command.status;
import com.intellij.openapi.util.text.StringUtil;
import org.jetbrains.annotations.NonNls;
import org.netbeans.lib.cvsclient.command.AbstractMessageParser;
import org.netbeans.lib.cvsclient.event.IEventSender;
import org.netbeans.lib.cvsclient.file.AbstractFileObject;
@@ -19,7 +21,6 @@ import org.netbeans.lib.cvsclient.file.FileObject;
import org.netbeans.lib.cvsclient.file.FileStatus;
import org.netbeans.lib.cvsclient.file.ICvsFileSystem;
import org.netbeans.lib.cvsclient.util.BugLog;
import org.jetbrains.annotations.NonNls;
import java.io.File;
import java.util.ArrayList;
@@ -135,9 +136,7 @@ final class StatusMessageParser extends AbstractMessageParser {
final String statusString = line.substring(statusIndex + STATUS.length());
final FileStatus status = FileStatus.getStatusForString(statusString);
String fileName = line.substring(FILE.length(), statusIndex).trim();
if (fileName.startsWith(NO_FILE)) {
fileName = fileName.substring(NO_FILE.length());
}
fileName = StringUtil.trimStart(fileName, NO_FILE);
outputDone();
+3 -2
View File
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2010 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -22,6 +22,7 @@
*/
package org.jetbrains.idea.devkit.dom.generator;
import com.intellij.openapi.util.text.StringUtil;
import org.apache.xerces.xs.XSObject;
import java.util.HashMap;
@@ -150,7 +151,7 @@ public class Util {
public static String toDefXmlTagName(String tname) {
String xmlName = tname;
if (xmlName.endsWith(TYPE_SUFFIX)) xmlName = xmlName.substring(0, xmlName.length() - TYPE_SUFFIX.length());
xmlName = StringUtil.trimEnd(xmlName, TYPE_SUFFIX);
return xmlName;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@ import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
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.ui.JBColor;
@@ -63,16 +64,16 @@ public class UseJBColorInspection extends InternalInspection {
if (text.contains(".")) {
text = text.substring(text.lastIndexOf('.'));
}
if (text.startsWith(".")) {
text = text.substring(1);
}
text = StringUtil.trimStart(text, ".");
if (text.equalsIgnoreCase("lightGray")) {
text = "LIGHT_GRAY";
} else if (text.equalsIgnoreCase("darkGray")) {
}
else if (text.equalsIgnoreCase("darkGray")) {
text = "DARK_GRAY";
}
final ProblemDescriptor descriptor = holder.getManager()
.createProblemDescriptor(expression, "Change to JBColor." + text.toUpperCase(), new ConvertToJBColorConstantQuickFix(text.toUpperCase()),
.createProblemDescriptor(expression, "Change to JBColor." + text.toUpperCase(),
new ConvertToJBColorConstantQuickFix(text.toUpperCase()),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING, isOnTheFly);
holder.registerProblem(descriptor);
}
@@ -24,6 +24,7 @@ import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiFile;
import com.intellij.psi.SmartPsiElementPointer;
@@ -62,9 +63,7 @@ abstract class AbstractRegisterFix implements LocalQuickFix, DescriptorUtil.Patc
protected static String filterMessage(String message) {
if (message == null) return null;
@NonNls String ioExceptionPrefix = "java.io.IOException:";
if (message.startsWith(ioExceptionPrefix)) {
message = message.substring(ioExceptionPrefix.length());
}
message = StringUtil.trimStart(message, ioExceptionPrefix);
return message;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -241,9 +241,7 @@ public class TestDataGuessByExistingFilesUtil {
if (result == null) {
return null;
}
if (result.endsWith("Test")) {
result = result.substring(0, result.length() - "Test".length());
}
result = StringUtil.trimEnd(result, "Test");
int i = result.lastIndexOf('.');
if (i >= 0) {
result = result.substring(i + 1);
@@ -16,29 +16,24 @@
package org.jetbrains.idea.eclipse.util;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.text.StringUtil;
public class PathUtil {
public static String normalize(String path) {
path = FileUtil.toSystemIndependentName(path);
if (path.endsWith("/")) {
path = path.substring(0, path.length() - 1);
}
path = StringUtil.trimEnd(path, "/");
while (path.contains("/./")) {
path = path.replace("/./", "/");
}
if (path.startsWith("./")) {
path = path.substring(2);
}
if (path.endsWith("/.")) {
path = path.substring(0, path.length() - 2);
}
path = StringUtil.trimStart(path, "./");
path = StringUtil.trimEnd(path, "/.");
while ( true ) {
while (true) {
int index = path.indexOf("/..");
if ( index < 0 ) break;
int slashIndex = path.substring(0,index).lastIndexOf("/");
if ( slashIndex < 0 ) break;
path = path.substring(0, slashIndex ) + path.substring(index+3);
if (index < 0) break;
int slashIndex = path.substring(0, index).lastIndexOf("/");
if (slashIndex < 0) break;
path = path.substring(0, slashIndex) + path.substring(index + 3);
}
return path;
@@ -16,6 +16,7 @@
package git4idea.push;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.util.text.StringUtil;
import git4idea.branch.GitBranchUtil;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
@@ -51,9 +52,7 @@ class GitPushSpecParser {
}
String source = parts[0].trim();
String target = parts[1].trim();
if (source.startsWith("+")) {
source = source.substring(1);
}
source = StringUtil.trimStart(source, "+");
if (!isStarPositionValid(source, target)) {
return null;
@@ -1,5 +1,21 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package git4idea.test;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.vcs.log.Hash;
import com.intellij.vcs.log.VcsLogObjectsFactory;
@@ -46,9 +62,7 @@ class RefParser {
@NotNull
private static String getRefName(@NotNull String longRefPath) {
String tagPrefix = "tag: ";
if (longRefPath.startsWith(tagPrefix)) {
longRefPath = longRefPath.substring(tagPrefix.length());
}
longRefPath = StringUtil.trimStart(longRefPath, tagPrefix);
return longRefPath;
}
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_6" inherit-compiler-output="true">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
@@ -28,7 +28,6 @@ import com.intellij.openapi.externalSystem.model.ProjectKeys;
import com.intellij.openapi.externalSystem.model.project.*;
import com.intellij.openapi.externalSystem.model.task.TaskData;
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
import com.intellij.openapi.externalSystem.util.ExternalSystemDebugEnvironment;
import com.intellij.openapi.externalSystem.util.Order;
import com.intellij.openapi.module.EmptyModuleType;
import com.intellij.openapi.module.JavaModuleType;
@@ -47,7 +46,6 @@ import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.ContainerUtilRt;
import com.intellij.util.net.HttpConfigurable;
import com.intellij.util.text.CharArrayUtil;
import gnu.trove.TObjectHashingStrategy;
import groovy.lang.GroovyObject;
import org.codehaus.groovy.runtime.typehandling.ShortTypeHandling;
import org.gradle.tooling.ProjectConnection;
@@ -55,14 +53,11 @@ import org.gradle.tooling.model.DomainObjectSet;
import org.gradle.tooling.model.GradleModuleVersion;
import org.gradle.tooling.model.GradleTask;
import org.gradle.tooling.model.UnsupportedMethodException;
import org.gradle.tooling.model.gradle.BasicGradleProject;
import org.gradle.tooling.model.gradle.GradleBuild;
import org.gradle.tooling.model.idea.*;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.DefaultExternalDependencyId;
import org.jetbrains.plugins.gradle.ExternalDependencyId;
import org.jetbrains.plugins.gradle.model.*;
import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData;
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData;
@@ -71,11 +66,9 @@ import org.jetbrains.plugins.gradle.tooling.builder.ModelBuildScriptClasspathBui
import org.jetbrains.plugins.gradle.tooling.internal.init.Init;
import org.jetbrains.plugins.gradle.util.GradleBundle;
import org.jetbrains.plugins.gradle.util.GradleConstants;
import org.jetbrains.plugins.gradle.util.GradleUtil;
import org.slf4j.impl.Log4jLoggerFactory;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
@@ -94,7 +87,7 @@ import static org.jetbrains.plugins.gradle.service.project.GradleProjectResolver
*/
@Order(Integer.MAX_VALUE)
public class BaseGradleProjectResolverExtension implements GradleProjectResolverExtension {
private static final Logger LOG = Logger.getInstance("#" + BaseGradleProjectResolverExtension.class.getName());
private static final Logger LOG = Logger.getInstance(BaseGradleProjectResolverExtension.class);
@NotNull @NonNls private static final String UNRESOLVED_DEPENDENCY_PREFIX = "unresolved dependency - ";
@@ -164,47 +157,23 @@ public class BaseGradleProjectResolverExtension implements GradleProjectResolver
@NotNull
@Override
public DataNode<ModuleData> createModule(@NotNull IdeaModule gradleModule, @NotNull DataNode<ProjectData> projectDataNode) {
final String moduleName = gradleModule.getName();
if (moduleName == null) {
throw new IllegalStateException("Module with undefined name detected: " + gradleModule);
}
final ProjectData projectData = projectDataNode.getData();
final String mainModuleConfigPath = getModuleConfigPath(gradleModule, projectData.getLinkedExternalProjectPath());
final String ideProjectPath = resolverCtx.getIdeProjectPath();
final String relativePath;
if (FileUtil.isAncestor(projectData.getLinkedExternalProjectPath(), mainModuleConfigPath, false)) {
relativePath = FileUtil.getRelativePath(projectData.getLinkedExternalProjectPath(), mainModuleConfigPath, '/');
}
else {
relativePath = String.valueOf(FileUtil.pathHashCode(mainModuleConfigPath));
}
final String mainModuleFileDirectoryPath =
ideProjectPath == null ? mainModuleConfigPath : ideProjectPath + "/.idea/modules/" +
(relativePath == null || relativePath.equals(".") ? "" : relativePath);
if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
LOG.info(String.format(
"Creating module data ('%s') with the external config path: '%s'", gradleModule.getGradleProject().getPath(), mainModuleConfigPath
));
}
String gradlePath = gradleModule.getGradleProject().getPath();
final boolean isRootModule = StringUtil.isEmpty(gradlePath) || ":".equals(gradlePath);
String mainModuleId = isRootModule ? moduleName : gradlePath;
final ModuleData moduleData =
new ModuleData(mainModuleId, GradleConstants.SYSTEM_ID, StdModuleTypes.JAVA.getId(), moduleName,
mainModuleFileDirectoryPath, mainModuleConfigPath);
DataNode<ModuleData> mainModuleNode = projectDataNode.createChild(ProjectKeys.MODULE, moduleData);
DataNode<ModuleData> mainModuleNode = createMainModule(resolverCtx, gradleModule, projectDataNode);
final ModuleData mainModuleData = mainModuleNode.getData();
final String mainModuleConfigPath = mainModuleData.getLinkedExternalProjectPath();
final String mainModuleFileDirectoryPath = mainModuleData.getModuleFileDirectoryPath();
ExternalProject externalProject = resolverCtx.getExtraProject(gradleModule, ExternalProject.class);
if (externalProject != null) {
final String[] moduleGroup = externalProject.getSourceSets().isEmpty() ? null : new String[]{moduleData.getInternalName() + " modules"};
moduleData.setIdeModuleGroup(moduleGroup);
moduleData.setGroup(externalProject.getGroup());
moduleData.setVersion(externalProject.getVersion());
moduleData.setDescription(externalProject.getDescription());
moduleData.setArtifacts(externalProject.getArtifacts());
String gradlePath = gradleModule.getGradleProject().getPath();
final boolean isRootModule = StringUtil.isEmpty(gradlePath) || ":".equals(gradlePath);
final String[] moduleGroup;
if (isRootModule) {
moduleGroup = new String[]{mainModuleData.getInternalName()};
}
else {
moduleGroup = ArrayUtil.remove(gradlePath.split(":"), 0);
}
mainModuleData.setIdeModuleGroup(isRootModule ? null : moduleGroup);
for (ExternalSourceSet sourceSet : externalProject.getSourceSets().values()) {
final String moduleId = getModuleId(externalProject, sourceSet);
@@ -247,9 +216,10 @@ public class BaseGradleProjectResolverExtension implements GradleProjectResolver
}
}
if (StringUtil.equals(moduleData.getLinkedExternalProjectPath(), projectData.getLinkedExternalProjectPath())) {
projectData.setGroup(moduleData.getGroup());
projectData.setVersion(moduleData.getVersion());
final ProjectData projectData = projectDataNode.getData();
if (StringUtil.equals(mainModuleData.getLinkedExternalProjectPath(), projectData.getLinkedExternalProjectPath())) {
projectData.setGroup(mainModuleData.getGroup());
projectData.setVersion(mainModuleData.getVersion());
}
return mainModuleNode;
@@ -525,7 +495,7 @@ public class BaseGradleProjectResolverExtension implements GradleProjectResolver
@Override
public Set<Class> getToolingExtensionsClasses() {
return ContainerUtil.<Class>set(
// externalSystem api jar
// external-system-rt.jar
ExternalSystemSourceType.class,
// gradle-tooling-extension-api jar
ProjectImportAction.class,
@@ -648,55 +618,6 @@ public class BaseGradleProjectResolverExtension implements GradleProjectResolver
public void enhanceLocalProcessing(@NotNull List<URL> urls) {
}
@NotNull
private String getModuleConfigPath(@NotNull IdeaModule gradleModule, @NotNull String rootProjectPath) {
GradleBuild build = resolverCtx.getExtraProject(gradleModule, GradleBuild.class);
if (build != null) {
String gradlePath = gradleModule.getGradleProject().getPath();
File moduleDirPath = getModuleDirPath(build, gradlePath);
if (moduleDirPath == null) {
throw new IllegalStateException(String.format("Unable to find root directory for module '%s'", gradleModule.getName()));
}
try {
return ExternalSystemApiUtil.toCanonicalPath(moduleDirPath.getCanonicalPath());
}
catch (IOException e) {
LOG.warn("construction of the canonical path for the module fails", e);
}
}
return GradleUtil.getConfigPath(gradleModule.getGradleProject(), rootProjectPath);
}
/**
* Returns the physical path of the module's root directory (the path in the file system.)
* <p>
* It is important to note that Gradle has its own "logical" path that may or may not be equal to the physical path of a Gradle project.
* For example, the sub-project at ${projectRootDir}/apps/app will have the Gradle path :apps:app. Gradle also allows mapping physical
* paths to a different logical path. For example, in settings.gradle:
* <pre>
* include ':app'
* project(':app').projectDir = new File(rootDir, 'apps/app')
* </pre>
* In this example, sub-project at ${projectRootDir}/apps/app will have the Gradle path :app.
* </p>
*
* @param build contains information about the root Gradle project and its sub-projects. Such information includes the physical path of
* the root Gradle project and its sub-projects.
* @param path the Gradle "logical" path. This path uses colon as separator, and may or may not be equal to the physical path of a
* Gradle project.
* @return the physical path of the module's root directory.
*/
@Nullable
static File getModuleDirPath(@NotNull GradleBuild build, @NotNull String path) {
for (BasicGradleProject project : build.getProjects()) {
if (project.getPath().equals(path)) {
return project.getProjectDirectory();
}
}
return null;
}
/**
* Stores information about given directories at the given content root
*
@@ -0,0 +1,150 @@
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.gradle.service.project;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.util.UserDataHolderBase;
import org.gradle.tooling.CancellationTokenSource;
import org.gradle.tooling.ProjectConnection;
import org.gradle.tooling.model.idea.IdeaModule;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.model.ProjectImportAction;
import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings;
import java.util.Collection;
/**
* @author Vladislav.Soroka
* @since 12/8/2015
*/
public class DefaultProjectResolverContext extends UserDataHolderBase implements ProjectResolverContext {
@NotNull private final ExternalSystemTaskId myExternalSystemTaskId;
@NotNull private final String myProjectPath;
@Nullable private final GradleExecutionSettings mySettings;
@NotNull private final ExternalSystemTaskNotificationListener myListener;
private ProjectConnection myConnection;
@Nullable private CancellationTokenSource myCancellationTokenSource;
private final boolean myIsPreviewMode;
@NotNull
private ProjectImportAction.AllModels myModels;
public DefaultProjectResolverContext(@NotNull final ExternalSystemTaskId externalSystemTaskId,
@NotNull final String projectPath,
@Nullable final GradleExecutionSettings settings,
@NotNull final ExternalSystemTaskNotificationListener listener,
final boolean isPreviewMode) {
this(externalSystemTaskId, projectPath, settings, null, listener, isPreviewMode);
}
public DefaultProjectResolverContext(@NotNull final ExternalSystemTaskId externalSystemTaskId,
@NotNull final String projectPath,
@Nullable final GradleExecutionSettings settings,
final ProjectConnection connection,
@NotNull final ExternalSystemTaskNotificationListener listener,
final boolean isPreviewMode) {
myExternalSystemTaskId = externalSystemTaskId;
myProjectPath = projectPath;
mySettings = settings;
myConnection = connection;
myListener = listener;
myIsPreviewMode = isPreviewMode;
}
@NotNull
public ExternalSystemTaskId getExternalSystemTaskId() {
return myExternalSystemTaskId;
}
@Nullable
public String getIdeProjectPath() {
return mySettings != null ? mySettings.getIdeProjectPath() : null;
}
@NotNull
public String getProjectPath() {
return myProjectPath;
}
@Nullable
public GradleExecutionSettings getSettings() {
return mySettings;
}
@NotNull
public ProjectConnection getConnection() {
return myConnection;
}
public void setConnection(@NotNull ProjectConnection connection) {
myConnection = connection;
}
@Nullable
public CancellationTokenSource getCancellationTokenSource() {
return myCancellationTokenSource;
}
public void setCancellationTokenSource(@Nullable CancellationTokenSource cancellationTokenSource) {
myCancellationTokenSource = cancellationTokenSource;
}
@NotNull
public ExternalSystemTaskNotificationListener getListener() {
return myListener;
}
public boolean isPreviewMode() {
return myIsPreviewMode;
}
@NotNull
public ProjectImportAction.AllModels getModels() {
return myModels;
}
public void setModels(@NotNull ProjectImportAction.AllModels models) {
myModels = models;
}
@Nullable
public <T> T getExtraProject(Class<T> modelClazz) {
return myModels.getExtraProject(null, modelClazz);
}
@Nullable
public <T> T getExtraProject(@Nullable IdeaModule module, Class<T> modelClazz) {
return myModels.getExtraProject(module, modelClazz);
}
@NotNull
public Collection<String> findModulesWithModel(@NotNull Class modelClazz) {
return myModels.findModulesWithModel(modelClazz);
}
public boolean hasModulesWithModel(@NotNull Class modelClazz) {
return myModels.hasModulesWithModel(modelClazz);
}
public void checkCancelled() {
if (myCancellationTokenSource != null && myCancellationTokenSource.token().isCancellationRequested()) {
throw new ProcessCanceledException();
}
}
}
@@ -105,18 +105,17 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad
}
final GradleProjectResolverExtension projectResolverChain = createProjectResolverChain(settings);
DefaultProjectResolverContext resolverContext = new DefaultProjectResolverContext(id, projectPath, settings, listener, isPreviewMode);
final DataNode<ProjectData> resultProjectDataNode = myHelper.execute(
projectPath, settings,
new ProjectConnectionDataNodeFunction(
id, projectPath, settings, listener, isPreviewMode, projectResolverChain, false)
projectPath, settings, new ProjectConnectionDataNodeFunction(resolverContext, projectResolverChain, false)
);
// auto-discover buildSrc project if needed
final String buildSrcProjectPath = projectPath + "/buildSrc";
handleBuildSrcProject(
resultProjectDataNode,
new ProjectConnectionDataNodeFunction(id, buildSrcProjectPath, settings, listener, isPreviewMode, projectResolverChain, true)
);
DefaultProjectResolverContext buildSrcResolverCtx =
new DefaultProjectResolverContext(id, buildSrcProjectPath, settings, listener, isPreviewMode);
resolverContext.copyUserDataTo(buildSrcResolverCtx);
handleBuildSrcProject(resultProjectDataNode, new ProjectConnectionDataNodeFunction(buildSrcResolverCtx, projectResolverChain, true));
return resultProjectDataNode;
}
@@ -131,7 +130,7 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad
}
@NotNull
private DataNode<ProjectData> doResolveProjectInfo(@NotNull final ProjectResolverContext resolverCtx,
private DataNode<ProjectData> doResolveProjectInfo(@NotNull final DefaultProjectResolverContext resolverCtx,
@NotNull final GradleProjectResolverExtension projectResolverChain,
boolean isBuildSrcProject)
throws IllegalArgumentException, IllegalStateException {
@@ -200,6 +199,7 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad
ProjectImportAction.AllModels allModels;
final CancellationTokenSource cancellationTokenSource = GradleConnector.newCancellationTokenSource();
try {
resolverCtx.setCancellationTokenSource(cancellationTokenSource);
buildActionExecutor.withCancellationToken(cancellationTokenSource.token());
synchronized (myCancellationMap) {
myCancellationMap.putValue(resolverCtx.getExternalSystemTaskId(), cancellationTokenSource);
@@ -618,26 +618,26 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad
private void handleBuildSrcProject(@NotNull final DataNode<ProjectData> resultProjectDataNode,
@NotNull final ProjectConnectionDataNodeFunction projectConnectionDataNodeFunction) {
if (!new File(projectConnectionDataNodeFunction.myProjectPath).isDirectory()) {
final String projectPath = projectConnectionDataNodeFunction.myResolverContext.getProjectPath();
if (!new File(projectPath).isDirectory()) {
return;
}
if (projectConnectionDataNodeFunction.myIsPreviewMode) {
if (projectConnectionDataNodeFunction.myResolverContext.isPreviewMode()) {
ModuleData buildSrcModuleData =
new ModuleData(":buildSrc", GradleConstants.SYSTEM_ID, StdModuleTypes.JAVA.getId(), "buildSrc",
projectConnectionDataNodeFunction.myProjectPath, projectConnectionDataNodeFunction.myProjectPath);
new ModuleData(":buildSrc", GradleConstants.SYSTEM_ID, StdModuleTypes.JAVA.getId(), "buildSrc", projectPath, projectPath);
resultProjectDataNode.createChild(ProjectKeys.MODULE, buildSrcModuleData);
return;
}
final DataNode<ModuleData> buildSrcModuleDataNode =
GradleProjectResolverUtil.findModule(resultProjectDataNode, projectConnectionDataNodeFunction.myProjectPath);
GradleProjectResolverUtil.findModule(resultProjectDataNode, projectPath);
// check if buildSrc project was already exposed in settings.gradle file
if (buildSrcModuleDataNode != null) return;
final DataNode<ProjectData> buildSrcProjectDataDataNode = myHelper.execute(
projectConnectionDataNodeFunction.myProjectPath, projectConnectionDataNodeFunction.mySettings, projectConnectionDataNodeFunction);
projectPath, projectConnectionDataNodeFunction.myResolverContext.getSettings(), projectConnectionDataNodeFunction);
if (buildSrcProjectDataDataNode != null) {
for (DataNode<ModuleData> moduleNode : ExternalSystemApiUtil.getChildren(buildSrcProjectDataDataNode, ProjectKeys.MODULE)) {
@@ -658,26 +658,13 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad
}
private class ProjectConnectionDataNodeFunction implements Function<ProjectConnection, DataNode<ProjectData>> {
@NotNull private final ExternalSystemTaskId myId;
@NotNull private final String myProjectPath;
@Nullable private final GradleExecutionSettings mySettings;
@NotNull private final ExternalSystemTaskNotificationListener myListener;
private final boolean myIsPreviewMode;
@NotNull private final GradleProjectResolverExtension myProjectResolverChain;
private final boolean myIsBuildSrcProject;
private DefaultProjectResolverContext myResolverContext;
public ProjectConnectionDataNodeFunction(@NotNull ExternalSystemTaskId id,
@NotNull String projectPath,
@Nullable GradleExecutionSettings settings,
@NotNull ExternalSystemTaskNotificationListener listener,
boolean isPreviewMode,
@NotNull GradleProjectResolverExtension projectResolverChain,
boolean isBuildSrcProject) {
myId = id;
myProjectPath = projectPath;
mySettings = settings;
myListener = listener;
myIsPreviewMode = isPreviewMode;
public ProjectConnectionDataNodeFunction(@NotNull DefaultProjectResolverContext resolverContext,
@NotNull GradleProjectResolverExtension projectResolverChain, boolean isBuildSrcProject) {
myResolverContext = resolverContext;
myProjectResolverChain = projectResolverChain;
myIsBuildSrcProject = isBuildSrcProject;
}
@@ -685,13 +672,12 @@ public class GradleProjectResolver implements ExternalSystemProjectResolver<Grad
@Override
public DataNode<ProjectData> fun(ProjectConnection connection) {
try {
return doResolveProjectInfo(
new ProjectResolverContext(myId, myProjectPath, mySettings, connection, myListener, myIsPreviewMode),
myProjectResolverChain, myIsBuildSrcProject);
myResolverContext.setConnection(connection);
return doResolveProjectInfo(myResolverContext, myProjectResolverChain, myIsBuildSrcProject);
}
catch (RuntimeException e) {
LOG.info("Gradle project resolve error", e);
throw myProjectResolverChain.getUserFriendlyError(e, myProjectPath, null);
throw myProjectResolverChain.getUserFriendlyError(e, myResolverContext.getProjectPath(), null);
}
}
}
@@ -15,6 +15,7 @@
*/
package org.jetbrains.plugins.gradle.service.project;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.externalSystem.model.DataNode;
import com.intellij.openapi.externalSystem.model.Key;
import com.intellij.openapi.externalSystem.model.ProjectKeys;
@@ -22,6 +23,8 @@ import com.intellij.openapi.externalSystem.model.project.*;
import com.intellij.openapi.externalSystem.model.task.TaskData;
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
import com.intellij.openapi.externalSystem.util.ExternalSystemDebugEnvironment;
import com.intellij.openapi.module.StdModuleTypes;
import com.intellij.openapi.roots.DependencyScope;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
@@ -30,6 +33,8 @@ import com.intellij.util.BooleanFunction;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import org.gradle.tooling.model.GradleProject;
import org.gradle.tooling.model.gradle.BasicGradleProject;
import org.gradle.tooling.model.gradle.GradleBuild;
import org.gradle.tooling.model.idea.IdeaModule;
import org.gradle.util.GradleVersion;
import org.jetbrains.annotations.NotNull;
@@ -39,8 +44,10 @@ import org.jetbrains.plugins.gradle.ExternalDependencyId;
import org.jetbrains.plugins.gradle.model.*;
import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData;
import org.jetbrains.plugins.gradle.util.GradleConstants;
import org.jetbrains.plugins.gradle.util.GradleUtil;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
import java.util.Queue;
@@ -50,9 +57,107 @@ import java.util.Queue;
* @since 10/6/2015
*/
public class GradleProjectResolverUtil {
private static final Logger LOG = Logger.getInstance(GradleProjectResolverUtil.class);
@NotNull
private static final Key<Object> CONTAINER_KEY = Key.create(Object.class, ExternalSystemConstants.UNORDERED);
@NotNull
public static DataNode<ModuleData> createMainModule(@NotNull ProjectResolverContext resolverCtx,
@NotNull IdeaModule gradleModule,
@NotNull DataNode<ProjectData> projectDataNode) {
final String moduleName = gradleModule.getName();
if (moduleName == null) {
throw new IllegalStateException("Module with undefined name detected: " + gradleModule);
}
final ProjectData projectData = projectDataNode.getData();
final String mainModuleConfigPath = getModuleConfigPath(resolverCtx, gradleModule, projectData.getLinkedExternalProjectPath());
final String ideProjectPath = resolverCtx.getIdeProjectPath();
final String relativePath;
if (FileUtil.isAncestor(projectData.getLinkedExternalProjectPath(), mainModuleConfigPath, false)) {
relativePath = FileUtil.getRelativePath(projectData.getLinkedExternalProjectPath(), mainModuleConfigPath, '/');
}
else {
relativePath = String.valueOf(FileUtil.pathHashCode(mainModuleConfigPath));
}
final String mainModuleFileDirectoryPath =
ideProjectPath == null ? mainModuleConfigPath : ideProjectPath + "/.idea/modules/" +
(relativePath == null || relativePath.equals(".") ? "" : relativePath);
if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
LOG.info(String.format(
"Creating module data ('%s') with the external config path: '%s'", gradleModule.getGradleProject().getPath(), mainModuleConfigPath
));
}
String gradlePath = gradleModule.getGradleProject().getPath();
final boolean isRootModule = StringUtil.isEmpty(gradlePath) || ":".equals(gradlePath);
String mainModuleId = isRootModule ? moduleName : gradlePath;
final ModuleData moduleData =
new ModuleData(mainModuleId, GradleConstants.SYSTEM_ID, StdModuleTypes.JAVA.getId(), moduleName,
mainModuleFileDirectoryPath, mainModuleConfigPath);
ExternalProject externalProject = resolverCtx.getExtraProject(gradleModule, ExternalProject.class);
if (externalProject != null) {
moduleData.setGroup(externalProject.getGroup());
moduleData.setVersion(externalProject.getVersion());
moduleData.setDescription(externalProject.getDescription());
moduleData.setArtifacts(externalProject.getArtifacts());
}
return projectDataNode.createChild(ProjectKeys.MODULE, moduleData);
}
@NotNull
public static String getModuleConfigPath(@NotNull ProjectResolverContext resolverCtx,
@NotNull IdeaModule gradleModule,
@NotNull String rootProjectPath) {
GradleBuild build = resolverCtx.getExtraProject(gradleModule, GradleBuild.class);
if (build != null) {
String gradlePath = gradleModule.getGradleProject().getPath();
File moduleDirPath = getModuleDirPath(build, gradlePath);
if (moduleDirPath == null) {
throw new IllegalStateException(String.format("Unable to find root directory for module '%s'", gradleModule.getName()));
}
try {
return ExternalSystemApiUtil.toCanonicalPath(moduleDirPath.getCanonicalPath());
}
catch (IOException e) {
LOG.warn("construction of the canonical path for the module fails", e);
}
}
return GradleUtil.getConfigPath(gradleModule.getGradleProject(), rootProjectPath);
}
/**
* Returns the physical path of the module's root directory (the path in the file system.)
* <p>
* It is important to note that Gradle has its own "logical" path that may or may not be equal to the physical path of a Gradle project.
* For example, the sub-project at ${projectRootDir}/apps/app will have the Gradle path :apps:app. Gradle also allows mapping physical
* paths to a different logical path. For example, in settings.gradle:
* <pre>
* include ':app'
* project(':app').projectDir = new File(rootDir, 'apps/app')
* </pre>
* In this example, sub-project at ${projectRootDir}/apps/app will have the Gradle path :app.
* </p>
*
* @param build contains information about the root Gradle project and its sub-projects. Such information includes the physical path of
* the root Gradle project and its sub-projects.
* @param path the Gradle "logical" path. This path uses colon as separator, and may or may not be equal to the physical path of a
* Gradle project.
* @return the physical path of the module's root directory.
*/
@Nullable
public static File getModuleDirPath(@NotNull GradleBuild build, @NotNull String path) {
for (BasicGradleProject project : build.getProjects()) {
if (project.getPath().equals(path)) {
return project.getProjectDirectory();
}
}
return null;
}
@NotNull
public static String getModuleId(@NotNull IdeaModule gradleModule) {
GradleProject gradleProject = gradleModule.getGradleProject();
@@ -18,6 +18,7 @@ package org.jetbrains.plugins.gradle.service.project;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.util.UserDataHolderEx;
import org.gradle.tooling.CancellationTokenSource;
import org.gradle.tooling.ProjectConnection;
import org.gradle.tooling.model.idea.IdeaModule;
@@ -32,101 +33,45 @@ import java.util.Collection;
* @author Vladislav.Soroka
* @since 10/15/13
*/
public class ProjectResolverContext {
@NotNull private final ExternalSystemTaskId myExternalSystemTaskId;
@NotNull private final String myProjectPath;
@Nullable private final GradleExecutionSettings mySettings;
@NotNull private final ProjectConnection myConnection;
@Nullable private CancellationTokenSource myCancellationTokenSource;
@NotNull private final ExternalSystemTaskNotificationListener myListener;
private final boolean myIsPreviewMode;
public interface ProjectResolverContext extends UserDataHolderEx {
@NotNull
private ProjectImportAction.AllModels myModels;
public ProjectResolverContext(@NotNull final ExternalSystemTaskId externalSystemTaskId,
@NotNull final String projectPath,
@Nullable final GradleExecutionSettings settings,
@NotNull final ProjectConnection connection,
@NotNull final ExternalSystemTaskNotificationListener listener,
final boolean isPreviewMode) {
myExternalSystemTaskId = externalSystemTaskId;
myProjectPath = projectPath;
mySettings = settings;
myConnection = connection;
myListener = listener;
myIsPreviewMode = isPreviewMode;
}
@NotNull
public ExternalSystemTaskId getExternalSystemTaskId() {
return myExternalSystemTaskId;
}
ExternalSystemTaskId getExternalSystemTaskId();
@Nullable
public String getIdeProjectPath() {
return mySettings != null ? mySettings.getIdeProjectPath() : null;
}
String getIdeProjectPath();
@NotNull
public String getProjectPath() {
return myProjectPath;
}
String getProjectPath();
@Nullable
public GradleExecutionSettings getSettings() {
return mySettings;
}
GradleExecutionSettings getSettings();
@NotNull
public ProjectConnection getConnection() {
return myConnection;
}
ProjectConnection getConnection();
@Nullable
public CancellationTokenSource getCancellationTokenSource() {
return myCancellationTokenSource;
}
public void setCancellationTokenSource(@Nullable CancellationTokenSource cancellationTokenSource) {
myCancellationTokenSource = cancellationTokenSource;
}
CancellationTokenSource getCancellationTokenSource();
@NotNull
public ExternalSystemTaskNotificationListener getListener() {
return myListener;
}
ExternalSystemTaskNotificationListener getListener();
public boolean isPreviewMode() {
return myIsPreviewMode;
}
boolean isPreviewMode();
@NotNull
public ProjectImportAction.AllModels getModels() {
return myModels;
}
ProjectImportAction.AllModels getModels();
public void setModels(@NotNull ProjectImportAction.AllModels models) {
myModels = models;
}
public void setModels(@NotNull ProjectImportAction.AllModels models) ;
@Nullable
public <T> T getExtraProject(Class<T> modelClazz) {
return myModels.getExtraProject(null, modelClazz);
}
<T> T getExtraProject(Class<T> modelClazz);
@Nullable
public <T> T getExtraProject(@Nullable IdeaModule module, Class<T> modelClazz) {
return myModels.getExtraProject(module, modelClazz);
}
<T> T getExtraProject(@Nullable IdeaModule module, Class<T> modelClazz);
@NotNull
public Collection<String> findModulesWithModel(@NotNull Class modelClazz) {
return myModels.findModulesWithModel(modelClazz);
}
Collection<String> findModulesWithModel(@NotNull Class modelClazz);
public void checkCancelled() {
if (myCancellationTokenSource != null && myCancellationTokenSource.token().isCancellationRequested()) {
throw new ProcessCanceledException();
}
}
boolean hasModulesWithModel(@NotNull Class modelClazz);
void checkCancelled() throws ProcessCanceledException;
}
@@ -7,7 +7,7 @@
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="external-system-api" />
<orderEntry type="module" module-name="external-system-rt" />
<orderEntry type="module" module-name="annotations" />
<orderEntry type="module" module-name="testFramework" scope="TEST" />
<orderEntry type="module" module-name="testFramework-java" scope="TEST" />
@@ -72,6 +72,13 @@ public abstract class ModelsHolder<K extends Model,V> implements Serializable {
return modules;
}
public boolean hasModulesWithModel(@NotNull Class modelClazz) {
for (Map.Entry<String, Object> set : myModelsById.entrySet()) {
if (modelClazz.isInstance(set.getValue())) return true;
}
return false;
}
public void addExtraProject(@NotNull Object project, @NotNull Class modelClazz) {
myModelsById.put(extractMapKey(modelClazz, null), project);
}
@@ -81,7 +88,7 @@ public abstract class ModelsHolder<K extends Model,V> implements Serializable {
}
@NotNull
protected abstract String extractMapKey(Class modelClazz, @Nullable V module) ;
protected abstract String extractMapKey(Class modelClazz, @Nullable V module);
@NotNull
private static String extractModulePath(Class modelClazz, String key) {
@@ -10,7 +10,7 @@
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="annotations" />
<orderEntry type="module" module-name="external-system-api" />
<orderEntry type="module" module-name="external-system-rt" />
<orderEntry type="module" module-name="gradle-tooling-extension-api" />
<orderEntry type="module" module-name="gradle" scope="TEST" />
<orderEntry type="module" module-name="testFramework" scope="TEST" />
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@ package org.jetbrains.plugins.groovy.intentions.conversions.strings;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.CommonClassNames;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiType;
@@ -138,17 +139,13 @@ public class ConvertGStringToStringIntention extends Intention {
if (text.startsWith("\"\"\"")) {
text = text.substring(3);
}
else if (text.startsWith("\"")) {
text = text.substring(1);
}
else text = StringUtil.trimStart(text, "\"");
}
if (isLast) {
if (text.endsWith("\"\"\"")) {
text = text.substring(0, text.length() - 3);
}
else if (text.endsWith("\"")) {
text = text.substring(0, text.length() - 1);
}
else text = StringUtil.trimEnd(text, "\"");
}
if (isBeforeInjection) {
text = text.substring(0, text.length() - 1);
@@ -159,9 +159,7 @@ public class MvcRunTargetDialog extends DialogWrapper {
String text = getSelectedText();
text = text.trim();
if (text.startsWith(GRAILS_PREFIX)) {
text = text.substring(GRAILS_PREFIX.length());
}
text = StringUtil.trimStart(text, GRAILS_PREFIX);
return text;
}
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2014 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -968,7 +968,7 @@ class Fopppp {
myFixture.configureByText "a.groovy", text
final LookupElement[] completion = myFixture.completeBasic()
return completion.find { println it.lookupString; itemToCheck == it.lookupString }
return completion.find { itemToCheck == it.lookupString }
}
public void testWordCompletionInLiterals() {
@@ -1,5 +1,5 @@
/*
* Copyright 2000-2009 JetBrains s.r.o.
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -15,16 +15,16 @@
*/
package com.intellij.lang.properties;
import com.intellij.lang.properties.references.PropertyReference;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.util.IncorrectOperationException;
import com.intellij.xml.util.XmlUtil;
import com.intellij.lang.properties.references.PropertyReference;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Arrays;
import java.util.Set;

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