diff --git a/community-main.iml b/community-main.iml index 6dcf144cc226..c6a02fa3a573 100644 --- a/community-main.iml +++ b/community-main.iml @@ -122,5 +122,6 @@ + \ No newline at end of file diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java index 9d120d982577..d385c671dae7 100644 --- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java +++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java @@ -378,7 +378,7 @@ public class BuildManager implements Disposable { doNotify(paths, true); } - public void runCommand(Runnable command) { + public void runCommand(@NotNull Runnable command) { myRequestsProcessor.submit(command); } @@ -672,13 +672,12 @@ public class BuildManager implements Disposable { return null; } - final DelegateFuture _future = new DelegateFuture(); + final DelegateFuture _future = new DelegateFuture<>(); // by using the same queue that processes events we ensure that // the build will be aware of all events that have happened before this request runCommand(new Runnable() { @Override public void run() { - final Pair, OSProcessHandler> preloaded = takePreloadedProcess(projectPath); final RequestFuture preloadedFuture = preloaded != null? preloaded.first : null; final boolean usingPreloadedProcess = preloadedFuture != null; @@ -694,7 +693,6 @@ public class BuildManager implements Disposable { } final RequestFuture future = usingPreloadedProcess? preloadedFuture : new RequestFuture(handler, sessionId, new CancelBuildSessionAction()); - _future.setDelegate(future); if (!usingPreloadedProcess && (future.isCancelled() || project.isDisposed())) { // in case of preloaded process the process was already running, so the handler will be notified upon process termination @@ -741,7 +739,7 @@ public class BuildManager implements Disposable { } try { - projectTaskQueue.submit(new Runnable() { + Future buildFuture = projectTaskQueue.submit(new Runnable() { @Override public void run() { Throwable execFailure = null; @@ -778,11 +776,11 @@ public class BuildManager implements Disposable { } }); } - catch(Throwable e) { + catch (Throwable e) { LOG.info(e); } } - + processHandler = launchBuildProcess(project, myListenPort, sessionId, false); errorsOnLaunch = new StringBuffer(); processHandler.addProcessListener(new StdOutputCollector((StringBuffer)errorsOnLaunch)); @@ -840,10 +838,12 @@ public class BuildManager implements Disposable { } }); } - } } }); + TaskFutureAdapter adapter = new TaskFutureAdapter<>(buildFuture); + boolean set = _future.setDelegate(adapter); + assert set; } catch (Throwable e) { handleProcessExecutionFailure(sessionId, e); diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java b/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java index d3b4c1d65d2e..e57e83ee7928 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/CompoundPositionManager.java @@ -30,10 +30,7 @@ import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiFile; import com.intellij.util.ThreeState; import com.intellij.xdebugger.frame.XStackFrame; -import com.sun.jdi.InternalException; -import com.sun.jdi.Location; -import com.sun.jdi.ReferenceType; -import com.sun.jdi.VMDisconnectedException; +import com.sun.jdi.*; import com.sun.jdi.request.ClassPrepareRequest; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -72,7 +69,7 @@ public class CompoundPositionManager extends PositionManagerEx implements MultiR return processor.process(positionManager); } catch (NoDataException | ProcessCanceledException ignored) {} - catch (VMDisconnectedException e) {throw e;} + catch (VMDisconnectedException | ObjectCollectedException e) {throw e;} catch (InternalException e) {LOG.info(e);} catch (Exception | AssertionError e) {LOG.error(e);} } diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/ThreadBlockedMonitor.java b/java/debugger/impl/src/com/intellij/debugger/engine/ThreadBlockedMonitor.java index e36faf363471..2b50d7ce07a4 100644 --- a/java/debugger/impl/src/com/intellij/debugger/engine/ThreadBlockedMonitor.java +++ b/java/debugger/impl/src/com/intellij/debugger/engine/ThreadBlockedMonitor.java @@ -15,6 +15,7 @@ */ package com.intellij.debugger.engine; +import com.intellij.concurrency.JobScheduler; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.engine.events.DebuggerCommandImpl; import com.intellij.debugger.engine.jdi.ThreadReferenceProxy; @@ -23,9 +24,8 @@ import com.intellij.debugger.jdi.VirtualMachineProxyImpl; import com.intellij.notification.NotificationType; import com.intellij.openapi.Disposable; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.registry.Registry; -import com.intellij.util.Alarm; -import com.intellij.util.SingleAlarm; import com.intellij.xdebugger.impl.XDebugSessionImpl; import com.sun.jdi.IncompatibleThreadStateException; import com.sun.jdi.ObjectReference; @@ -36,6 +36,8 @@ import org.jetbrains.annotations.Nullable; import javax.swing.event.HyperlinkEvent; import java.util.Collection; import java.util.HashSet; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; /** * @author egor @@ -45,12 +47,12 @@ public class ThreadBlockedMonitor { private final Collection myWatchedThreads = new HashSet<>(); - private final SingleAlarm myAlarm; + private ScheduledFuture myTask; private final DebugProcessImpl myProcess; public ThreadBlockedMonitor(DebugProcessImpl process, Disposable disposable) { myProcess = process; - myAlarm = new SingleAlarm(this::checkBlockingThread, 5000, Alarm.ThreadToUse.POOLED_THREAD, disposable); + Disposer.register(disposable, this::cancelTask); } public void startWatching(@Nullable ThreadReferenceProxy thread) { @@ -58,7 +60,9 @@ public class ThreadBlockedMonitor { DebuggerManagerThreadImpl.assertIsManagerThread(); if (thread != null) { myWatchedThreads.add(thread); - myAlarm.request(); + if (myTask == null) { + myTask = JobScheduler.getScheduler().scheduleWithFixedDelay(this::checkBlockingThread, 5, 5, TimeUnit.SECONDS); + } } } @@ -71,7 +75,14 @@ public class ThreadBlockedMonitor { myWatchedThreads.clear(); } if (myWatchedThreads.isEmpty()) { - myAlarm.cancel(); + cancelTask(); + } + } + + private void cancelTask() { + if (myTask != null) { + myTask.cancel(true); + myTask = null; } } @@ -129,7 +140,6 @@ public class ThreadBlockedMonitor { } finally { vmProxy.getVirtualMachine().resume(); - myAlarm.request(); } } }); diff --git a/java/execution/impl/src/com/intellij/testIntegration/DeadTestsCleaner.java b/java/execution/impl/src/com/intellij/testIntegration/DeadTestsCleaner.java new file mode 100644 index 000000000000..06432484a68c --- /dev/null +++ b/java/execution/impl/src/com/intellij/testIntegration/DeadTestsCleaner.java @@ -0,0 +1,56 @@ +/* + * Copyright 2000-2016 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.testIntegration; + +import com.intellij.execution.Location; +import com.intellij.execution.TestStateStorage; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.util.Ref; + +import java.util.Collection; + +public class DeadTestsCleaner implements Runnable { + private final TestStateStorage myTestStorage; + private final Collection myTestUrls; + private final TestLocator myTestLocator; + + public DeadTestsCleaner(TestStateStorage storage, Collection urls, TestLocator locator) { + myTestStorage = storage; + myTestUrls = urls; + myTestLocator = locator; + } + + @Override + public void run() { + for (String url : myTestUrls) { + processUrl(url); + } + } + + private void processUrl(final String url) { + final Ref locationRef = Ref.create(); + ApplicationManager.getApplication().runReadAction(new Runnable() { + @Override + public void run() { + Location location = myTestLocator.getLocation(url); + locationRef.set(location); + } + }); + if (locationRef.get() == null) { + myTestStorage.removeState(url); + } + } +} \ No newline at end of file diff --git a/java/execution/impl/src/com/intellij/testIntegration/RecentTestRunner.java b/java/execution/impl/src/com/intellij/testIntegration/RecentTestRunner.java index 47556660b43f..ff0fdf2532b3 100644 --- a/java/execution/impl/src/com/intellij/testIntegration/RecentTestRunner.java +++ b/java/execution/impl/src/com/intellij/testIntegration/RecentTestRunner.java @@ -16,29 +16,21 @@ package com.intellij.testIntegration; import com.intellij.execution.Location; -import com.intellij.execution.testframework.JavaTestLocator; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataContext; -import com.intellij.openapi.project.Project; -import com.intellij.openapi.vfs.VirtualFileManager; -import com.intellij.psi.search.GlobalSearchScope; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.Nullable; -import java.util.List; - public interface RecentTestRunner { - enum Mode { RUN, DEBUG } + enum Mode { + RUN, + DEBUG + } void setMode(Mode mode); - void run(Location location); - - Location getLocation(String url); - - boolean isSuite(String url); } class RecentTestRunnerImpl implements RecentTestRunner { @@ -46,12 +38,7 @@ class RecentTestRunnerImpl implements RecentTestRunner { private static AnAction DEBUG = ActionManager.getInstance().getAction("DebugClass"); protected AnAction myCurrentAction = RUN; - private final Project myProject; - - public RecentTestRunnerImpl(Project project) { - myProject = project; - } - + public void setMode(Mode mode) { switch (mode) { case RUN: @@ -62,26 +49,6 @@ class RecentTestRunnerImpl implements RecentTestRunner { break; } } - - public Location getLocation(String url) { - String protocol = VirtualFileManager.extractProtocol(url); - String path = VirtualFileManager.extractPath(url); - - if (protocol != null) { - List locations = JavaTestLocator.INSTANCE.getLocation(protocol, path, myProject, GlobalSearchScope.allScope(myProject)); - if (!locations.isEmpty()) { - return locations.get(0); - } - } - - return null; - } - - @Override - public boolean isSuite(String url) { - String protocol = VirtualFileManager.extractProtocol(url); - return JavaTestLocator.SUITE_PROTOCOL.equals(protocol); - } public void run(final Location location) { DataContext data = new DataContext() { diff --git a/java/execution/impl/src/com/intellij/testIntegration/RecentTestsData.java b/java/execution/impl/src/com/intellij/testIntegration/RecentTestsListProvider.java similarity index 88% rename from java/execution/impl/src/com/intellij/testIntegration/RecentTestsData.java rename to java/execution/impl/src/com/intellij/testIntegration/RecentTestsListProvider.java index 23f7a2468485..81048d7b7d10 100644 --- a/java/execution/impl/src/com/intellij/testIntegration/RecentTestsData.java +++ b/java/execution/impl/src/com/intellij/testIntegration/RecentTestsListProvider.java @@ -15,6 +15,7 @@ */ package com.intellij.testIntegration; +import com.intellij.execution.TestStateStorage; import com.intellij.execution.testframework.sm.runner.states.TestStateInfo; import com.intellij.openapi.util.Condition; import com.intellij.openapi.vfs.VirtualFileManager; @@ -27,7 +28,40 @@ import java.util.*; import static com.intellij.execution.testframework.sm.runner.states.TestStateInfo.Magnitude.*; import static com.intellij.testIntegration.TestInfo.select; -public class RecentTestsData { + +public class RecentTestsListProvider { + private final Map myRecords; + + public RecentTestsListProvider(Map records) { + myRecords = records; + } + + public List getUrlsToShowFromHistory() { + if (myRecords == null) return ContainerUtil.emptyList(); + + RecentTestsData data = new RecentTestsData(); + for (Map.Entry entry : myRecords.entrySet()) { + String url = entry.getKey(); + TestStateStorage.Record record = entry.getValue(); + if (TestLocator.canLocate(url)) { + data.addTest(url, getMagnitude(record.magnitude), record.date); + } + } + + return data.getSortedTestsList(); + } + + private static TestStateInfo.Magnitude getMagnitude(int magnitude) { + for (TestStateInfo.Magnitude m : values()) { + if (m.getValue() == magnitude) { + return m; + } + } + return null; + } +} + +class RecentTestsData { private static Comparator BY_PATH_COMPARATOR = new Comparator() { @Override public int compare(TestInfo o1, TestInfo o2) { @@ -50,18 +84,13 @@ public class RecentTestsData { return -o1.getRunDate().compareTo(o2.getRunDate()); } }; - - private final RecentTestRunner myRunner; + private final Map mySuites = ContainerUtil.newHashMap(); private List myTestsWithoutSuites = ContainerUtil.newArrayList(); - public RecentTestsData(RecentTestRunner runner) { - myRunner = runner; - } - public void addTest(String url, TestStateInfo.Magnitude magnitude, Date runDate) { - if (myRunner.isSuite(url)) { + if (TestLocator.isSuite(url)) { mySuites.put(url, new SuiteInfo(url, magnitude, runDate)); return; } @@ -91,7 +120,7 @@ public class RecentTestsData { return null; } - public List calculateTestList() { + public List getSortedTestsList() { distributeUnmatchedTests(); List result = ContainerUtil.newArrayList(); fillWithTests(result, ERROR_INDEX, FAILED_INDEX); @@ -288,18 +317,4 @@ class TestInfo { } }); } - - public static List selectNot(Collection infos, final TestStateInfo.Magnitude... magnitudes) { - return ContainerUtil.filter(infos, new Condition() { - @Override - public boolean value(T t) { - for (TestStateInfo.Magnitude magnitude : magnitudes) { - if (t.getMagnitude() == magnitude) { - return false; - } - } - return true; - } - }); - } } diff --git a/java/execution/impl/src/com/intellij/testIntegration/SelectTestStep.java b/java/execution/impl/src/com/intellij/testIntegration/SelectTestStep.java index e56bedd8fea8..5cc6cd0357b4 100644 --- a/java/execution/impl/src/com/intellij/testIntegration/SelectTestStep.java +++ b/java/execution/impl/src/com/intellij/testIntegration/SelectTestStep.java @@ -16,9 +16,6 @@ package com.intellij.testIntegration; import com.intellij.execution.Location; -import com.intellij.execution.TestStateStorage; -import com.intellij.execution.testframework.TestIconMapper; -import com.intellij.execution.testframework.sm.runner.states.TestStateInfo; import com.intellij.openapi.ui.popup.PopupStep; import com.intellij.openapi.ui.popup.util.BaseListPopupStep; import com.intellij.openapi.vfs.VirtualFileManager; @@ -29,34 +26,20 @@ import java.util.List; import java.util.Map; public class SelectTestStep extends BaseListPopupStep { - private final Map myRecords; private final RecentTestRunner myRunner; + private final TestLocator myTestLocator; + private final Map myIcons; - public SelectTestStep(Map records, RecentTestRunner runner) { - super("Debug Recent Tests", getUrls(records, runner)); + public SelectTestStep(List urls, Map icons, RecentTestRunner runner, TestLocator locator) { + super("Debug Recent Tests", urls); myRunner = runner; - myRecords = records; + myIcons = icons; + myTestLocator = locator; } - private static List getUrls(Map records, RecentTestRunner runner) { - RecentTestsData data = new RecentTestsData(runner); - - for (Map.Entry entry : records.entrySet()) { - String url = entry.getKey(); - TestStateStorage.Record record = entry.getValue(); - data.addTest(url, getMagnitude(record.magnitude), record.date); - } - - return data.calculateTestList(); - } - - private static TestStateInfo.Magnitude getMagnitude(int magnitude) { - for (TestStateInfo.Magnitude m : TestStateInfo.Magnitude.values()) { - if (m.getValue() == magnitude) { - return m; - } - } - return null; + @Override + public Icon getIconFor(String value) { + return myIcons.get(value); } @NotNull @@ -69,17 +52,10 @@ public class SelectTestStep extends BaseListPopupStep { public boolean isSpeedSearchEnabled() { return true; } - - @Override - public Icon getIconFor(String value) { - TestStateStorage.Record record = myRecords.get(value); - TestStateInfo.Magnitude magnitude = TestIconMapper.getMagnitude(record.magnitude); - return TestIconMapper.getIcon(magnitude); - } @Override public PopupStep onChosen(String url, boolean finalChoice) { - Location location = myRunner.getLocation(url); + Location location = myTestLocator.getLocation(url); myRunner.run(location); return null; } diff --git a/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java b/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java index 5647a6bc3918..c453c16d222d 100644 --- a/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java +++ b/java/execution/impl/src/com/intellij/testIntegration/ShowRecentTests.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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,21 +17,28 @@ package com.intellij.testIntegration; import com.intellij.execution.Location; import com.intellij.execution.TestStateStorage; +import com.intellij.execution.testframework.TestIconMapper; +import com.intellij.execution.testframework.sm.runner.states.TestStateInfo; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.keymap.MacKeymapUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.ListPopupStep; +import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.SystemInfo; import com.intellij.ui.popup.list.ListPopupImpl; +import com.intellij.util.Function; import com.intellij.util.PsiNavigateUtil; import com.intellij.util.Time; +import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Date; +import java.util.List; import java.util.Map; public class ShowRecentTests extends AnAction { @@ -51,21 +58,43 @@ public class ShowRecentTests extends AnAction { final Project project = e.getProject(); if (project == null) return; - Map records = TestStateStorage.getInstance(project).getRecentTests(TEST_LIMIT, getSinceDate()); - RecentTestRunner testRunner = new RecentTestRunnerImpl(project); + final TestStateStorage testStorage = TestStateStorage.getInstance(project); + final TestLocator testLocator = new TestLocator(project); + final RecentTestRunnerImpl testRunner = new RecentTestRunnerImpl(); - SelectTestStep selectStepTest = new SelectTestStep(records, testRunner); - RecentTestsListPopup popup = new RecentTestsListPopup(selectStepTest, testRunner); + final Map records = testStorage.getRecentTests(TEST_LIMIT, getSinceDate()); + RecentTestsListProvider listProvider = new RecentTestsListProvider(records); + List urls = listProvider.getUrlsToShowFromHistory(); + Map icons = ContainerUtil.map2Map(urls, new Function>() { + @Override + public Pair fun(String url) { + return Pair.create(url, getIconFor(url, records)); + } + }); + SelectTestStep selectStepTest = new SelectTestStep(urls, icons, testRunner, testLocator); + + RecentTestsListPopup popup = new RecentTestsListPopup(selectStepTest, testRunner, testLocator); popup.showCenteredInCurrentWindow(project); + + ApplicationManager.getApplication().executeOnPooledThread(new DeadTestsCleaner(testStorage, urls, testLocator)); + } + + private static Icon getIconFor(String value, Map records) { + TestStateStorage.Record record = records.get(value); + TestStateInfo.Magnitude magnitude = TestIconMapper.getMagnitude(record.magnitude); + return TestIconMapper.getIcon(magnitude); } } class RecentTestsListPopup extends ListPopupImpl { private final RecentTestRunner myTestRunner; + private final TestLocator myLocator; - public RecentTestsListPopup(ListPopupStep popupStep, RecentTestRunner testRunner) { + public RecentTestsListPopup(ListPopupStep popupStep, RecentTestRunner testRunner, TestLocator locator) { super(popupStep); myTestRunner = testRunner; + myLocator = locator; + shiftReleased(); registerActions(this); @@ -97,7 +126,7 @@ class RecentTestsListPopup extends ListPopupImpl { public void actionPerformed(ActionEvent e) { Object[] values = getSelectedValues(); if (values.length == 1) { - Location location = myTestRunner.getLocation(values[0].toString()); + Location location = myLocator.getLocation(values[0].toString()); if (location != null) { cancel(); PsiNavigateUtil.navigate(location.getPsiElement()); diff --git a/java/execution/impl/src/com/intellij/testIntegration/TestLocator.java b/java/execution/impl/src/com/intellij/testIntegration/TestLocator.java new file mode 100644 index 000000000000..10dd60f2f8c9 --- /dev/null +++ b/java/execution/impl/src/com/intellij/testIntegration/TestLocator.java @@ -0,0 +1,65 @@ +/* + * Copyright 2000-2016 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.testIntegration; + +import com.intellij.execution.Location; +import com.intellij.execution.testframework.JavaTestLocator; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.vfs.VirtualFileManager; +import com.intellij.psi.search.GlobalSearchScope; + +import java.util.List; + +public class TestLocator { + private final Project myProject; + + public TestLocator(Project project) { + myProject = project; + } + + public Location getLocation(String url) { + return getLocation(url, myProject); + } + + public static Location getLocation(String url, Project project) { + String protocol = VirtualFileManager.extractProtocol(url); + String path = VirtualFileManager.extractPath(url); + + if (protocol != null) { + List locations = JavaTestLocator.INSTANCE.getLocation(protocol, path, project, GlobalSearchScope.allScope(project)); + if (!locations.isEmpty()) { + return locations.get(0); + } + } + + return null; + } + + public static boolean canLocate(String url) { + return isSuite(url) || isTest(url); + } + + public static boolean isSuite(String url) { + String protocol = VirtualFileManager.extractProtocol(url); + return JavaTestLocator.SUITE_PROTOCOL.equals(protocol); + } + + public static boolean isTest(String url) { + String protocol = VirtualFileManager.extractProtocol(url); + return JavaTestLocator.TEST_PROTOCOL.equals(protocol); + } + +} \ No newline at end of file diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java index 0e42638954a5..ba93efb67764 100644 --- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java +++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java @@ -22,6 +22,7 @@ import com.intellij.ide.util.frameworkSupport.FrameworkSupportUtil; import com.intellij.ide.util.newProjectWizard.AddSupportForFrameworksPanel; import com.intellij.ide.util.newProjectWizard.FrameworkSupportNode; import com.intellij.ide.util.newProjectWizard.TemplatesGroup; +import com.intellij.ide.util.newProjectWizard.WizardDelegate; import com.intellij.ide.util.newProjectWizard.impl.FrameworkSupportModelBase; import com.intellij.ide.util.newProjectWizard.modes.CreateFromTemplateMode; import com.intellij.ide.util.projectWizard.*; @@ -650,6 +651,7 @@ public class ProjectTypeStep extends ModuleWizardStep implements SettingsStep, D if (builder != null) { myWizard.getSequence().setType(builder.getBuilderId()); } + myWizard.setDelegate(builder instanceof WizardDelegate ? (WizardDelegate)builder : null); } @TestOnly diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java index 75559410bda4..74908efb2e9f 100644 --- a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/AbstractProjectWizard.java @@ -53,15 +53,19 @@ import java.io.File; */ public abstract class AbstractProjectWizard extends AbstractWizard { protected final WizardContext myWizardContext; + @Nullable + private WizardDelegate myDelegate; public AbstractProjectWizard(String title, Project project, String defaultPath) { super(title, project); myWizardContext = initContext(project, defaultPath, getDisposable()); + myWizardContext.setWizard(this); } public AbstractProjectWizard(String title, Project project, Component dialogParent) { super(title, dialogParent); myWizardContext = initContext(project, null, getDisposable()); + myWizardContext.setWizard(this); } @Override @@ -174,6 +178,10 @@ public abstract class AbstractProjectWizard extends AbstractWizard getCurrentStep() && !commitStepData(step)) { - updateStepsPanel(); - return; - } - step.onStepLeaving(); - - // Commit data of current step - final Step currentStep = mySteps.get(myCurrentStep); - try { - currentStep._commit(false); - } - catch (final CommitStepException exc) { - Messages.showErrorDialog( - myContentPanel, - exc.getMessage() - ); - return; - } - - myCurrentStep = ind; - updateStep(); - - } - }); - - final int next = getNextStep(index); - index = index == next ? -1 : next; - } - - final Enumeration buttons = group.getElements(); - while (buttons.hasMoreElements()) { - final JRadioButton b = (JRadioButton)buttons.nextElement(); - b.setUI(new WizardArrowUI(b, index < myCurrentStep)); - } - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - myStepsPanel.revalidate(); - myStepsPanel.repaint(); - } - }); - } -} diff --git a/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/WizardDelegate.java b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/WizardDelegate.java new file mode 100644 index 000000000000..70766d58fff5 --- /dev/null +++ b/java/idea-ui/src/com/intellij/ide/util/newProjectWizard/WizardDelegate.java @@ -0,0 +1,28 @@ +/* + * Copyright 2000-2016 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.ide.util.newProjectWizard; + +/** + * @author Dmitry Avdeev + */ +public interface WizardDelegate { + + void doNextAction(); + + void doPreviousAction(); + + void doFinishAction(); +} diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/TrivialMethodReferenceInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/TrivialMethodReferenceInspection.java index c2678959d23c..b66674135de7 100644 --- a/java/java-analysis-impl/src/com/intellij/codeInspection/TrivialMethodReferenceInspection.java +++ b/java/java-analysis-impl/src/com/intellij/codeInspection/TrivialMethodReferenceInspection.java @@ -15,6 +15,7 @@ */ package com.intellij.codeInspection; +import com.intellij.codeInsight.FileModificationService; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.util.MethodSignatureUtil; @@ -62,6 +63,7 @@ public class TrivialMethodReferenceInspection extends BaseJavaBatchLocalInspecti @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { PsiElement element = descriptor.getPsiElement(); + if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return; final PsiElement parent = element != null ? element.getParent() : null; if (parent instanceof PsiMethodReferenceExpression) { final PsiExpression qualifierExpression = ((PsiMethodReferenceExpression)parent).getQualifierExpression(); diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaLineMarkerProvider.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaLineMarkerProvider.java index 257a37e84585..8c7ae863eb89 100644 --- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaLineMarkerProvider.java +++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/JavaLineMarkerProvider.java @@ -55,7 +55,7 @@ import java.util.Set; public class JavaLineMarkerProvider extends LineMarkerProviderDescriptor { private final DaemonCodeAnalyzerSettings myDaemonSettings; private final EditorColorsManager myColorsManager; - private final Option myLambdaOption = new Option("java.lambda", "Lambda", AllIcons.Gutter.ImplementingFunctional); + private final Option myLambdaOption = new Option("java.lambda", "Lambda", AllIcons.Gutter.ImplementingFunctionalInterface); public JavaLineMarkerProvider(DaemonCodeAnalyzerSettings daemonSettings, EditorColorsManager colorsManager) { myDaemonSettings = daemonSettings; @@ -81,7 +81,7 @@ public class JavaLineMarkerProvider extends LineMarkerProviderDescriptor { final PsiMethod interfaceMethod = LambdaUtil.getFunctionalInterfaceMethod(element); final PsiElement firstChild = element.getFirstChild(); if (interfaceMethod != null && firstChild != null && LineMarkerSettings.getSettings().isEnabled(myLambdaOption)) { - return createSuperMethodLineMarkerInfo(firstChild, AllIcons.Gutter.ImplementingFunctional, Pass.UPDATE_ALL); + return createSuperMethodLineMarkerInfo(firstChild, AllIcons.Gutter.ImplementingFunctionalInterface, Pass.UPDATE_ALL); } if (myDaemonSettings.SHOW_METHOD_SEPARATORS && firstChild == null) { diff --git a/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractClassUtil.java b/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractClassUtil.java index 6bb20f589273..66649dfe4614 100644 --- a/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractClassUtil.java +++ b/java/java-impl/src/com/intellij/refactoring/extractInterface/ExtractClassUtil.java @@ -53,7 +53,7 @@ public class ExtractClassUtil { final boolean isPreviewUsages = dialog.isPreviewUsages(); JavaRefactoringSettings.getInstance().EXTRACT_INTERFACE_PREVIEW_USAGES = isPreviewUsages; TurnRefsToSuperProcessor processor = - new TurnRefsToSuperProcessor(project, (PsiClass)classElement, superClass, true); + new TurnRefsToSuperProcessor(project, (PsiClass)classElement, superClass, false); processor.setPreviewUsages(isPreviewUsages); processor.run(); } diff --git a/java/java-psi-api/src/messages/JavaCoreBundle.properties b/java/java-psi-api/src/messages/JavaCoreBundle.properties index c64bfa9814c9..bab3bde52ca7 100644 --- a/java/java-psi-api/src/messages/JavaCoreBundle.properties +++ b/java/java-psi-api/src/messages/JavaCoreBundle.properties @@ -1,4 +1,4 @@ -psi.error.attempt.to.edit.class.file=Cannot modify compiled element +psi.error.attempt.to.edit.class.file=Cannot modify compiled element in file ''{0}'' default.language.level.description=SDK default jdk.1.3.language.level.description=1.3 - Plain old Java diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsAnnotationImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsAnnotationImpl.java index e42d4b8d459b..21c064095a63 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsAnnotationImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsAnnotationImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,7 +26,6 @@ import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.meta.PsiMetaData; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -122,7 +121,7 @@ public class ClsAnnotationImpl extends ClsRepositoryPsiElement T setDeclaredAttributeValue(@NonNls String attributeName, T value) { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsAnnotationValueImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsAnnotationValueImpl.java index 56a509ad326e..a53941709c14 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsAnnotationValueImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsAnnotationValueImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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,7 +22,6 @@ import com.intellij.psi.impl.meta.MetaRegistry; import com.intellij.psi.impl.source.SourceTreeToPsiMap; import com.intellij.psi.impl.source.tree.TreeElement; import com.intellij.psi.meta.PsiMetaData; -import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -30,13 +29,13 @@ import org.jetbrains.annotations.Nullable; /** * @author ven */ -public abstract class ClsAnnotationValueImpl extends ClsElementImpl implements PsiAnnotation, Navigatable { +abstract class ClsAnnotationValueImpl extends ClsElementImpl implements PsiAnnotation, Navigatable { private final ClsElementImpl myParent; private final ClsJavaCodeReferenceElementImpl myReferenceElement; private final ClsAnnotationParameterListImpl myParameterList; @SuppressWarnings("AbstractMethodCallInConstructor") - public ClsAnnotationValueImpl(@NotNull ClsElementImpl parent) { + ClsAnnotationValueImpl(@NotNull ClsElementImpl parent) { myParent = parent; myReferenceElement = createReference(); myParameterList = createParameterList(); @@ -112,7 +111,7 @@ public abstract class ClsAnnotationValueImpl extends ClsElementImpl implements P @Override public T setDeclaredAttributeValue(@NonNls String attributeName, T value) { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsElementImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsElementImpl.java index 96ec63b29b33..1f9b6800e4f6 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsElementImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsElementImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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 @@ import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; +import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.codeStyle.JavaCodeStyleSettingsFacade; import com.intellij.psi.impl.PsiElementBase; @@ -43,11 +44,9 @@ import java.util.List; public abstract class ClsElementImpl extends PsiElementBase implements PsiCompiledElement { public static final Key COMPILED_ELEMENT = Key.create("COMPILED_ELEMENT"); - protected static final String CAN_NOT_MODIFY_MESSAGE = JavaCoreBundle.message("psi.error.attempt.to.edit.class.file"); - private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.compiled.ClsElementImpl"); - private volatile TreeElement myMirror = null; + private volatile TreeElement myMirror; @Override @NotNull @@ -107,37 +106,44 @@ public abstract class ClsElementImpl extends PsiElementBase implements PsiCompil @Override public void checkAdd(@NotNull PsiElement element) throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); + } + + @NotNull + static IncorrectOperationException cannotModifyException(@NotNull ClsElementImpl element) { + VirtualFile virtualFile = PsiUtilCore.getVirtualFile(element); + String path = virtualFile == null ? "?" : virtualFile.getPresentableUrl(); + return new IncorrectOperationException(JavaCoreBundle.message("psi.error.attempt.to.edit.class.file", path)); } @Override public PsiElement add(@NotNull PsiElement element) throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override public PsiElement addBefore(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override public PsiElement addAfter(@NotNull PsiElement element, PsiElement anchor) throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override public void delete() throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override public void checkDelete() throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override public PsiElement replace(@NotNull PsiElement newElement) throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } public abstract void appendMirrorText(int indentLevel, @NotNull StringBuilder buffer); @@ -259,7 +265,7 @@ public abstract class ClsElementImpl extends PsiElementBase implements PsiCompil return null; } - protected static void goNextLine(int indentLevel, @NotNull StringBuilder buffer) { + static void goNextLine(int indentLevel, @NotNull StringBuilder buffer) { buffer.append('\n'); for (int i = 0; i < indentLevel; i++) buffer.append(' '); } diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java index 0caaa3ea3656..5a151e6c0895 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java @@ -77,8 +77,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import static com.intellij.reference.SoftReference.dereference; - public class ClsFileImpl extends ClsRepositoryPsiElement implements PsiJavaFile, PsiFileWithStubSupport, PsiFileEx, Queryable, PsiClassOwnerEx, PsiCompiledFile { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.compiled.ClsFileImpl"); @@ -99,8 +97,8 @@ public class ClsFileImpl extends ClsRepositoryPsiElement private final boolean myIsForDecompiling; private volatile SoftReference myStub; private volatile TreeElement myMirrorFileElement; - private volatile ClsPackageStatementImpl myPackageStatement = null; - private volatile LanguageLevel myLanguageLevel = null; + private volatile ClsPackageStatementImpl myPackageStatement; + private volatile LanguageLevel myLanguageLevel; private boolean myIsPhysical = true; private boolean myInvalidated; @@ -154,7 +152,7 @@ public class ClsFileImpl extends ClsRepositoryPsiElement return !myInvalidated && (myIsForDecompiling || getVirtualFile().isValid()); } - protected boolean isForDecompiling() { + boolean isForDecompiling() { return myIsForDecompiling; } @@ -259,12 +257,12 @@ public class ClsFileImpl extends ClsRepositoryPsiElement @Override public PsiElement setName(@NotNull String name) throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override public void checkSetName(String name) throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override @@ -347,6 +345,7 @@ public class ClsFileImpl extends ClsRepositoryPsiElement try { final TreeElement finalMirrorTreeElement = mirrorTreeElement; ProgressManager.getInstance().executeNonCancelableSection(new Runnable() { + @Override public void run() { setMirror(finalMirrorTreeElement); putUserData(CLS_DOCUMENT_LINK_KEY, document); @@ -478,7 +477,7 @@ public class ClsFileImpl extends ClsRepositoryPsiElement public StubTree getStubTree() { ApplicationManager.getApplication().assertReadAccessAllowed(); - StubTree stubTree = dereference(myStub); + StubTree stubTree = SoftReference.dereference(myStub); if (stubTree != null) return stubTree; // build newStub out of lock to avoid deadlock @@ -491,7 +490,7 @@ public class ClsFileImpl extends ClsRepositoryPsiElement } synchronized (myStubLock) { - stubTree = dereference(myStub); + stubTree = SoftReference.dereference(myStub); if (stubTree != null) return stubTree; stubTree = newStubTree; @@ -520,7 +519,7 @@ public class ClsFileImpl extends ClsRepositoryPsiElement ApplicationManager.getApplication().assertWriteAccessAllowed(); synchronized (myStubLock) { - StubTree stubTree = dereference(myStub); + StubTree stubTree = SoftReference.dereference(myStub); myStub = null; if (stubTree != null) { //noinspection unchecked diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsJavaCodeReferenceElementImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsJavaCodeReferenceElementImpl.java index 89eddafc52f9..ab94f7471a39 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsJavaCodeReferenceElementImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsJavaCodeReferenceElementImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -254,12 +254,12 @@ public class ClsJavaCodeReferenceElementImpl extends ClsElementImpl implements P @Override public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsModifierListImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsModifierListImpl.java index 1ce4baf130ec..03e7013f1d7c 100644 --- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsModifierListImpl.java +++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsModifierListImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -51,12 +51,12 @@ public class ClsModifierListImpl extends ClsRepositoryPsiElement @Override public PsiElement setName(@NotNull String name) throws IncorrectOperationException { - throw new IncorrectOperationException(CAN_NOT_MODIFY_MESSAGE); + throw cannotModifyException(this); } @Override diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateMembersUtilTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateMembersUtilTest.java index 220a571d5759..9658830054d6 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateMembersUtilTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateMembersUtilTest.java @@ -1,3 +1,18 @@ +/* + * Copyright 2000-2016 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.codeInsight; import com.intellij.JavaTestUtil; @@ -5,6 +20,8 @@ import com.intellij.codeInsight.generation.GenerateMembersUtil; import com.intellij.codeInsight.generation.GenerationInfo; import com.intellij.codeInsight.generation.PsiGenerationInfo; import com.intellij.lang.java.JavaLanguage; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.util.Computable; import com.intellij.psi.*; import com.intellij.testFramework.LightCodeInsightTestCase; import org.jetbrains.annotations.NonNls; @@ -47,7 +64,12 @@ public class GenerateMembersUtilTest extends LightCodeInsightTestCase { PsiMethod method = factory.createMethod("foo", PsiType.VOID); int offset = getEditor().getCaretModel().getOffset(); List list = Collections.singletonList(new PsiGenerationInfo(method)); - List members = GenerateMembersUtil.insertMembersAtOffset(getFile(), offset, list); + List members = ApplicationManager.getApplication().runWriteAction(new Computable>() { + @Override + public List compute() { + return GenerateMembersUtil.insertMembersAtOffset(getFile(), offset, list); + } + }); members.get(0).positionCaret(myEditor, true); checkResultByFile(null, BASE_PATH + getTestName(false) + "_after.java", true); } @@ -63,10 +85,16 @@ public class GenerateMembersUtilTest extends LightCodeInsightTestCase { PsiJavaFile file = (PsiJavaFile)PsiFileFactory.getInstance(getProject()) .createFileFromText(JavaLanguage.INSTANCE, "class A {void foo() {}}\n class B extends A {void foo() {}\n}"); - method = file.getClasses()[1].getMethods()[0]; - GenerateMembersUtil.setupGeneratedMethod(method); - assertEquals("@Override void foo() {\n" + - " super.foo();\n" + - " }", method.getText()); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + PsiMethod newMethod = file.getClasses()[1].getMethods()[0]; + GenerateMembersUtil.setupGeneratedMethod(newMethod); + assertEquals("@Override void foo() {\n" + + " super.foo();\n" + + " }", newMethod.getText()); + } + }); + } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateSuperMethodCallTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateSuperMethodCallTest.java index 30acd989c957..2fa48e312e1b 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/GenerateSuperMethodCallTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/GenerateSuperMethodCallTest.java @@ -1,7 +1,23 @@ +/* + * Copyright 2000-2016 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.codeInsight; import com.intellij.JavaTestUtil; import com.intellij.codeInsight.generation.actions.GenerateSuperMethodCallAction; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiFile; @@ -43,7 +59,13 @@ public class GenerateSuperMethodCallTest extends LightCodeInsightTestCase { return super.getHandler(); } }.getHandler(); - handler.invoke(getProject(), getEditor(), getFile()); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + handler.invoke(getProject(), getEditor(), getFile()); + } + }); + checkResultByFile(after); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java index 84ec461a8ada..71e1a928c4e3 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/OverrideImplement15Test.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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.codeInsight.generation.OverrideImplementUtil; import com.intellij.codeInsight.generation.PsiMethodMember; import com.intellij.codeInsight.intention.impl.ImplementAbstractMethodHandler; import com.intellij.lang.java.JavaLanguage; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.pom.java.LanguageLevel; import com.intellij.psi.*; import com.intellij.psi.codeStyle.CodeStyleSettings; @@ -163,19 +164,27 @@ public class OverrideImplement15Test extends LightCodeInsightTestCase { PsiElement context = getFile().findElementAt(offset); PsiClass psiClass = PsiTreeUtil.getParentOfType(context, PsiClass.class); assert psiClass != null; - if (toImplement == null) { - PsiClassType[] implement = psiClass.getImplementsListTypes(); - final PsiClass superClass = implement.length == 0 ? psiClass.getSuperClass() : implement[0].resolve(); - assert superClass != null; - PsiMethod method = superClass.getMethods()[0]; - final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, psiClass, PsiSubstitutor.EMPTY); - final List candidates = Collections.singletonList(new PsiMethodMember(method, - OverrideImplementExploreUtil.correctSubstitutor(method, substitutor))); - OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(getEditor(), psiClass, candidates, copyJavadoc, true); - } - else { - OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), getEditor(), psiClass, toImplement); - } + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + if (toImplement == null) { + PsiClassType[] implement = psiClass.getImplementsListTypes(); + final PsiClass superClass = implement.length == 0 ? psiClass.getSuperClass() : implement[0].resolve(); + assert superClass != null; + PsiMethod method = superClass.getMethods()[0]; + final PsiSubstitutor substitutor = TypeConversionUtil.getSuperClassSubstitutor(superClass, psiClass, PsiSubstitutor.EMPTY); + final List candidates = Collections.singletonList(new PsiMethodMember(method, + OverrideImplementExploreUtil + .correctSubstitutor(method, + substitutor))); + OverrideImplementUtil.overrideOrImplementMethodsInRightPlace(getEditor(), psiClass, candidates, copyJavadoc, true); + } + else { + OverrideImplementUtil.chooseAndOverrideOrImplementMethods(getProject(), getEditor(), psiClass, toImplement); + } + } + }); + checkResultByFile(BASE_DIR + "after" + name + ".java"); } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java index 414d89368523..2b4832eda07a 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/I18nizeTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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 @@ import com.intellij.ide.DataManager; import com.intellij.lang.properties.psi.PropertiesFile; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DataContext; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.PathManagerEx; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiLiteralExpression; @@ -61,8 +62,15 @@ public class I18nizeTest extends LightCodeInsightTestCase { if (afterFileExists) { PsiLiteralExpression literalExpression = I18nizeAction.getEnclosingStringLiteral(getFile(), getEditor()); assertNotNull(handler); - handler.performI18nization(getFile(), getEditor(), literalExpression, Collections.emptyList(), "key1", "value1", "i18nizedExpr", - PsiExpression.EMPTY_ARRAY, JavaI18nUtil.DEFAULT_PROPERTY_CREATION_HANDLER); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + handler.performI18nization(getFile(), getEditor(), literalExpression, Collections.emptyList(), "key1", "value1", + "i18nizedExpr", + PsiExpression.EMPTY_ARRAY, JavaI18nUtil.DEFAULT_PROPERTY_CREATION_HANDLER); + } + }); + checkResultByFile(afterFile); } } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/generation/surroundWith/JavaSurroundWithTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/generation/surroundWith/JavaSurroundWithTest.java index 8426d2d3fded..e775ef7260cf 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/generation/surroundWith/JavaSurroundWithTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/generation/surroundWith/JavaSurroundWithTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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.lang.LanguageSurrounders; import com.intellij.lang.java.JavaLanguage; import com.intellij.lang.surroundWith.SurroundDescriptor; import com.intellij.lang.surroundWith.Surrounder; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.SelectionModel; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; @@ -216,14 +217,26 @@ public class JavaSurroundWithTest extends LightCodeInsightTestCase { PsiElement[] elements = item.getElementsToSurround(getFile(), selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()); assertTrue(surrounder.isApplicable(elements)); - SurroundWithHandler.invoke(getProject(), getEditor(), getFile(), surrounder); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + SurroundWithHandler.invoke(getProject(), getEditor(), getFile(), surrounder); + } + }); + checkResultByFile(BASE_PATH + fileName + "_after.java"); } private void doTestWithTemplateFinish(@NotNull String fileName, Surrounder surrounder, @Nullable String textToType) { TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable()); configureByFile(BASE_PATH + fileName + ".java"); - SurroundWithHandler.invoke(getProject(), getEditor(), getFile(), surrounder); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + SurroundWithHandler.invoke(getProject(), getEditor(), getFile(), surrounder); + } + }); + if (textToType != null) { type(textToType); } diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/intention/SplitIfActionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/intention/SplitIfActionTest.java index c9653c3eabdb..6cef301c8b1c 100644 --- a/java/java-tests/testSrc/com/intellij/codeInsight/intention/SplitIfActionTest.java +++ b/java/java-tests/testSrc/com/intellij/codeInsight/intention/SplitIfActionTest.java @@ -1,6 +1,22 @@ +/* + * Copyright 2000-2016 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ package com.intellij.codeInsight.intention; import com.intellij.codeInsight.intention.impl.SplitIfAction; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.testFramework.LightCodeInsightTestCase; @@ -61,6 +77,11 @@ public class SplitIfActionTest extends LightCodeInsightTestCase { private void perform() throws Exception { SplitIfAction action = new SplitIfAction(); assertTrue(action.isAvailable(getProject(), getEditor(), getFile())); - action.invoke(getProject(), getEditor(), getFile()); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + action.invoke(getProject(), getEditor(), getFile()); + } + }); } } diff --git a/java/java-tests/testSrc/com/intellij/editor/LineSetIncrementalUpdateTest.java b/java/java-tests/testSrc/com/intellij/editor/LineSetIncrementalUpdateTest.java index b8465edc3136..1fb719f8f765 100644 --- a/java/java-tests/testSrc/com/intellij/editor/LineSetIncrementalUpdateTest.java +++ b/java/java-tests/testSrc/com/intellij/editor/LineSetIncrementalUpdateTest.java @@ -1,3 +1,19 @@ +/* + * Copyright 2000-2016 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. + */ + /* * Created by IntelliJ IDEA. * User: Maxim.Mossienko @@ -6,6 +22,7 @@ */ package com.intellij.editor; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.impl.LineSet; import com.intellij.testFramework.LightCodeInsightTestCase; @@ -55,46 +72,56 @@ public class LineSetIncrementalUpdateTest extends LightCodeInsightTestCase { } private static void doInsert() { - Document document = myEditor.getDocument(); - document.insertString(myEditor.getCaretModel().getOffset(), STRING6); - document.insertString(myEditor.getCaretModel().getOffset(), STRING5); - document.insertString(myEditor.getCaretModel().getOffset(), STRING4); - document.insertString(myEditor.getCaretModel().getOffset(), STRING3); - document.insertString(myEditor.getCaretModel().getOffset(), STRING2); - document.insertString(myEditor.getCaretModel().getOffset(), STRING1); + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + Document document = myEditor.getDocument(); + document.insertString(myEditor.getCaretModel().getOffset(), STRING6); + document.insertString(myEditor.getCaretModel().getOffset(), STRING5); + document.insertString(myEditor.getCaretModel().getOffset(), STRING4); + document.insertString(myEditor.getCaretModel().getOffset(), STRING3); + document.insertString(myEditor.getCaretModel().getOffset(), STRING2); + document.insertString(myEditor.getCaretModel().getOffset(), STRING1); + } + }.execute().throwException(); } private static void doDelete() { - Document document = myEditor.getDocument(); + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + Document document = myEditor.getDocument(); - document.deleteString( - myEditor.getCaretModel().getOffset(), - myEditor.getCaretModel().getOffset() + STRING1.length() - ); + document.deleteString( + myEditor.getCaretModel().getOffset(), + myEditor.getCaretModel().getOffset() + STRING1.length() + ); - document.deleteString( - myEditor.getCaretModel().getOffset(), - myEditor.getCaretModel().getOffset() + STRING2.length() - ); + document.deleteString( + myEditor.getCaretModel().getOffset(), + myEditor.getCaretModel().getOffset() + STRING2.length() + ); - document.deleteString( - myEditor.getCaretModel().getOffset(), - myEditor.getCaretModel().getOffset() + STRING3.length() - ); + document.deleteString( + myEditor.getCaretModel().getOffset(), + myEditor.getCaretModel().getOffset() + STRING3.length() + ); - document.deleteString( - myEditor.getCaretModel().getOffset(), - myEditor.getCaretModel().getOffset() + STRING4.length() - ); + document.deleteString( + myEditor.getCaretModel().getOffset(), + myEditor.getCaretModel().getOffset() + STRING4.length() + ); - document.deleteString( - myEditor.getCaretModel().getOffset(), - myEditor.getCaretModel().getOffset() + STRING5.length() - ); + document.deleteString( + myEditor.getCaretModel().getOffset(), + myEditor.getCaretModel().getOffset() + STRING5.length() + ); - document.deleteString( - myEditor.getCaretModel().getOffset(), - myEditor.getCaretModel().getOffset() + STRING6.length() - ); + document.deleteString( + myEditor.getCaretModel().getOffset(), + myEditor.getCaretModel().getOffset() + STRING6.length() + ); + } + }.execute().throwException(); } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingExceptionTest.java b/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingExceptionTest.java index 9d148d34d6bb..8179876c4414 100644 --- a/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingExceptionTest.java +++ b/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -43,9 +43,4 @@ public class FoldingExceptionTest extends LightCodeInsightTestCase { PsiDocumentManager.getInstance(ourProject).commitAllDocuments(); CodeInsightTestFixtureImpl.instantiateAndRun(myFile, myEditor, new int[]{Pass.UPDATE_ALL, Pass.LOCAL_INSPECTIONS}, false); } - - @Override - protected boolean isRunInWriteAction() { - return false; - } } diff --git a/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingProcessingOnDocumentModificationTest.java b/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingProcessingOnDocumentModificationTest.java index ff8aae2a0192..c987402b9574 100644 --- a/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingProcessingOnDocumentModificationTest.java +++ b/java/java-tests/testSrc/com/intellij/openapi/editor/impl/FoldingProcessingOnDocumentModificationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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.openapi.editor.impl; import com.intellij.codeInsight.folding.CodeFoldingManager; import com.intellij.openapi.actionSystem.IdeActions; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.CaretModel; import com.intellij.openapi.editor.FoldRegion; import com.intellij.psi.PsiDocumentManager; @@ -80,11 +81,24 @@ public class FoldingProcessingOnDocumentModificationTest extends AbstractEditorT "}"); executeAction(IdeActions.ACTION_COLLAPSE_ALL_REGIONS); checkFoldingState("[FoldRegion +(25:33), placeholder='{...}']"); - - myEditor.getDocument().insertString(0, "/*"); + + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + myEditor.getDocument().insertString(0, "/*"); + } + }.execute().throwException(); + checkFoldingState("[FoldRegion -(0:37), placeholder='/.../', FoldRegion +(27:35), placeholder='{...}']"); - - myEditor.getDocument().deleteString(0, 2); + + WriteCommandAction.runWriteCommandAction(getProject(), + new Runnable() { + @Override + public void run() { + myEditor.getDocument().deleteString(0, 2); + } + }); + checkFoldingState("[FoldRegion +(25:33), placeholder='{...}']"); } @@ -97,7 +111,13 @@ public class FoldingProcessingOnDocumentModificationTest extends AbstractEditorT executeAction(IdeActions.ACTION_COLLAPSE_ALL_REGIONS); checkFoldingState("[FoldRegion +(25:33), placeholder='{...}']"); - myEditor.getDocument().insertString(0, "/*"); + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + myEditor.getDocument().insertString(0, "/*"); + } + }.execute().throwException(); + checkFoldingState("[FoldRegion -(0:37), placeholder='/.../', FoldRegion +(27:35), placeholder='{...}']"); executeAction(IdeActions.ACTION_EXPAND_ALL_REGIONS); diff --git a/java/java-tests/testSrc/com/intellij/psi/TreeIsCorrectAfterDiffReparseTest.java b/java/java-tests/testSrc/com/intellij/psi/TreeIsCorrectAfterDiffReparseTest.java index ef874519d512..c959ac753f4f 100644 --- a/java/java-tests/testSrc/com/intellij/psi/TreeIsCorrectAfterDiffReparseTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/TreeIsCorrectAfterDiffReparseTest.java @@ -1,8 +1,25 @@ +/* + * Copyright 2000-2016 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /* * @author max */ package com.intellij.psi; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.psi.impl.DebugUtil; import com.intellij.testFramework.LightCodeInsightTestCase; @@ -1084,7 +1101,13 @@ public class TreeIsCorrectAfterDiffReparseTest extends LightCodeInsightTestCase final PsiDocumentManager docManager = PsiDocumentManager.getInstance(ourProject); final Document doc = docManager.getDocument(myFile); - doc.insertString(part1.length(), "/**"); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + doc.insertString(part1.length(), "/**"); + } + }); + boolean old = DebugUtil.CHECK; DebugUtil.CHECK = true; diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java index 86b876d97918..bb907f068e78 100644 --- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2016 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.psi.formatter.java; import com.intellij.lang.java.JavaLanguage; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; @@ -168,7 +169,13 @@ public class JavaFormatterInEditorTest extends LightPlatformCodeInsightTestCase public void doTest(@NotNull String before, @NotNull String after) throws IOException { configureFromFileText(getTestName(false) + ".java", before); - CodeStyleManager.getInstance(getProject()).reformatText(getFile(), 0, getEditor().getDocument().getTextLength()); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + CodeStyleManager.getInstance(getProject()).reformatText(getFile(), 0, getEditor().getDocument().getTextLength()); + } + }); + checkResultByText(after); } } \ No newline at end of file diff --git a/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ExtendsBoundListTest.java b/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ExtendsBoundListTest.java index 85aa78f3c4a4..275da0cfea86 100644 --- a/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ExtendsBoundListTest.java +++ b/java/java-tests/testSrc/com/intellij/psi/impl/source/tree/java/ExtendsBoundListTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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,7 +66,13 @@ public class ExtendsBoundListTest extends LightCodeInsightTestCase { final PsiClass cloneableClass = getJavaFacade().findClass("java.lang.Cloneable"); assertNotNull(cloneableClass); final PsiJavaCodeReferenceElement reference = getJavaFacade().getElementFactory().createClassReferenceElement(cloneableClass); - extendsList.addAfter(reference, extendsList.getReferenceElements()[0]); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + extendsList.addAfter(reference, extendsList.getReferenceElements()[0]); + } + }); + check(); } @@ -76,7 +82,13 @@ public class ExtendsBoundListTest extends LightCodeInsightTestCase { final PsiClass cloneableClass = getJavaFacade().findClass("java.lang.Cloneable"); assertNotNull(cloneableClass); final PsiJavaCodeReferenceElement reference = getJavaFacade().getElementFactory().createClassReferenceElement(cloneableClass); - extendsList.addBefore(reference, extendsList.getReferenceElements()[0]); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + extendsList.addBefore(reference, extendsList.getReferenceElements()[0]); + } + }); + check(); } @@ -86,7 +98,13 @@ public class ExtendsBoundListTest extends LightCodeInsightTestCase { final PsiClass cloneableClass = getJavaFacade().findClass("java.lang.Cloneable"); assertNotNull(cloneableClass); final PsiJavaCodeReferenceElement reference = getJavaFacade().getElementFactory().createClassReferenceElement(cloneableClass); - extendsList.addBefore(reference, null); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + extendsList.addBefore(reference, null); + } + }); + check(); } @@ -96,7 +114,13 @@ public class ExtendsBoundListTest extends LightCodeInsightTestCase { final PsiClass cloneableClass = getJavaFacade().findClass(CommonClassNames.JAVA_LANG_RUNNABLE); assertNotNull(cloneableClass); final PsiJavaCodeReferenceElement reference = getJavaFacade().getElementFactory().createClassReferenceElement(cloneableClass); - extendsList.add(reference); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + extendsList.add(reference); + } + }); + check(); } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java b/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java index c479f1dc3e35..27032f4532cf 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/ExtractMethodTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2012 JetBrains s.r.o. + * Copyright 2000-2016 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.refactoring; import com.intellij.JavaTestUtil; import com.intellij.codeInsight.CodeInsightUtil; import com.intellij.lang.java.JavaLanguage; +import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.*; @@ -919,7 +920,12 @@ public class ExtractMethodTest extends LightCodeInsightTestCase { for (final Match match : duplicates) { if (!match.getMatchStart().isValid() || !match.getMatchEnd().isValid()) continue; PsiDocumentManager.getInstance(project).commitAllDocuments(); - processor.processMatch(match); + ApplicationManager.getApplication().runWriteAction(new Runnable() { + @Override + public void run() { + processor.processMatch(match); + } + }); } } } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/InplaceIntroduceParameterTest.java b/java/java-tests/testSrc/com/intellij/refactoring/InplaceIntroduceParameterTest.java index 60febdf8401e..f3ebda6c62cc 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/InplaceIntroduceParameterTest.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/InplaceIntroduceParameterTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -215,8 +215,4 @@ public class InplaceIntroduceParameterTest extends AbstractJavaInplaceIntroduceT return super.invokeImpl(project, localVariable, editor); } } - @Override - protected boolean isRunInWriteAction() { - return false; - } } diff --git a/java/java-tests/testSrc/com/intellij/refactoring/LightRefactoringTestCase.java b/java/java-tests/testSrc/com/intellij/refactoring/LightRefactoringTestCase.java index 713b26edbb59..5333bb36250d 100644 --- a/java/java-tests/testSrc/com/intellij/refactoring/LightRefactoringTestCase.java +++ b/java/java-tests/testSrc/com/intellij/refactoring/LightRefactoringTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,8 +18,4 @@ package com.intellij.refactoring; import com.intellij.testFramework.LightCodeInsightTestCase; public abstract class LightRefactoringTestCase extends LightCodeInsightTestCase{ - @Override - protected boolean isRunInWriteAction() { - return false; - } } diff --git a/java/java-tests/testSrc/com/intellij/testIntergration/RecentTestsTest.kt b/java/java-tests/testSrc/com/intellij/testIntergration/RecentTestsTest.kt index 80aba33b4705..2189f6b46cbb 100644 --- a/java/java-tests/testSrc/com/intellij/testIntergration/RecentTestsTest.kt +++ b/java/java-tests/testSrc/com/intellij/testIntergration/RecentTestsTest.kt @@ -17,14 +17,11 @@ package com.intellij.testIntergration import com.intellij.execution.Location import com.intellij.execution.TestStateStorage -import com.intellij.execution.testframework.JavaTestLocator import com.intellij.execution.testframework.sm.runner.states.TestStateInfo import com.intellij.openapi.vfs.VirtualFileManager -import com.intellij.testIntegration.RecentTestRunner -import com.intellij.testIntegration.SelectTestStep +import com.intellij.testFramework.LightIdeaTestCase +import com.intellij.testIntegration.* import org.assertj.core.api.Assertions.assertThat -import org.junit.Ignore -import org.junit.Test import org.mockito.Matchers import org.mockito.Mockito.`when` import org.mockito.Mockito.mock @@ -33,8 +30,8 @@ import java.util.* fun passed(date: Date) = TestStateStorage.Record(TestStateInfo.Magnitude.PASSED_INDEX.value, date) fun failed(date: Date) = TestStateStorage.Record(TestStateInfo.Magnitude.FAILED_INDEX.value, date) -class RecentTestsStepTest { - val runner = createRunner() +class RecentTestsStepTest: LightIdeaTestCase() { + val runner = mock(RecentTestRunner::class.java) val passed = passed(Date(0)) val failed = failed(Date(0)) @@ -42,14 +39,14 @@ class RecentTestsStepTest { class TestStorage { private val map: MutableMap = hashMapOf() - fun addSuite(name: String, pass: Boolean, date: Date = Date(0)) { + fun addSuite(name: String, pass: Boolean, date: Date = Date(0), language: String = "java") { val magnitude = if (pass) TestStateInfo.Magnitude.PASSED_INDEX else TestStateInfo.Magnitude.FAILED_INDEX - addSuite(name, magnitude, date) + addSuite(name, magnitude, date, language) } - fun addSuite(name: String, magnitude: TestStateInfo.Magnitude, date: Date = Date(0)) { + fun addSuite(name: String, magnitude: TestStateInfo.Magnitude, date: Date = Date(0), language: String = "java") { val record = TestStateStorage.Record(magnitude.value, date) - map.put("java:suite://$name", record) + map.put("$language:suite://$name", record) } fun addTest(name: String, magnitude: TestStateInfo.Magnitude, date: Date = Date(0)) { @@ -63,23 +60,27 @@ class RecentTestsStepTest { } fun getMap() = map + + fun getSuite(name: String, language: String = "java") = map["$language:suite://$name"] + + fun removeUrl(url: String) { + map.remove(url) + } } - @Test - fun `show sorted by date`() { + fun `test show sorted by date`() { val storage = TestStorage() storage.addSuite("ASTest", true, Date(1000)) storage.addSuite("JSTest", true, Date(1200)) - val step = SelectTestStep(storage.getMap(), runner) - val values = step.values.map { VirtualFileManager.extractPath(it) } + val sortedUrlList = getSortedList(storage.getMap()) + val values = sortedUrlList.map { VirtualFileManager.extractPath(it) } assertThat(values).isEqualTo(listOf("JSTest", "ASTest")) } - @Test - fun `show tests sorted by date`() { + fun `test show tests sorted by date`() { val storage = TestStorage() storage.addSuite("ASTest", false, Date(0)) @@ -89,27 +90,25 @@ class RecentTestsStepTest { storage.addTest("ASTest.cccc", false, Date(20000)) storage.addTest("ASTest.bbbb", false, Date(30000)) - val step = SelectTestStep(storage.getMap(), runner) - val values = step.values.map { VirtualFileManager.extractPath(it) } + val sortedUrlList = getSortedList(storage.getMap()) + val values = sortedUrlList.map { VirtualFileManager.extractPath(it) } assertThat(values).isEqualTo(listOf("ASTest", "ASTest.bbbb", "ASTest.cccc", "ASTest.aaaa")) } - @Test - fun `show ignored`() { + fun `test show ignored`() { val storage = TestStorage() storage.addSuite("ASTest", TestStateInfo.Magnitude.IGNORED_INDEX) storage.addTest("ASTest.ignored", TestStateInfo.Magnitude.IGNORED_INDEX) storage.addTest("ASTest.passed", pass = true) - val step = SelectTestStep(storage.getMap(), runner) - val values = step.values.map { VirtualFileManager.extractPath(it) } + val sortedUrlList = getSortedList(storage.getMap()) + val values = sortedUrlList.map { VirtualFileManager.extractPath(it) } assertThat(values).isEqualTo(listOf("ASTest")) } - @Test - fun `when suite passed - show only suite`() { + fun `test when suite passed - show only suite`() { val map: MutableMap = hashMapOf() map.put("java:suite://JavaFormatterSuperDuperTest", passed) @@ -121,19 +120,36 @@ class RecentTestsStepTest { map.put("java:test://Test.textQQQ", passed) map.put("java:test://JavaFormatterSuperDuperTest.testUnconditionalAlignmentErrorneous", passed) - val step = SelectTestStep(map, runner) - val expected = listOf( "java:suite://JavaFormatterSuperDuperTest", "java:suite://Test" ) - assertThat(step.values).isEqualTo(expected) + val list = getSortedList(map) + assertThat(list).isEqualTo(expected) } + private fun getSortedList(map: MutableMap): List { + val provider = RecentTestsListProvider(map) + return provider.urlsToShowFromHistory + } - @Test - fun `show failed first`() { + + fun `test show only java tests`() { + val storage = TestStorage() + + storage.addSuite("JavaTest1", true) + storage.addSuite("JavaTest2", true) + + storage.addSuite("JsSuite1", true, Date(0), "js") + storage.addSuite("JsSuite2", true, Date(0), "js") + storage.addSuite("JsSuite3", true, Date(0), "js") + + val values = getSortedList(storage.getMap()) + assertThat(values.map { VirtualFileManager.extractPath(it) }).isEqualTo(listOf("JavaTest1", "JavaTest2")) + } + + fun `test show failed first`() { val map: MutableMap = hashMapOf() map.put("java:suite://JavaFormatterSuperDuperTest", failed) @@ -148,7 +164,7 @@ class RecentTestsStepTest { map.put("java:test://Test.textQQQ", passed) map.put("java:test://JavaFormatterSuperDuperTest.testUnconditionalAlignmentErrorneous", passed) - val step = SelectTestStep(map, runner) + val values = getSortedList(map) val expected = listOf( "java:test://JavaFormatterFailed.fail", @@ -158,11 +174,10 @@ class RecentTestsStepTest { "java:suite://Test" ) - assertThat(step.values).isEqualTo(expected) + assertThat(values).isEqualTo(expected) } - - @Test - fun `if failed more than 2 tests show suite first`() { + + fun `test if failed more than 2 tests show suite first`() { val storage = TestStorage() storage.addSuite("ASTest", false) storage.addTest("ASTest.failed1", false, Date(3000)) @@ -170,8 +185,8 @@ class RecentTestsStepTest { storage.addTest("ASTest.failed3", false, Date(1000)) storage.addTest("ASTest.passed1", true) - val step = SelectTestStep(storage.getMap(), runner) - val values = step.values.map { VirtualFileManager.extractPath(it) } + val sortedUrlList = getSortedList(storage.getMap()) + val values = sortedUrlList.map { VirtualFileManager.extractPath(it) } assertThat(values).isEqualTo(listOf( "ASTest", @@ -180,9 +195,8 @@ class RecentTestsStepTest { "ASTest.failed3" )) } - - @Test - fun `if failed less than 3 tests, show tests first`() { + + fun `test if failed less than 3 tests, show tests first`() { val storage = TestStorage() storage.addSuite("ASTest", false) @@ -190,8 +204,8 @@ class RecentTestsStepTest { storage.addTest("ASTest.failed2", false, Date(2000)) storage.addTest("ASTest.passed1", true) - val step = SelectTestStep(storage.getMap(), runner) - val values = step.values.map { VirtualFileManager.extractPath(it) } + val sortedUrlList = getSortedList(storage.getMap()) + val values = sortedUrlList.map { VirtualFileManager.extractPath(it) } assertThat(values).isEqualTo(listOf( "ASTest.failed1", @@ -199,9 +213,8 @@ class RecentTestsStepTest { "ASTest" )) } - - @Test - fun `if all failed show only suite`() { + + fun `test if all failed show only suite`() { val storage = TestStorage() storage.addSuite("ASTest", false) @@ -210,17 +223,33 @@ class RecentTestsStepTest { storage.addTest("ASTest.failed3", false) storage.addTest("ASTest.failed4", false) - val step = SelectTestStep(storage.getMap(), runner) - val values = step.values.map { VirtualFileManager.extractPath(it) } + val sortedUrlList = getSortedList(storage.getMap()) + val values = sortedUrlList.map { VirtualFileManager.extractPath(it) } assertThat(values).isEqualTo(listOf("ASTest")) } - @Ignore - @Test - fun `do not show urls without location`() { - val storage = TestStorage() + private fun locatorReturningNullIfContains(substring: String): TestLocator { + val locator = mock(TestLocator::class.java) + `when`(locator.getLocation(Matchers.anyString())).thenAnswer { + val url = it.arguments[0] as String + if (url.contains(substring)) null else mock(Location::class.java) + } + return locator + } + + fun `test shown value without protocol`() { + val step = SelectTestStep(emptyList(), emptyMap(), runner, mock(TestLocator::class.java)) + var shownValue = step.getTextFor("java:suite://JavaFormatterSuperDuperTest") + assertThat(shownValue).isEqualTo("JavaFormatterSuperDuperTest") + shownValue = step.getTextFor("java:test://JavaFormatterSuperDuperTest.testItMakesMeSadToFixIt") + assertThat(shownValue).isEqualTo("JavaFormatterSuperDuperTest.testItMakesMeSadToFixIt") + } + + fun `test do not show urls which we can locate without location`() { + val storage = TestStorage() + storage.addSuite("ASTest", true) storage.addSuite("BSTest", false) storage.addTest("BSTest.fff", false) @@ -229,34 +258,47 @@ class RecentTestsStepTest { storage.addTest("", false) storage.addSuite("", false) - val step = SelectTestStep(storage.getMap(), runner) - val values = step.values.map { VirtualFileManager.extractPath(it) } - - assertThat(values).isEqualTo(listOf("BSTest", "BSTest.fff", "ASTest")) + val testStorageMock = createMockStorage(storage) + + val map = storage.getMap() + + val cleaner = DeadTestsCleaner(testStorageMock, map.keys.toList(), locatorReturningNullIfContains("<")) + cleaner.run() + + val sortedUrlList = getSortedList(storage.getMap()) + val values = sortedUrlList.map { VirtualFileManager.extractPath(it) } + + assertThat(values).isEqualTo(listOf("BSTest.fff", "BSTest", "ASTest")) + assertThat(storage.getSuite("")).isEqualTo(null) } - private fun createRunner(): RecentTestRunner { - val runner = mock(RecentTestRunner::class.java) - `when`(runner.isSuite(Matchers.anyString())).thenAnswer { - val url = it.arguments[0] as String - val protocol = VirtualFileManager.extractProtocol(url) - JavaTestLocator.SUITE_PROTOCOL.startsWith(protocol.toString()) - } - `when`(runner.getLocation(Matchers.anyString())).thenAnswer { - val url = it.arguments[0] as String - if (url.contains("<")) null else mock(Location::class.java) - } - return runner + fun `test do not remove tests if we are unable to locate them`() { + val storage = TestStorage() + + storage.addSuite("ASTest", true) + + storage.addSuite("JsSuite1", true, Date(), "js") + storage.addSuite("JsSuite2", true, Date(), "js") + + val testStorageMock = createMockStorage(storage) + + val sortedUrlList = getSortedList(storage.getMap()) + + val cleaner = DeadTestsCleaner(testStorageMock, sortedUrlList, locatorReturningNullIfContains("JsSuite")) + cleaner.run() + + assertThat(storage.getSuite("JsSuite1", "js")).isNotEqualTo(null) + assertThat(storage.getSuite("JsSuite2", "js")).isNotEqualTo(null) } - @Test - fun `shown value without protocol`() { - val step = SelectTestStep(emptyMap(), runner) - var shownValue = step.getTextFor("java:suite://JavaFormatterSuperDuperTest") - assertThat(shownValue).isEqualTo("JavaFormatterSuperDuperTest") - - shownValue = step.getTextFor("java:test://JavaFormatterSuperDuperTest.testItMakesMeSadToFixIt") - assertThat(shownValue).isEqualTo("JavaFormatterSuperDuperTest.testItMakesMeSadToFixIt") + private fun createMockStorage(storage: TestStorage): TestStateStorage? { + val testStorageMock = mock(TestStateStorage::class.java) + `when`(testStorageMock.removeState(Matchers.anyString())).then { + val url = it.arguments[0]as String + storage.removeUrl(url) + } + return testStorageMock } - + + } \ No newline at end of file diff --git a/java/typeMigration/test/com/intellij/refactoring/ChangeTypeSignatureTest.java b/java/typeMigration/test/com/intellij/refactoring/ChangeTypeSignatureTest.java index 782ac2ec09df..50137dc0b9e9 100644 --- a/java/typeMigration/test/com/intellij/refactoring/ChangeTypeSignatureTest.java +++ b/java/typeMigration/test/com/intellij/refactoring/ChangeTypeSignatureTest.java @@ -1,3 +1,19 @@ +/* + * Copyright 2000-2016 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. + */ + /* * User: anna * Date: 18-Mar-2008 @@ -8,7 +24,6 @@ import com.intellij.psi.*; import com.intellij.psi.impl.source.PsiImmediateClassType; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.util.PsiTreeUtil; -import com.intellij.refactoring.typeMigration.TypeMigrationLabeler; import com.intellij.refactoring.typeMigration.TypeMigrationProcessor; import com.intellij.refactoring.typeMigration.TypeMigrationRules; import com.intellij.testFramework.LightCodeInsightTestCase; @@ -143,9 +158,4 @@ public class ChangeTypeSignatureTest extends LightCodeInsightTestCase { public void testMethodReturnTypeMigration() throws Exception { doTest(true, "java.lang.Integer"); } - - @Override - protected boolean isRunInWriteAction() { - return false; - } } \ No newline at end of file diff --git a/jps/jps-builders/src/org/jetbrains/jps/api/TaskFutureAdapter.java b/jps/jps-builders/src/org/jetbrains/jps/api/TaskFutureAdapter.java new file mode 100644 index 000000000000..8d7fe84ffb8a --- /dev/null +++ b/jps/jps-builders/src/org/jetbrains/jps/api/TaskFutureAdapter.java @@ -0,0 +1,90 @@ +/* + * Copyright 2000-2016 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.jps.api; + +import org.jetbrains.annotations.NotNull; + +import java.util.concurrent.*; + +/** + * Makes TaskFuture from the supplied Future + */ +public class TaskFutureAdapter implements TaskFuture { + @NotNull private final Future myFuture; + + public TaskFutureAdapter(@NotNull Future future) { + myFuture = future; + } + + @Override + public void waitFor() { + try { + get(); + } + catch (InterruptedException e) { + throw new RuntimeException(e); + } + catch (ExecutionException e) { + throw new RuntimeException(e); + } + catch (CancellationException ignored) { + } + } + + @Override + public boolean waitFor(long timeout, TimeUnit unit) { + try { + get(timeout, unit); + } + catch (InterruptedException e) { + throw new RuntimeException(e); + } + catch (ExecutionException e) { + throw new RuntimeException(e); + } + catch (TimeoutException ignored) { + } + catch (CancellationException ignored) { + } + return isDone(); + } + + // delegates + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return myFuture.cancel(mayInterruptIfRunning); + } + + @Override + public boolean isCancelled() { + return myFuture.isCancelled(); + } + + @Override + public boolean isDone() { + return myFuture.isDone(); + } + + @Override + public T get() throws InterruptedException, ExecutionException { + return myFuture.get(); + } + + @Override + public T get(long timeout, @NotNull TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + return myFuture.get(timeout, unit); + } +} diff --git a/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceResolver.java b/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceResolver.java index 3f11fb6c7458..209b3d82e623 100644 --- a/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceResolver.java +++ b/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceResolver.java @@ -1,10 +1,29 @@ +/* + * Copyright 2000-2016 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.psi.impl.source.resolve.reference.impl.providers; import com.intellij.psi.PsiFileSystemItem; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Collection; + public interface FileReferenceResolver { @Nullable PsiFileSystemItem resolveFileReference(@NotNull FileReference reference, @NotNull String name); + + Collection getVariants(@NotNull FileReference reference); } \ No newline at end of file diff --git a/platform/built-in-server/testSrc/BuiltInWebServerTest.kt b/platform/built-in-server/testSrc/BuiltInWebServerTest.kt index 9b15e9c9a618..899d21dc4248 100644 --- a/platform/built-in-server/testSrc/BuiltInWebServerTest.kt +++ b/platform/built-in-server/testSrc/BuiltInWebServerTest.kt @@ -35,7 +35,7 @@ private class BuiltInWebServerTest : BuiltInServerTestCase() { private fun testIndex(vararg paths: String) { val project = BuiltInServerTestCase.projectRule.project - val newPath = tempDirManager.newPath(refreshVfs = false) + val newPath = tempDirManager.newPath() newPath.writeChild(manager.filePath!!, "hello") newPath.refreshVfs() diff --git a/platform/built-in-server/testSrc/TestManager.kt b/platform/built-in-server/testSrc/TestManager.kt index feaab3eb56ea..20339c80eded 100644 --- a/platform/built-in-server/testSrc/TestManager.kt +++ b/platform/built-in-server/testSrc/TestManager.kt @@ -49,7 +49,7 @@ internal class TestManager(val projectRule: ProjectRule, private val tempDirMana projectRule.project if (filePath!! == "_tmp_") { - val file = tempDirManager.newPath(".txt") + val file = tempDirManager.newPath(".txt", refreshVfs = true) if (!annotation!!.doNotCreate) { file.createFile() } diff --git a/platform/configuration-store-impl/src/DirectoryBasedStorage.kt b/platform/configuration-store-impl/src/DirectoryBasedStorage.kt index e4b2f3fb99a8..ec04f166a574 100644 --- a/platform/configuration-store-impl/src/DirectoryBasedStorage.kt +++ b/platform/configuration-store-impl/src/DirectoryBasedStorage.kt @@ -33,14 +33,15 @@ import com.intellij.util.LineSeparator import com.intellij.util.SmartList import com.intellij.util.SystemProperties import com.intellij.util.containers.SmartHashSet +import com.intellij.util.systemIndependentPath import gnu.trove.THashMap import org.jdom.Element -import java.io.File import java.io.FileNotFoundException import java.io.IOException import java.nio.ByteBuffer +import java.nio.file.Path -open class DirectoryBasedStorage(private val dir: File, +open class DirectoryBasedStorage(private val dir: Path, private val splitter: StateSplitter, private val pathMacroSubstitutor: TrackingPathMacroSubstitutor? = null) : StateStorageBase() { private @Volatile var virtualFile: VirtualFile? = null @@ -93,7 +94,7 @@ open class DirectoryBasedStorage(private val dir: File, private fun getVirtualFile(): VirtualFile? { var result = virtualFile if (result == null) { - result = LocalFileSystem.getInstance().findFileByIoFile(dir) + result = LocalFileSystem.getInstance().findFileByPath(dir.systemIndependentPath) virtualFile = result } return result diff --git a/platform/configuration-store-impl/src/SchemeManagerFactoryImpl.kt b/platform/configuration-store-impl/src/SchemeManagerFactoryImpl.kt index adc612723f3b..6508108e5882 100644 --- a/platform/configuration-store-impl/src/SchemeManagerFactoryImpl.kt +++ b/platform/configuration-store-impl/src/SchemeManagerFactoryImpl.kt @@ -27,7 +27,8 @@ import com.intellij.openapi.project.Project import com.intellij.util.SmartList import com.intellij.util.containers.ContainerUtil import com.intellij.util.lang.CompoundRuntimeException -import java.io.File +import java.nio.file.Path +import java.nio.file.Paths const val ROOT_CONFIG = "\$ROOT_CONFIG$" @@ -59,7 +60,7 @@ sealed class SchemeManagerFactoryBase : SchemesManagerFactory(), SettingsSavingC return originalPath } - abstract fun pathToFile(path: String, storageManager: StateStorageManager): File + abstract fun pathToFile(path: String, storageManager: StateStorageManager): Path fun process(processor: (SchemeManagerImpl) -> Unit) { for (manager in managers) { @@ -100,12 +101,12 @@ sealed class SchemeManagerFactoryBase : SchemesManagerFactory(), SettingsSavingC return path } - override fun pathToFile(path: String, storageManager: StateStorageManager) = File(storageManager.expandMacros("$ROOT_CONFIG/$path")) + override fun pathToFile(path: String, storageManager: StateStorageManager) = Paths.get(storageManager.expandMacros(ROOT_CONFIG), path) } private class ProjectSchemeManagerFactory(private val project: Project) : SchemeManagerFactoryBase() { override val componentManager = project - override fun pathToFile(path: String, storageManager: StateStorageManager) = File(project.basePath, if (ProjectUtil.isDirectoryBased(project)) "${Project.DIRECTORY_STORE_FOLDER}/$path" else ".$path") + override fun pathToFile(path: String, storageManager: StateStorageManager) = Paths.get(project.basePath, if (ProjectUtil.isDirectoryBased(project)) "${Project.DIRECTORY_STORE_FOLDER}/$path" else ".$path") } } \ No newline at end of file diff --git a/platform/configuration-store-impl/src/SchemeManagerImpl.kt b/platform/configuration-store-impl/src/SchemeManagerImpl.kt index f7679f1de56a..7c933590c7a5 100644 --- a/platform/configuration-store-impl/src/SchemeManagerImpl.kt +++ b/platform/configuration-store-impl/src/SchemeManagerImpl.kt @@ -35,28 +35,24 @@ import com.intellij.openapi.util.text.StringUtilRt import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.newvfs.NewVirtualFile import com.intellij.openapi.vfs.tracker.VirtualFileTracker -import com.intellij.util.PathUtil -import com.intellij.util.PathUtilRt -import com.intellij.util.SmartList -import com.intellij.util.ThrowableConvertor +import com.intellij.util.* import com.intellij.util.containers.ContainerUtil import com.intellij.util.io.URLUtil import com.intellij.util.text.UniqueNameGenerator import gnu.trove.THashMap import gnu.trove.THashSet import gnu.trove.TObjectObjectProcedure -import gnu.trove.TObjectProcedure import org.jdom.Document import org.jdom.Element -import java.io.File import java.io.IOException import java.io.InputStream +import java.nio.file.Path import java.util.* class SchemeManagerImpl(val fileSpec: String, private val processor: SchemeProcessor, private val provider: StreamProvider?, - private val ioDirectory: File, + private val ioDirectory: Path, val roamingType: RoamingType = RoamingType.DEFAULT, virtualFileTrackerDisposable: Disposable? = null, val presentableName: String? = null) : SchemesManager(), SafeWriteRequestor { @@ -104,7 +100,7 @@ class SchemeManagerImpl(val fileSpec: Stri private fun refreshVirtualDirectoryAndAddListener(virtualFileTrackerDisposable: Disposable?) { // store refreshes root directory, so, we don't need to use refreshAndFindFile - val directory = LocalFileSystem.getInstance().findFileByIoFile(ioDirectory) ?: return + val directory = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) ?: return this.directory = directory directory.children @@ -118,7 +114,7 @@ class SchemeManagerImpl(val fileSpec: Stri } private fun addVfsListener(virtualFileTrackerDisposable: Disposable?) { - service().addTracker("${LocalFileSystem.PROTOCOL_PREFIX}${ioDirectory.absolutePath.replace(File.separatorChar, '/')}", object : VirtualFileAdapter() { + service().addTracker("${LocalFileSystem.PROTOCOL_PREFIX}${ioDirectory.toAbsolutePath().systemIndependentPath}", object : VirtualFileAdapter() { override fun contentsChanged(event: VirtualFileEvent) { if (event.requestor != null || !isMy(event)) { return @@ -268,17 +264,17 @@ class SchemeManagerImpl(val fileSpec: Stri } } else { - ioDirectory.listFiles({ parent, name -> canRead(name) })?.let { + ioDirectory.directoryStreamIfExists({ canRead(it.fileName.toString()) }) { for (file in it) { - if (file.isDirectory) { + if (file.isDirectory()) { continue } try { - loadScheme(file.name, file.inputStream(), true) + loadScheme(file.fileName.toString(), file.inputStream(), true) } catch (e: Throwable) { - LOG.error("Cannot read scheme ${file.path}", e) + LOG.error("Cannot read scheme $file", e) } } } @@ -467,16 +463,16 @@ class SchemeManagerImpl(val fileSpec: Stri } private fun removeDirectoryIfEmpty(errors: MutableList) { - ioDirectory.listFiles()?.let { + ioDirectory.directoryStreamIfExists { for (file in it) { - if (!file.isHidden) { - LOG.info("Directory ${ioDirectory.name} is not deleted: at least one file ${file.name} exists") - return + if (!file.isHidden()) { + LOG.info("Directory ${ioDirectory.fileName} is not deleted: at least one file ${file.fileName} exists") + return@removeDirectoryIfEmpty } } } - LOG.info("Remove schemes directory ${ioDirectory.name}") + LOG.info("Remove schemes directory ${ioDirectory.fileName}") directory = null var deleteUsingIo = !useVfs @@ -496,7 +492,7 @@ class SchemeManagerImpl(val fileSpec: Stri } if (deleteUsingIo) { - errors.catch { FileUtil.delete(ioDirectory) } + errors.catch { ioDirectory.deleteRecursively() } } } @@ -581,7 +577,7 @@ class SchemeManagerImpl(val fileSpec: Stri if (renamed) { externalInfo!!.scheduleDelete() } - FileUtil.writeToFile(File(ioDirectory, fileName), byteOut.internalBuffer, 0, byteOut.size()) + ioDirectory.resolve(fileName).write(byteOut.internalBuffer, 0, byteOut.size()) } } else { @@ -655,7 +651,7 @@ class SchemeManagerImpl(val fileSpec: Stri if (deleteUsingIo) { for (name in filesToDelete) { - errors.catch { FileUtil.delete(File(ioDirectory, name)) } + errors.catch { ioDirectory.resolve(name).delete() } } } @@ -665,13 +661,13 @@ class SchemeManagerImpl(val fileSpec: Stri private fun getDirectory(): VirtualFile? { var result = directory if (result == null) { - result = LocalFileSystem.getInstance().findFileByIoFile(ioDirectory) + result = LocalFileSystem.getInstance().findFileByPath(ioDirectory.systemIndependentPath) directory = result } return result } - override fun getRootDirectory() = ioDirectory + override fun getRootDirectory() = ioDirectory.toFile() override fun setSchemes(newSchemes: List, newCurrentScheme: T?, removeCondition: Condition?) { val oldCurrentScheme = currentScheme @@ -705,25 +701,23 @@ class SchemeManagerImpl(val fileSpec: Stri return } - schemeToInfo.retainEntries(object : TObjectObjectProcedure { - override fun execute(scheme: E, info: ExternalInfo): Boolean { - if (readOnlyExternalizableSchemes[scheme.name] == scheme) { - return true - } - - for (t in newSchemes) { - // by identity - if (t === scheme) { - if (filesToDelete.isNotEmpty()) { - filesToDelete.remove("${info.fileName}") - } - return true - } - } - - info.scheduleDelete() - return false + schemeToInfo.retainEntries(TObjectObjectProcedure { scheme, info -> + if (readOnlyExternalizableSchemes[scheme.name] == scheme) { + return@TObjectObjectProcedure true } + + for (t in newSchemes) { + // by identity + if (t === scheme) { + if (filesToDelete.isNotEmpty()) { + filesToDelete.remove("${info.fileName}") + } + return@TObjectObjectProcedure true + } + } + + info.scheduleDelete() + false }) } @@ -777,12 +771,10 @@ class SchemeManagerImpl(val fileSpec: Stri } override fun clearAllSchemes() { - schemeToInfo.forEachValue(object : TObjectProcedure { - override fun execute(info: ExternalInfo): Boolean { - info.scheduleDelete() - return true - } - }) + schemeToInfo.forEachValue { + it.scheduleDelete() + true + } currentScheme = null schemes.clear() @@ -895,11 +887,11 @@ private inline fun MutableList.catch(runnable: () -> Unit) { } } -fun createDir(ioDir: File, requestor: Any): VirtualFile { - ioDir.mkdirs() +fun createDir(ioDir: Path, requestor: Any): VirtualFile { + ioDir.createDirectories() val parentFile = ioDir.parent - val parentVirtualFile = (if (parentFile == null) null else VfsUtil.createDirectoryIfMissing(parentFile)) ?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile)) - return getFile(ioDir.name, parentVirtualFile, requestor) + val parentVirtualFile = (if (parentFile == null) null else VfsUtil.createDirectoryIfMissing(parentFile.systemIndependentPath)) ?: throw IOException(ProjectBundle.message("project.configuration.save.file.not.found", parentFile)) + return getFile(ioDir.fileName.toString(), parentVirtualFile, requestor) } fun getFile(fileName: String, parent: VirtualFile, requestor: Any): VirtualFile { diff --git a/platform/configuration-store-impl/src/StateStorageManagerImpl.kt b/platform/configuration-store-impl/src/StateStorageManagerImpl.kt index 2d1af6710f58..aafb5ea8b1ee 100644 --- a/platform/configuration-store-impl/src/StateStorageManagerImpl.kt +++ b/platform/configuration-store-impl/src/StateStorageManagerImpl.kt @@ -36,6 +36,8 @@ import org.jdom.Element import org.jetbrains.annotations.TestOnly import java.io.File import java.io.IOException +import java.nio.file.Path +import java.nio.file.Paths import java.util.* import java.util.concurrent.locks.ReentrantLock import java.util.regex.Pattern @@ -195,7 +197,7 @@ open class StateStorageManagerImpl(private val rootTagName: String, val filePath = expandMacros(collapsedPath) @Suppress("DEPRECATION") if (stateSplitter != StateSplitter::class.java && stateSplitter != StateSplitterEx::class.java) { - val storage = MyDirectoryStorage(this, File(filePath), ReflectionUtil.newInstance(stateSplitter)) + val storage = MyDirectoryStorage(this, Paths.get(filePath), ReflectionUtil.newInstance(stateSplitter)) virtualFileTracker?.put(filePath, storage) return storage } @@ -212,7 +214,7 @@ open class StateStorageManagerImpl(private val rootTagName: String, return storage } - private class MyDirectoryStorage(override val storageManager: StateStorageManagerImpl, file: File, @Suppress("DEPRECATION") splitter: StateSplitter) : + private class MyDirectoryStorage(override val storageManager: StateStorageManagerImpl, file: Path, @Suppress("DEPRECATION") splitter: StateSplitter) : DirectoryBasedStorage(file, splitter, storageManager.pathMacroSubstitutor), StorageVirtualFileTracker.TrackedStorage private class MyFileStorage(override val storageManager: StateStorageManagerImpl, diff --git a/platform/configuration-store-impl/testSrc/ApplicationStoreTest.kt b/platform/configuration-store-impl/testSrc/ApplicationStoreTest.kt index 1687463a16e4..b41c71fc1eff 100644 --- a/platform/configuration-store-impl/testSrc/ApplicationStoreTest.kt +++ b/platform/configuration-store-impl/testSrc/ApplicationStoreTest.kt @@ -62,7 +62,7 @@ internal class ApplicationStoreTest { private var componentStore: MyComponentStore by Delegates.notNull() @Before fun setUp() { - testAppConfig = tempDirManager.newPath(refreshVfs = false) + testAppConfig = tempDirManager.newPath() componentStore = MyComponentStore(testAppConfig.systemIndependentPath) } @@ -220,7 +220,7 @@ internal class ApplicationStoreTest { @Test fun `don't save if only format is changed`() { val oldContent = "" val file = writeConfig("a.xml", oldContent) - val oldModificationTime = file.getLastModifiedTime() + val oldModificationTime = file.lastModified() testAppConfig.refreshVfs() val component = A() @@ -230,7 +230,7 @@ internal class ApplicationStoreTest { saveStore() assertThat(file).hasContent(oldContent) - assertThat(oldModificationTime).isEqualTo(file.getLastModifiedTime()) + assertThat(oldModificationTime).isEqualTo(file.lastModified()) component.options.bar = "2" component.options.foo = "1" diff --git a/platform/configuration-store-impl/testSrc/DirectoryBasedStorageTest.kt b/platform/configuration-store-impl/testSrc/DirectoryBasedStorageTest.kt index 2f7a2a7d7121..213d9ea14fa0 100644 --- a/platform/configuration-store-impl/testSrc/DirectoryBasedStorageTest.kt +++ b/platform/configuration-store-impl/testSrc/DirectoryBasedStorageTest.kt @@ -65,8 +65,8 @@ internal class DirectoryBasedStorageTest { @Rule fun getChain() = ruleChain @Test fun save() { - val dir = tempDirManager.newPath() - val storage = DirectoryBasedStorage(dir.toFile(), TestStateSplitter()) + val dir = tempDirManager.newPath(refreshVfs = true) + val storage = DirectoryBasedStorage(dir, TestStateSplitter()) val componentName = "test" diff --git a/platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt b/platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt index 4d5253ab917d..936a58786331 100644 --- a/platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt +++ b/platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt @@ -47,7 +47,7 @@ internal class ModuleStoreRenameTest { object : ExternalResource() { override fun before() { runInEdtAndWait { - module = projectRule.createModule(tempDirManager.newPath().resolve("m.iml")) + module = projectRule.createModule(tempDirManager.newPath(refreshVfs = true).resolve("m.iml")) } module.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleAdapter() { diff --git a/platform/configuration-store-impl/testSrc/ModuleStoreTest.kt b/platform/configuration-store-impl/testSrc/ModuleStoreTest.kt index 4c5a21681117..260f0855a09b 100644 --- a/platform/configuration-store-impl/testSrc/ModuleStoreTest.kt +++ b/platform/configuration-store-impl/testSrc/ModuleStoreTest.kt @@ -76,7 +76,7 @@ class ModuleStoreTest { @Test fun `must be empty if classpath storage`() { // we must not use VFS here, file must not be created - val moduleFile = tempDirManager.newPath("module").resolve("test.iml") + val moduleFile = tempDirManager.newPath("module", refreshVfs = true).resolve("test.iml") moduleFile.createModule().useAndDispose { ModuleRootModificationUtil.addContentRoot(this, moduleFile.parentSystemIndependentPath) saveStore() @@ -92,7 +92,7 @@ class ModuleStoreTest { @Test fun `one batch update session if several modules changed`() { val nameToCount = TObjectIntHashMap() - val root = tempDirManager.newPath() + val root = tempDirManager.newPath(refreshVfs = true) fun Module.addContentRoot() { val moduleName = name diff --git a/platform/configuration-store-impl/testSrc/ProjectStoreTest.kt b/platform/configuration-store-impl/testSrc/ProjectStoreTest.kt index 0ebf377a0136..97a159d2d749 100644 --- a/platform/configuration-store-impl/testSrc/ProjectStoreTest.kt +++ b/platform/configuration-store-impl/testSrc/ProjectStoreTest.kt @@ -27,11 +27,11 @@ import com.intellij.openapi.project.ex.ProjectEx import com.intellij.openapi.project.ex.ProjectManagerEx import com.intellij.openapi.project.impl.ProjectImpl import com.intellij.openapi.project.impl.ProjectManagerImpl -import com.intellij.openapi.util.io.systemIndependentPath import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.* import com.intellij.util.PathUtil import com.intellij.util.readText +import com.intellij.util.systemIndependentPath import org.assertj.core.api.Assertions.assertThat import org.intellij.lang.annotations.Language import org.junit.ClassRule @@ -52,7 +52,7 @@ private fun createOrLoadProject(tempDirManager: TemporaryDirectory, task: (Proje runInEdtAndWait { var filePath: String if (projectCreator == null) { - filePath = tempDirManager.newDirectory("test${if (directoryBased) "" else ProjectFileType.DOT_DEFAULT_EXTENSION}").systemIndependentPath + filePath = tempDirManager.newPath("test${if (directoryBased) "" else ProjectFileType.DOT_DEFAULT_EXTENSION}").systemIndependentPath } else { filePath = runWriteAction { projectCreator(tempDirManager.newVirtualDirectory()) } diff --git a/platform/configuration-store-impl/testSrc/SchemeManagerTest.kt b/platform/configuration-store-impl/testSrc/SchemeManagerTest.kt index 7532fa4bf183..e96c81ac3a66 100644 --- a/platform/configuration-store-impl/testSrc/SchemeManagerTest.kt +++ b/platform/configuration-store-impl/testSrc/SchemeManagerTest.kt @@ -18,13 +18,12 @@ package com.intellij.configurationStore import com.intellij.openapi.options.BaseSchemeProcessor import com.intellij.openapi.options.ExternalizableScheme import com.intellij.openapi.options.SchemesManagerFactory -import com.intellij.openapi.util.JDOMUtil import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.testFramework.PlatformTestUtil import com.intellij.testFramework.ProjectRule import com.intellij.testFramework.TemporaryDirectory -import com.intellij.util.SmartList +import com.intellij.util.* import com.intellij.util.lang.CompoundRuntimeException import com.intellij.util.xmlb.XmlSerializer import com.intellij.util.xmlb.annotations.Attribute @@ -40,6 +39,7 @@ import org.junit.ClassRule import org.junit.Rule import org.junit.Test import java.io.File +import java.nio.file.Path internal val FILE_SPEC = "REMOTE" @@ -55,8 +55,8 @@ internal class SchemeManagerTest { private val tempDirManager = TemporaryDirectory() @Rule fun getTemporaryFolder() = tempDirManager - private var localBaseDir: File? = null - private var remoteBaseDir: File? = null + private var localBaseDir: Path? = null + private var remoteBaseDir: Path? = null private fun getTestDataPath() = PlatformTestUtil.getCommunityPath().replace(File.separatorChar, '/') + "/platform/platform-tests/testData/options" @@ -112,14 +112,14 @@ internal class SchemeManagerTest { firstScheme!!.name = "first_renamed" manager.save() - checkSchemes(File(remoteBaseDir, "REMOTE"), "first_renamed->first_renamed;2->second", true) + checkSchemes(remoteBaseDir!!.resolve("REMOTE"), "first_renamed->first_renamed;2->second", true) checkSchemes(localBaseDir!!, "", false) firstScheme.name = "first_renamed2" manager.removeScheme(firstScheme) manager.save() - checkSchemes(File(remoteBaseDir, "REMOTE"), "2->second", true) + checkSchemes(remoteBaseDir!!.resolve("REMOTE"), "2->second", true) checkSchemes(localBaseDir!!, "", false) } @@ -142,16 +142,16 @@ internal class SchemeManagerTest { assertThat("first2").isEqualTo(scheme.name) } - fun TestScheme.save(file: File) { - FileUtil.writeToFile(file, serialize().toByteArray()) + fun TestScheme.save(file: Path) { + file.write(serialize().toByteArray()) } @Test fun `different extensions`() { - val dir = tempDirManager.newDirectory() + val dir = tempDirManager.newPath() val scheme = TestScheme("local", "true") - scheme.save(File(dir, "1.icls")) - TestScheme("local", "false").save(File(dir, "1.xml")) + scheme.save(dir.resolve("1.icls")) + TestScheme("local", "false").save(dir.resolve("1.xml")) val schemesManager = SchemeManagerImpl(FILE_SPEC, object: TestSchemesProcessor() { override fun isUpgradeNeeded() = true @@ -161,18 +161,18 @@ internal class SchemeManagerTest { schemesManager.loadSchemes() assertThat(schemesManager.allSchemes).containsOnly(scheme) - assertThat(File(dir, "1.icls")).isFile() - assertThat(File(dir, "1.xml")).isFile() + assertThat(dir.resolve("1.icls")).isRegularFile() + assertThat(dir.resolve("1.xml")).isRegularFile() scheme.data = "newTrue" schemesManager.save() - assertThat(File(dir, "1.icls")).isFile() - assertThat(File(dir, "1.xml")).doesNotExist() + assertThat(dir.resolve("1.icls")).isRegularFile() + assertThat(dir.resolve("1.xml")).doesNotExist() } @Test fun setSchemes() { - val dir = tempDirManager.newDirectory() + val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() @@ -183,12 +183,12 @@ internal class SchemeManagerTest { val schemes = schemeManager.allSchemes assertThat(schemes).containsOnly(scheme) - assertThat(File(dir, "s1.xml")).doesNotExist() + assertThat(dir.resolve("s1.xml")).doesNotExist() scheme.data = "newTrue" schemeManager.save() - assertThat(File(dir, "s1.xml")).isFile() + assertThat(dir.resolve("s1.xml")).isRegularFile() schemeManager.setSchemes(emptyList()) @@ -198,7 +198,7 @@ internal class SchemeManagerTest { } @Test fun `save only if scheme differs from bundled`() { - val dir = tempDirManager.newDirectory() + val dir = tempDirManager.newPath() var schemeManager = createSchemeManager(dir) val converter: (Element) -> TestScheme = { XmlSerializer.deserialize(it, TestScheme::class.java)!! } val bundledPath = "/bundledSchemes/default" @@ -219,7 +219,7 @@ internal class SchemeManagerTest { customScheme.data = "foo" schemeManager.save() - assertThat(File(dir, "default.xml")).isFile() + assertThat(dir.resolve("default.xml")).isRegularFile() schemeManager = createSchemeManager(dir) schemeManager.loadBundledScheme(bundledPath, this, converter) @@ -230,7 +230,7 @@ internal class SchemeManagerTest { } @Test fun `don't remove dir if no schemes but at least one non-hidden file exists`() { - val dir = tempDirManager.newDirectory() + val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) val scheme = TestScheme("s1") @@ -238,12 +238,12 @@ internal class SchemeManagerTest { schemeManager.save() - val schemeFile = File(dir, "s1.xml") - assertThat(schemeFile).isFile() + val schemeFile = dir.resolve("s1.xml") + assertThat(schemeFile).isRegularFile() schemeManager.setSchemes(emptyList()) - FileUtil.writeToFile(File(dir, "empty"), byteArrayOf()) + dir.resolve("empty").write(byteArrayOf()) schemeManager.save() @@ -252,11 +252,11 @@ internal class SchemeManagerTest { } @Test fun `remove empty directory only if some file was deleted`() { - val dir = tempDirManager.newDirectory() + val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() - assertThat(dir.mkdirs()).isTrue() + dir.createDirectories() schemeManager.save() assertThat(dir).isDirectory() @@ -270,7 +270,7 @@ internal class SchemeManagerTest { } @Test fun rename() { - val dir = tempDirManager.newDirectory() + val dir = tempDirManager.newPath() val schemeManager = createSchemeManager(dir) schemeManager.loadSchemes() assertThat(schemeManager.allSchemes).isEmpty() @@ -281,19 +281,19 @@ internal class SchemeManagerTest { val schemes = schemeManager.allSchemes assertThat(schemes).containsOnly(scheme) - assertThat(File(dir, "s1.xml")).doesNotExist() + assertThat(dir.resolve("s1.xml")).doesNotExist() scheme.data = "newTrue" schemeManager.save() - assertThat(File(dir, "s1.xml")).isFile() + assertThat(dir.resolve("s1.xml")).isRegularFile() scheme.name = "s2" schemeManager.save() - assertThat(File(dir, "s1.xml")).doesNotExist() - assertThat(File(dir, "s2.xml")).isFile() + assertThat(dir.resolve("s1.xml")).doesNotExist() + assertThat(dir.resolve("s2.xml")).isRegularFile() } @Test fun `path must not contains ROOT_CONFIG macro`() { @@ -304,7 +304,7 @@ internal class SchemeManagerTest { assertThatThrownBy({SchemesManagerFactory.getInstance().create("foo\\bar", TestSchemesProcessor())}).hasMessage("Path must be system-independent, use forward slash instead of backslash") } - private fun createSchemeManager(dir: File) = SchemeManagerImpl(FILE_SPEC, TestSchemesProcessor(), null, dir) + private fun createSchemeManager(dir: Path) = SchemeManagerImpl(FILE_SPEC, TestSchemesProcessor(), null, dir) private fun createAndLoad(testData: String): SchemeManagerImpl { createTempFiles(testData) @@ -314,30 +314,30 @@ internal class SchemeManagerTest { private fun doLoadSaveTest(testData: String, expected: String, localExpected: String = "") { val schemesManager = createAndLoad(testData) schemesManager.save() - checkSchemes(File(remoteBaseDir, "REMOTE"), expected, true) + checkSchemes(remoteBaseDir!!.resolve("REMOTE"), expected, true) checkSchemes(localBaseDir!!, localExpected, false) } private fun checkSchemes(expected: String) { - checkSchemes(File(remoteBaseDir, "REMOTE"), expected, true) + checkSchemes(remoteBaseDir!!.resolve("REMOTE"), expected, true) checkSchemes(localBaseDir!!, "", false) } private fun createAndLoad(): SchemeManagerImpl { - val schemesManager = SchemeManagerImpl(FILE_SPEC, TestSchemesProcessor(), MockStreamProvider(remoteBaseDir!!), localBaseDir!!) + val schemesManager = SchemeManagerImpl(FILE_SPEC, TestSchemesProcessor(), MockStreamProvider(remoteBaseDir!!.toFile()), localBaseDir!!) schemesManager.loadSchemes() return schemesManager } private fun createTempFiles(testData: String) { - val temp = tempDirManager.newDirectory() - localBaseDir = File(temp, "__local") + val temp = tempDirManager.newPath() + localBaseDir = temp.resolve("__local") remoteBaseDir = temp - FileUtil.copyDir(File("${getTestDataPath()}/$testData"), File(temp, "REMOTE")) + FileUtil.copyDir(File("${getTestDataPath()}/$testData"), temp.resolve("REMOTE").toFile()) } } -private fun checkSchemes(baseDir: File, expected: String, ignoreDeleted: Boolean) { +private fun checkSchemes(baseDir: Path, expected: String, ignoreDeleted: Boolean) { val filesToScheme = StringUtil.split(expected, ";") val fileToSchemeMap = THashMap() for (fileToScheme in filesToScheme) { @@ -345,10 +345,9 @@ private fun checkSchemes(baseDir: File, expected: String, ignoreDeleted: Boolean fileToSchemeMap.put(fileToScheme.substring(0, index), fileToScheme.substring(index + 2)) } - val files = baseDir.listFiles() - if (files != null) { - for (file in files) { - val fileName = FileUtil.getNameWithoutExtension(file) + baseDir.directoryStreamIfExists { + for (file in it) { + val fileName = FileUtil.getNameWithoutExtension(file.fileName.toString()) if ("--deleted" == fileName && ignoreDeleted) { assertThat(fileToSchemeMap).containsKey(fileName) } @@ -356,14 +355,14 @@ private fun checkSchemes(baseDir: File, expected: String, ignoreDeleted: Boolean } for (file in fileToSchemeMap.keys) { - assertThat(File(baseDir, "$file.xml")).isFile() + assertThat(baseDir.resolve("$file.xml")).isRegularFile() } - if (files != null) { + baseDir.directoryStreamIfExists { val schemesProcessor = TestSchemesProcessor() - for (file in files) { - val scheme = schemesProcessor.readScheme(JDOMUtil.load(file), true)!! - assertThat(fileToSchemeMap.get(FileUtil.getNameWithoutExtension(file))).isEqualTo(scheme.name) + for (file in it) { + val scheme = schemesProcessor.readScheme(loadElement(file), true)!! + assertThat(fileToSchemeMap.get(FileUtil.getNameWithoutExtension(file.fileName.toString()))).isEqualTo(scheme.name) } } } diff --git a/platform/core-impl/src/com/intellij/ide/plugins/PluginManagerCore.java b/platform/core-impl/src/com/intellij/ide/plugins/PluginManagerCore.java index d349ce55bfab..7cae6abfb550 100644 --- a/platform/core-impl/src/com/intellij/ide/plugins/PluginManagerCore.java +++ b/platform/core-impl/src/com/intellij/ide/plugins/PluginManagerCore.java @@ -903,7 +903,7 @@ public class PluginManagerCore { int i = 0; for (URL url : urls) { IdeaPluginDescriptorImpl descriptor = loadDescriptorFromResource(url); - if (descriptor != null) { + if (descriptor != null && !result.contains(descriptor)) { descriptor.setUseCoreClassLoader(true); result.add(descriptor); if (progress != null && !SPECIAL_IDEA_PLUGIN.equals(descriptor.getName())) { diff --git a/platform/core-impl/src/com/intellij/psi/impl/DocumentCommitThread.java b/platform/core-impl/src/com/intellij/psi/impl/DocumentCommitThread.java index f1a55b1e5cd2..b7eaab6a8dac 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/DocumentCommitThread.java +++ b/platform/core-impl/src/com/intellij/psi/impl/DocumentCommitThread.java @@ -217,7 +217,7 @@ public class DocumentCommitThread extends DocumentCommitProcessor implements Run @Override public void log(Project project, @NonNls String msg, @Nullable CommitTask task, @NonNls Object... args) { - //if (true) return; + if (true) return; String indent = new SimpleDateFormat("hh:mm:ss:SSSS").format(new Date()) + (SwingUtilities.isEventDispatchThread() ? "-(EDT) " : diff --git a/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java b/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java index f048f4e6964e..8fb3d7827771 100644 --- a/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java +++ b/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java @@ -22,6 +22,7 @@ import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.diagnostic.Logger; @@ -505,6 +506,16 @@ public abstract class PsiDocumentManagerBase extends PsiDocumentManager implemen } actions.add(action); myDocumentCommitProcessor.log(myProject, "PDI: added performWhenAllCommitted", null, action); + + ModalityState current = ModalityState.current(); + if (current != ModalityState.NON_MODAL) { + // re-add all uncommitted documents into the queue with this new modality + // because this client obviously expects them to commit even inside modal dialog + for (Document document : myUncommittedDocuments) { + myDocumentCommitProcessor.commitAsynchronously(myProject, document, + "re-added with modality "+current+" because performWhenAllCommitted("+current+") was called", current); + } + } return false; } diff --git a/platform/diff-api/src/com/intellij/diff/chains/DiffRequestProducerException.java b/platform/diff-api/src/com/intellij/diff/chains/DiffRequestProducerException.java index 2b1657a4cf52..81991cfe7ddf 100644 --- a/platform/diff-api/src/com/intellij/diff/chains/DiffRequestProducerException.java +++ b/platform/diff-api/src/com/intellij/diff/chains/DiffRequestProducerException.java @@ -17,7 +17,7 @@ package com.intellij.diff.chains; public class DiffRequestProducerException extends Exception { public DiffRequestProducerException(Throwable cause) { - super(cause); + super(cause.getMessage(), cause); } public DiffRequestProducerException(String message, Throwable cause) { diff --git a/platform/diff-impl/src/com/intellij/diff/requests/UnknownFileTypeDiffRequest.java b/platform/diff-impl/src/com/intellij/diff/requests/UnknownFileTypeDiffRequest.java index 03a21984ff2d..d3ee5f5c1614 100644 --- a/platform/diff-impl/src/com/intellij/diff/requests/UnknownFileTypeDiffRequest.java +++ b/platform/diff-impl/src/com/intellij/diff/requests/UnknownFileTypeDiffRequest.java @@ -17,7 +17,6 @@ package com.intellij.diff.requests; import com.intellij.diff.DiffContext; import com.intellij.diff.DiffContextEx; -import com.intellij.diff.util.DiffUtil; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.UnknownFileType; @@ -28,11 +27,14 @@ import com.intellij.openapi.vcs.changes.issueLinks.LinkMouseListenerBase; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.SimpleColoredComponent; import com.intellij.ui.SimpleTextAttributes; +import com.intellij.util.ui.GridBag; +import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; +import java.awt.*; public class UnknownFileTypeDiffRequest extends ComponentDiffRequest { @Nullable private final String myFileName; @@ -52,6 +54,7 @@ public class UnknownFileTypeDiffRequest extends ComponentDiffRequest { @Override public JComponent getComponent(@NotNull final DiffContext context) { final SimpleColoredComponent label = new SimpleColoredComponent(); + label.setTextAlign(SwingConstants.CENTER); label.append("Can't show diff for unknown file type. ", new SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, UIUtil.getInactiveTextColor())); if (myFileName != null) { @@ -69,7 +72,7 @@ public class UnknownFileTypeDiffRequest extends ComponentDiffRequest { }); LinkMouseListenerBase.installSingleTagOn(label); } - return DiffUtil.createMessagePanel(label); + return JBUI.Panels.simplePanel(label).withBorder(JBUI.Borders.empty(5)); } @Nullable diff --git a/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java b/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java index fb87929c8f9d..d05bf977b1b0 100644 --- a/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java +++ b/platform/diff-impl/src/com/intellij/diff/util/DiffUtil.java @@ -84,7 +84,7 @@ import com.intellij.util.DocumentUtil; import com.intellij.util.Function; import com.intellij.util.LineSeparator; import com.intellij.util.containers.ContainerUtil; -import com.intellij.util.ui.GridBag; +import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.UIUtil; import org.jetbrains.annotations.*; @@ -284,24 +284,21 @@ public class DiffUtil { @NotNull public static JPanel createMessagePanel(@NotNull String message) { - Pair pair = createMessagePanel(); - pair.getSecond().setText(message); - return pair.getFirst(); - } - - @NotNull - public static Pair createMessagePanel() { - JLabel label = new JLabel(); + String text = StringUtil.replace(message, "\n", "
"); + JLabel label = new JBLabel(text) { + @Override + public Dimension getMinimumSize() { + Dimension size = super.getMinimumSize(); + size.width = Math.min(size.width, 200); + size.height = Math.min(size.height, 100); + return size; + } + }.setCopyable(true); label.setForeground(UIUtil.getInactiveTextColor()); - JPanel wrapper = createMessagePanel(label); - return Pair.create(wrapper, label); - } - @NotNull - public static JPanel createMessagePanel(@NotNull JComponent comp) { - JPanel wrapper = new JPanel(new GridBagLayout()); - wrapper.add(comp, new GridBag().insets(JBUI.insets(1))); - return wrapper; + JPanel panel = new CenteredPanel(label); + panel.setBorder(JBUI.Borders.empty(5)); + return panel; } public static void addActionBlock(@NotNull DefaultActionGroup group, AnAction... actions) { @@ -1289,4 +1286,49 @@ public class DiffUtil { return height; } } + + private static class CenteredPanel extends JPanel { + private final JComponent myComponent; + + public CenteredPanel(@NotNull JComponent component) { + myComponent = component; + add(component); + } + + @Override + public void doLayout() { + final Dimension size = getSize(); + final Dimension preferredSize = myComponent.getPreferredSize(); + + Insets insets = getInsets(); + JBInsets.removeFrom(size, insets); + + int width = Math.min(size.width, preferredSize.width); + int height = Math.min(size.height, preferredSize.height); + int x = Math.max(0, (size.width - preferredSize.width) / 2); + int y = Math.max(0, (size.height - preferredSize.height) / 2); + + myComponent.setBounds(insets.left + x, insets.top + y, width, height); + } + + @Override + public Dimension getPreferredSize() { + return addInsets(myComponent.getPreferredSize()); + } + + @Override + public Dimension getMinimumSize() { + return addInsets(myComponent.getMinimumSize()); + } + + @Override + public Dimension getMaximumSize() { + return addInsets(myComponent.getMaximumSize()); + } + + private Dimension addInsets(Dimension dimension) { + JBInsets.addTo(dimension, getInsets()); + return dimension; + } + } } diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/execution/ExternalSystemExecutionConsoleManager.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/execution/ExternalSystemExecutionConsoleManager.java index 8e5d6f99cefa..67e6671b170e 100644 --- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/execution/ExternalSystemExecutionConsoleManager.java +++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/execution/ExternalSystemExecutionConsoleManager.java @@ -58,5 +58,5 @@ public interface ExternalSystemExecutionConsoleManager< boolean isApplicableFor(@NotNull ExternalSystemTask task); - AnAction[] getRestartActions(); + AnAction[] getRestartActions(@NotNull ExternalSystemExecutionConsole consoleView); } diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java index 4179681ab59b..c2c06d218043 100644 --- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java +++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java @@ -3,7 +3,6 @@ package com.intellij.openapi.externalSystem.model.project; import com.intellij.ide.highlighter.ModuleFileType; import com.intellij.openapi.externalSystem.model.ProjectSystemId; import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil; -import com.intellij.openapi.util.io.FileUtil; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -58,7 +57,7 @@ public class ModuleData extends AbstractNamedData implements Named, ExternalConf @NotNull String internalName, @NotNull String moduleFileDirectoryPath, @NotNull String externalConfigPath) { - super(owner, externalName, FileUtil.sanitizeFileName(internalName)); + super(owner, externalName, internalName); myId = id; myModuleTypeId = typeId; myExternalConfigPath = externalConfigPath; diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/DefaultExternalSystemExecutionConsoleManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/DefaultExternalSystemExecutionConsoleManager.java index 6a5f673d9dd5..025d77312a59 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/DefaultExternalSystemExecutionConsoleManager.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/DefaultExternalSystemExecutionConsoleManager.java @@ -70,7 +70,7 @@ public class DefaultExternalSystemExecutionConsoleManager } @Override - public AnAction[] getRestartActions() { + public AnAction[] getRestartActions(@NotNull ExecutionConsole consoleView) { return new AnAction[0]; } } diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemRunConfiguration.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemRunConfiguration.java index 2b316c68f42f..60005ba6924c 100644 --- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemRunConfiguration.java +++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemRunConfiguration.java @@ -68,7 +68,7 @@ public class ExternalSystemRunConfiguration extends LocatableConfigurationBase { } @Override - public RunConfiguration clone() { + public ExternalSystemRunConfiguration clone() { ExternalSystemRunConfiguration result = (ExternalSystemRunConfiguration)super.clone(); result.mySettings = mySettings.clone(); return result; @@ -234,7 +234,7 @@ public class ExternalSystemRunConfiguration extends LocatableConfigurationBase { } }); DefaultExecutionResult result = new DefaultExecutionResult(consoleView, processHandler); - result.setRestartActions(consoleManager.getRestartActions()); + result.setRestartActions(consoleManager.getRestartActions(consoleView)); return result; } } diff --git a/platform/icons/src/gutter/implementingFunctional.png b/platform/icons/src/gutter/implementingFunctionalInterface.png similarity index 100% rename from platform/icons/src/gutter/implementingFunctional.png rename to platform/icons/src/gutter/implementingFunctionalInterface.png diff --git a/platform/icons/src/gutter/ImplementingFunctional@2x.png b/platform/icons/src/gutter/implementingFunctionalInterface@2x.png similarity index 100% rename from platform/icons/src/gutter/ImplementingFunctional@2x.png rename to platform/icons/src/gutter/implementingFunctionalInterface@2x.png diff --git a/platform/lang-api/src/com/intellij/ide/util/projectWizard/WizardContext.java b/platform/lang-api/src/com/intellij/ide/util/projectWizard/WizardContext.java index 77d399d520c1..9a8db534b9d5 100644 --- a/platform/lang-api/src/com/intellij/ide/util/projectWizard/WizardContext.java +++ b/platform/lang-api/src/com/intellij/ide/util/projectWizard/WizardContext.java @@ -16,7 +16,7 @@ package com.intellij.ide.util.projectWizard; import com.intellij.ide.IdeBundle; -import com.intellij.ide.RecentProjectsManager; +import com.intellij.ide.wizard.AbstractWizard; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.components.StorageScheme; @@ -53,6 +53,7 @@ public class WizardContext extends UserDataHolderBase { private boolean myNewWizard; private ModulesProvider myModulesProvider; private boolean myProjectFileDirectorySetExplicitly; + private AbstractWizard myWizard; public void setProjectStorageFormat(StorageScheme format) { myProjectStorageFormat = format; @@ -78,6 +79,14 @@ public class WizardContext extends UserDataHolderBase { return myDisposable; } + public AbstractWizard getWizard() { + return myWizard; + } + + public void setWizard(AbstractWizard wizard) { + myWizard = wizard; + } + public interface Listener { void buttonsUpdateRequested(); void nextStepRequested(); @@ -109,10 +118,10 @@ public class WizardContext extends UserDataHolderBase { if (myProjectFileDirectory != null) { return myProjectFileDirectory; } - final String lastProjectLocation = RecentProjectsManager.getInstance().getLastProjectCreationLocation(); - if (lastProjectLocation != null) { - return lastProjectLocation.replace('/', File.separatorChar); - } + //final String lastProjectLocation = RecentProjectsManager.getInstance().getLastProjectCreationLocation(); + //if (lastProjectLocation != null) { + // return lastProjectLocation.replace('/', File.separatorChar); + //} final String userHome = SystemProperties.getUserHome(); //noinspection HardCodedStringLiteral String productName = ApplicationNamesInfo.getInstance().getLowercaseProductName(); diff --git a/platform/lang-api/src/com/intellij/lang/parameterInfo/UpdateParameterInfoContext.java b/platform/lang-api/src/com/intellij/lang/parameterInfo/UpdateParameterInfoContext.java index 1b74dd0e390b..f4a13ad75d9f 100644 --- a/platform/lang-api/src/com/intellij/lang/parameterInfo/UpdateParameterInfoContext.java +++ b/platform/lang-api/src/com/intellij/lang/parameterInfo/UpdateParameterInfoContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -27,7 +27,7 @@ public interface UpdateParameterInfoContext extends ParameterInfoContext { void setHighlightedParameter(final Object parameter); void setCurrentParameter(final int index); boolean isUIComponentEnabled(int index); - void setUIComponentEnabled(int index, boolean b); + void setUIComponentEnabled(int index, boolean enabled); int getParameterListStart(); diff --git a/platform/lang-api/src/com/intellij/util/download/FileDownloader.java b/platform/lang-api/src/com/intellij/util/download/FileDownloader.java index 6ca69ffce0c6..f61ef9abd13a 100644 --- a/platform/lang-api/src/com/intellij/util/download/FileDownloader.java +++ b/platform/lang-api/src/com/intellij/util/download/FileDownloader.java @@ -37,7 +37,7 @@ public interface FileDownloader { * @param targetDirectoryPath target directory for downloaded files. If {@code null} a file chooser will be shown to select target directory * @param project project instance used to show the progress window * @param parentComponent parent component for the progress window - * @return list of downloaded files of {@code null} if the downloading process was failed or cancelled + * @return list of downloaded files or {@code null} if the downloading process was failed or cancelled */ @Nullable List downloadFilesWithProgress(@Nullable String targetDirectoryPath, @Nullable Project project, @Nullable JComponent parentComponent); diff --git a/platform/lang-impl/src/com/intellij/application/options/editor/GutterIconsConfigurable.java b/platform/lang-impl/src/com/intellij/application/options/editor/GutterIconsConfigurable.java index c9309c443859..7175455c3a82 100644 --- a/platform/lang-impl/src/com/intellij/application/options/editor/GutterIconsConfigurable.java +++ b/platform/lang-impl/src/com/intellij/application/options/editor/GutterIconsConfigurable.java @@ -60,7 +60,7 @@ public class GutterIconsConfigurable implements Configurable, Configurable.NoScr @Nullable @Override public String getHelpTopic() { - return null; + return "reference.settings.editor.gutter.icons"; } @Nullable diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/fillParagraph/FillParagraphAction.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/fillParagraph/FillParagraphAction.java index 3e4449f714a8..787779121180 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/fillParagraph/FillParagraphAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/fillParagraph/FillParagraphAction.java @@ -3,6 +3,7 @@ package com.intellij.codeInsight.editorActions.fillParagraph; import com.intellij.codeInsight.CodeInsightActionHandler; import com.intellij.codeInsight.actions.BaseCodeInsightAction; import com.intellij.openapi.editor.Editor; +import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; @@ -16,7 +17,7 @@ import org.jetbrains.annotations.NotNull; * * The action came from Emacs users // PY-4775 */ -public class FillParagraphAction extends BaseCodeInsightAction { +public class FillParagraphAction extends BaseCodeInsightAction implements DumbAware { @NotNull @Override diff --git a/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java b/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java index 196f723850c1..bce965b73fda 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/hint/ParameterInfoController.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -413,8 +413,8 @@ public class ParameterInfoController implements Disposable { } @Override - public void setUIComponentEnabled(int index, boolean b) { - myComponent.setEnabled(index, b); + public void setUIComponentEnabled(int index, boolean enabled) { + myComponent.setEnabled(index, enabled); } @Override diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java index 71fea342b459..52fdb9d21ef4 100644 --- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java +++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/actions/GotoDeclarationAction.java @@ -33,11 +33,12 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.LogicalPosition; -import com.intellij.openapi.editor.ScrollType; import com.intellij.openapi.editor.ex.EditorGutterComponentEx; import com.intellij.openapi.editor.ex.util.EditorUtil; import com.intellij.openapi.extensions.ExtensionException; import com.intellij.openapi.extensions.Extensions; +import com.intellij.openapi.fileEditor.OpenFileDescriptor; +import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.IndexNotReadyException; @@ -136,8 +137,9 @@ public class GotoDeclarationAction extends BaseCodeInsightAction implements Code private static void gotoTargetElement(@NotNull PsiElement element, @NotNull Editor currentEditor, @NotNull PsiFile currentFile) { if (element.getContainingFile() == currentFile) { - currentEditor.getCaretModel().moveToOffset(element.getTextOffset()); - currentEditor.getScrollingModel().scrollToCaret(ScrollType.CENTER); + Project project = element.getProject(); + IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation(); + new OpenFileDescriptor(project, currentFile.getViewProvider().getVirtualFile(), element.getTextOffset()).navigateIn(currentEditor); return; } diff --git a/platform/lang-impl/src/com/intellij/execution/TestStateStorage.java b/platform/lang-impl/src/com/intellij/execution/TestStateStorage.java index 4875cf49117a..5826d53ac6f4 100644 --- a/platform/lang-impl/src/com/intellij/execution/TestStateStorage.java +++ b/platform/lang-impl/src/com/intellij/execution/TestStateStorage.java @@ -131,6 +131,17 @@ public class TestStateStorage implements Disposable { } } + public synchronized void removeState(String url) { + if (myMap != null) { + try { + myMap.remove(url); + } + catch (IOException e) { + thingsWentWrongLetsReinitialize(e, "Can't remove state for " + url); + } + } + } + @Nullable public synchronized Map getRecentTests(int limit, Date since) { if (myMap == null) return null; diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/ui/AbstractNavBarUI.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/ui/AbstractNavBarUI.java index 48ca9172ae75..b3f4d4c33b35 100644 --- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/ui/AbstractNavBarUI.java +++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/ui/AbstractNavBarUI.java @@ -17,7 +17,6 @@ package com.intellij.ide.navigationToolbar.ui; import com.intellij.ide.navigationToolbar.NavBarItem; import com.intellij.ide.navigationToolbar.NavBarPanel; -import com.intellij.ide.navigationToolbar.NavBarRootPaneExtension; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.util.SystemInfo; import com.intellij.ui.ColorUtil; @@ -290,15 +289,15 @@ public abstract class AbstractNavBarUI implements NavBarUI { @Override public Insets getWrapperPanelInsets(Insets insets) { - //final JBInsets result = JBUI.insets(insets); - //if (shouldPaintWrapperPanel()) { - // result.top += JBUI.scale(1); - //} - return insets; + final JBInsets result = JBUI.insets(insets); + if (shouldPaintWrapperPanel()) { + result.top += JBUI.scale(1); + } + return result; } private static boolean shouldPaintWrapperPanel() { - return !UISettings.getInstance().SHOW_MAIN_TOOLBAR && NavBarRootPaneExtension.runToolbarExists(); + return false; //return !UISettings.getInstance().SHOW_MAIN_TOOLBAR && NavBarRootPaneExtension.runToolbarExists(); } protected Color getBackgroundColor() { diff --git a/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerAction.java b/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerAction.java index ea3826dfb88c..f45653b3d2a0 100644 --- a/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerAction.java +++ b/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2010 JetBrains s.r.o. + * Copyright 2000-2016 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,9 +17,6 @@ package com.intellij.internal.psiView; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; -import com.intellij.openapi.actionSystem.CommonDataKeys; -import com.intellij.openapi.actionSystem.PlatformDataKeys; -import com.intellij.openapi.actionSystem.Presentation; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; @@ -33,36 +30,28 @@ import com.intellij.openapi.project.Project; public class PsiViewerAction extends AnAction implements DumbAware { @Override public void actionPerformed(AnActionEvent e) { - final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext()); - new PsiViewerDialog(project, false, null, null).show(); + new PsiViewerDialog(e.getProject(), false, null, null).show(); } @Override public void update(AnActionEvent e) { - final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext()); - final Presentation p = e.getPresentation(); - if (project == null) { - p.setVisible(false); - p.setEnabled(false); - return; - } + boolean enabled = false; - if (ApplicationManagerEx.getApplicationEx().isInternal()) { - p.setVisible(true); - p.setEnabled(true); - return; - } - - final Module[] modules = ModuleManager.getInstance(project).getModules(); - for (Module module : modules) { - if ("PLUGIN_MODULE".equals(ModuleType.get(module).getId())) { - p.setVisible(true); - p.setEnabled(true); - return; + Project project = e.getProject(); + if (project != null) { + if (ApplicationManagerEx.getApplicationEx().isInternal()) { + enabled = true; + } + else { + for (Module module : ModuleManager.getInstance(project).getModules()) { + if ("PLUGIN_MODULE".equals(ModuleType.get(module).getId())) { + enabled = true; + break; + } + } } } - - p.setVisible(false); - p.setEnabled(false); + + e.getPresentation().setEnabledAndVisible(enabled); } -} +} \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerForContextAction.java b/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerForContextAction.java index ad47939e1414..a3e28fc77714 100644 --- a/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerForContextAction.java +++ b/platform/lang-impl/src/com/intellij/internal/psiView/PsiViewerForContextAction.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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,36 +18,24 @@ package com.intellij.internal.psiView; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.CommonDataKeys; +import com.intellij.openapi.actionSystem.DataContext; import com.intellij.openapi.application.ex.ApplicationManagerEx; -import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.DumbAware; -import com.intellij.openapi.project.Project; -import com.intellij.psi.PsiFile; /** - * Created by IntelliJ IDEA. - * User: Nadya.Zabrodina - * Date: 7/4/11 - * Time: 4:16 PM + * @author Nadya.Zabrodina */ public class PsiViewerForContextAction extends AnAction implements DumbAware { @Override public void actionPerformed(AnActionEvent e) { - - Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext()); - PsiFile currentFile = CommonDataKeys.PSI_FILE.getData(e.getDataContext()); - new PsiViewerDialog(currentFile.getProject(), false, currentFile, editor).show(); + DataContext ctx = e.getDataContext(); + new PsiViewerDialog(e.getProject(), false, CommonDataKeys.PSI_FILE.getData(ctx), CommonDataKeys.EDITOR.getData(ctx)).show(); } @Override public void update(AnActionEvent e) { - if (!ApplicationManagerEx.getApplicationEx().isInternal()) { - e.getPresentation().setVisible(false); - e.getPresentation().setEnabled(false); - return; - } - final Project project = CommonDataKeys.PROJECT.getData(e.getDataContext()); - PsiFile currentFile = CommonDataKeys.PSI_FILE.getData(e.getDataContext()); - e.getPresentation().setEnabled(project != null && currentFile != null); + boolean enabled = ApplicationManagerEx.getApplicationEx().isInternal() && e.getProject() != null; + e.getPresentation().setEnabled(enabled); + e.getPresentation().setVisible(enabled && CommonDataKeys.PSI_FILE.getData(e.getDataContext()) != null); } -} +} \ No newline at end of file diff --git a/platform/lang-impl/src/com/intellij/packageDependencies/DependencyUISettings.java b/platform/lang-impl/src/com/intellij/packageDependencies/DependencyUISettings.java index 0e0e234bc983..1d6a716e8d2f 100644 --- a/platform/lang-impl/src/com/intellij/packageDependencies/DependencyUISettings.java +++ b/platform/lang-impl/src/com/intellij/packageDependencies/DependencyUISettings.java @@ -25,7 +25,10 @@ import com.intellij.util.xmlb.XmlSerializerUtil; @State( name = "DependencyUISettings", - storages = @Storage("other.xml") + storages = { + @Storage("ui.lnf.xml"), + @Storage(value = "other.xml", deprecated = true) + } ) public class DependencyUISettings implements PersistentStateComponent { public boolean UI_FLATTEN_PACKAGES = true; diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceCompletionImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceCompletionImpl.java index ea4274f677e1..c0f7361bd9aa 100644 --- a/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceCompletionImpl.java +++ b/platform/lang-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReferenceCompletionImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2013 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -26,6 +26,7 @@ import com.intellij.psi.util.PsiUtilCore; import com.intellij.util.ArrayUtil; import com.intellij.util.CommonProcessors; import com.intellij.util.FilteringProcessor; +import com.intellij.util.containers.ContainerUtil; import gnu.trove.THashSet; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; @@ -76,17 +77,23 @@ public class FileReferenceCompletionImpl extends FileReferenceCompletion { FileReference.getOriginalFile(fileSystemItem)); } }; + + List additionalItems = ContainerUtil.newArrayList(); for (PsiFileSystemItem context : reference.getContexts()) { for (final PsiElement child : context.getChildren()) { if (child instanceof PsiFileSystemItem) { processor.execute((PsiFileSystemItem)child); } } + if (context instanceof FileReferenceResolver) { + additionalItems.addAll(((FileReferenceResolver)context).getVariants(reference)); + } } + final THashSet set = new THashSet(collector.getResults(), VARIANTS_HASHING_STRATEGY); final PsiElement[] candidates = PsiUtilCore.toPsiElementArray(set); - final Object[] variants = new Object[candidates.length]; + final Object[] variants = new Object[candidates.length + additionalItems.size()]; for (int i = 0; i < candidates.length; i++) { PsiElement candidate = candidates[i]; Object item = reference.createLookupItem(candidate); @@ -95,10 +102,14 @@ public class FileReferenceCompletionImpl extends FileReferenceCompletion { } variants[i] = item; } + + for (int i = 0; i < additionalItems.size(); i++) { + variants[i + candidates.length] = additionalItems.get(i); + } if (!reference.getFileReferenceSet().isUrlEncoded()) { return variants; } - List encodedVariants = new ArrayList(variants.length); + List encodedVariants = new ArrayList(variants.length + additionalItems.size()); for (int i = 0; i < candidates.length; i++) { final PsiElement element = candidates[i]; if (element instanceof PsiNamedElement) { @@ -116,6 +127,7 @@ public class FileReferenceCompletionImpl extends FileReferenceCompletion { } } } + encodedVariants.addAll(additionalItems); return ArrayUtil.toObjectArray(encodedVariants); } } diff --git a/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanDialog.java b/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanDialog.java index 089927426293..d3a8237db889 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanDialog.java +++ b/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanDialog.java @@ -15,7 +15,9 @@ */ package com.intellij.refactoring.invertBoolean; +import com.intellij.lang.LanguageNamesValidation; import com.intellij.lang.findUsages.DescriptiveNameUtil; +import com.intellij.lang.refactoring.NamesValidator; import com.intellij.openapi.project.Project; import com.intellij.openapi.help.HelpManager; import com.intellij.psi.PsiElement; @@ -61,7 +63,8 @@ public class InvertBooleanDialog extends RefactoringDialog { protected void doAction() { Project project = myElement.getProject(); final String name = myNameField.getText().trim(); - if (name.length() == 0) { + final NamesValidator namesValidator = LanguageNamesValidation.INSTANCE.forLanguage(myElement.getLanguage()); + if (namesValidator != null && !namesValidator.isIdentifier(name, myProject)) { CommonRefactoringUtil.showErrorMessage(InvertBooleanHandler.REFACTORING_NAME, RefactoringBundle.message("please.enter.a.valid.name.for.inverted.element", UsageViewUtil.getType(myElement)), diff --git a/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java b/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java index 256fb3edea31..690bb859a6b2 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java @@ -26,6 +26,7 @@ import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.refactoring.RefactoringActionHandler; import com.intellij.refactoring.RefactoringBundle; +import com.intellij.refactoring.rename.PsiElementRenameHandler; import com.intellij.refactoring.util.CommonRefactoringUtil; import org.jetbrains.annotations.NotNull; @@ -47,7 +48,7 @@ public class InvertBooleanHandler implements RefactoringActionHandler { return; } final PsiElement namedElement = delegate.adjustElement(element, project, editor); - if (namedElement != null) { + if (namedElement != null && PsiElementRenameHandler.canRename(project, editor, namedElement)) { new InvertBooleanDialog(namedElement).show(); } } @@ -70,7 +71,7 @@ public class InvertBooleanHandler implements RefactoringActionHandler { return; } PsiElement element = delegate.adjustElement(elements[0], project, null); - if (element != null) { + if (element != null && PsiElementRenameHandler.canRename(project, null, element)) { new InvertBooleanDialog(element).show(); } } diff --git a/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanProcessor.java index d2814b92a79e..88adfabf14ae 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanProcessor.java +++ b/platform/lang-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanProcessor.java @@ -23,6 +23,7 @@ import com.intellij.psi.*; import com.intellij.refactoring.BaseRefactoringProcessor; import com.intellij.refactoring.rename.RenameProcessor; import com.intellij.refactoring.rename.RenameUtil; +import com.intellij.refactoring.ui.ConflictsDialog; import com.intellij.refactoring.util.MoveRenameUsageInfo; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewDescriptor; @@ -30,6 +31,7 @@ import com.intellij.util.IncorrectOperationException; import com.intellij.util.containers.HashMap; import com.intellij.util.containers.MultiMap; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.LinkedHashSet; @@ -54,8 +56,25 @@ public class InvertBooleanProcessor extends BaseRefactoringProcessor { myElement = namedElement; myNewName = newName; final Project project = namedElement.getProject(); - myRenameProcessor = !(namedElement instanceof PsiNamedElement) || Comparing.equal(((PsiNamedElement)namedElement).getName(), myNewName) - ? null : new RenameProcessor(project, namedElement, newName, false, false); + final boolean canRename = + namedElement instanceof PsiNamedElement && !Comparing.equal(((PsiNamedElement)namedElement).getName(), myNewName); + myRenameProcessor = canRename ? new RenameProcessor(project, namedElement, newName, false, false) { + @NotNull + @Override + protected ConflictsDialog createConflictsDialog(@NotNull MultiMap conflicts, @Nullable final UsageInfo[] usages) { + return new ConflictsDialog(myProject, conflicts, usages == null ? null : new Runnable() { + @Override + public void run() { + InvertBooleanProcessor.this.execute(usages); + } + }, false, true); + } + + @Override + protected void prepareSuccessful() { + InvertBooleanProcessor.this.prepareSuccessful(); + } + } : null; mySmartPointerManager = SmartPointerManager.getInstance(project); myDelegate = InvertBooleanDelegate.findInvertBooleanDelegate(myElement); LOG.assertTrue(myDelegate != null); @@ -139,7 +158,6 @@ public class InvertBooleanProcessor extends BaseRefactoringProcessor { return extractedUsages.toArray(new UsageInfo[extractedUsages.size()]); } - @Override protected void performRefactoring(@NotNull UsageInfo[] usages) { if (myRenameProcessor != null) { diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/PsiElementRenameHandler.java b/platform/lang-impl/src/com/intellij/refactoring/rename/PsiElementRenameHandler.java index 9d8a53832932..ede322cb6ef4 100644 --- a/platform/lang-impl/src/com/intellij/refactoring/rename/PsiElementRenameHandler.java +++ b/platform/lang-impl/src/com/intellij/refactoring/rename/PsiElementRenameHandler.java @@ -119,7 +119,7 @@ public class PsiElementRenameHandler implements RenameHandler { rename(element, project, nameSuggestionContext, editor); } - static boolean canRename(Project project, Editor editor, PsiElement element) throws CommonRefactoringUtil.RefactoringErrorHintException { + public static boolean canRename(Project project, Editor editor, PsiElement element) throws CommonRefactoringUtil.RefactoringErrorHintException { String message = renameabilityStatus(project, element); if (StringUtil.isNotEmpty(message)) { showErrorMessage(project, editor, message); diff --git a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizard.java b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizard.java index 55c80b9f69cd..1c679654c380 100644 --- a/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizard.java +++ b/platform/platform-api/src/com/intellij/ide/wizard/AbstractWizard.java @@ -473,7 +473,12 @@ public abstract class AbstractWizard extends DialogWrapper { } protected void updateButtons() { - if (isLastStep()) { + boolean lastStep = isLastStep(); + updateButtons(lastStep, lastStep ? canFinish() : canGoNext(), isFirstStep()); + } + + public void updateButtons(boolean lastStep, boolean canGoNext, boolean firstStep) { + if (lastStep) { if (mySteps.size() > 1) { myNextButton.setText(UIUtil.removeMnemonic(IdeBundle.message("button.finish"))); myNextButton.setMnemonic('F'); @@ -481,19 +486,23 @@ public abstract class AbstractWizard extends DialogWrapper { else { myNextButton.setText(IdeBundle.message("button.ok")); } - myNextButton.setEnabled(canFinish()); + myNextButton.setEnabled(canGoNext); } else { myNextButton.setText(UIUtil.removeMnemonic(IdeBundle.message("button.wizard.next"))); myNextButton.setMnemonic('N'); - myNextButton.setEnabled(canGoNext()); + myNextButton.setEnabled(canGoNext); } if (myNextButton.isEnabled() && !ApplicationManager.getApplication().isUnitTestMode()) { getRootPane().setDefaultButton(myNextButton); } - myPreviousButton.setEnabled(myCurrentStep > 0); + myPreviousButton.setEnabled(!firstStep); + } + + protected boolean isFirstStep() { + return myCurrentStep == 0; } protected boolean isLastStep() { diff --git a/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java b/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java index 9a66d45345a9..f66a87c3c9d0 100644 --- a/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java +++ b/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java @@ -30,6 +30,7 @@ import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.help.HelpManager; import com.intellij.openapi.keymap.KeymapUtil; +import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.util.PopupUtil; import com.intellij.openapi.util.*; @@ -710,7 +711,7 @@ public abstract class DialogWrapper { final char mnemonic = (char)eachInfo.getMnemonic(); JRootPane rootPane = getPeer().getRootPane(); if (rootPane != null) { - new AnAction() { + new DumbAwareAction() { @Override public void actionPerformed(AnActionEvent e) { final JBOptionButton buttonToActivate = eachInfo.getButton(); @@ -1250,7 +1251,7 @@ public abstract class DialogWrapper { myPeer.setContentPane(root); final CustomShortcutSet sc = new CustomShortcutSet(SHOW_OPTION_KEYSTROKE); - final AnAction toggleShowOptions = new AnAction() { + final AnAction toggleShowOptions = new DumbAwareAction() { @Override public void actionPerformed(@NotNull AnActionEvent e) { expandNextOptionButton(); @@ -1306,7 +1307,7 @@ public abstract class DialogWrapper { } private static void installEnterHook(JComponent root, Disposable disposable) { - new AnAction() { + new DumbAwareAction() { @Override public void actionPerformed(AnActionEvent e) { final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); diff --git a/platform/platform-api/src/com/intellij/ui/ScreenUtil.java b/platform/platform-api/src/com/intellij/ui/ScreenUtil.java index ccd1eac11fc4..2a29a0fbd7d6 100644 --- a/platform/platform-api/src/com/intellij/ui/ScreenUtil.java +++ b/platform/platform-api/src/com/intellij/ui/ScreenUtil.java @@ -35,7 +35,7 @@ public class ScreenUtil { public static final String DISPOSE_TEMPORARY = "dispose.temporary"; @Nullable private static final Map> ourInsetsCache = - Patches.JDK_BUG_ID_8004103 ? new WeakHashMap>() : null; + Patches.isJdkBugId8004103() ? new WeakHashMap>() : null; private static final int ourInsetsTimeout = 5000; // shouldn't be too long private ScreenUtil() { } diff --git a/platform/platform-api/src/com/intellij/ui/components/JBScrollPane.java b/platform/platform-api/src/com/intellij/ui/components/JBScrollPane.java index 9f1d7754156e..5f4d23139774 100644 --- a/platform/platform-api/src/com/intellij/ui/components/JBScrollPane.java +++ b/platform/platform-api/src/com/intellij/ui/components/JBScrollPane.java @@ -149,7 +149,9 @@ public class JBScrollPane extends JScrollPane { } private void updateViewportBorder() { - setViewportBorder(new ViewportBorder(myViewportBorderWidth >= 0 ? myViewportBorderWidth : 1)); + if (getViewportBorder() instanceof ViewportBorder) { + setViewportBorder(new ViewportBorder(myViewportBorderWidth >= 0 ? myViewportBorderWidth : 1)); + } } public static ViewportBorder createIndentBorder() { diff --git a/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.form b/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.form index 6515359d2275..200c63c556da 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.form +++ b/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.form @@ -1,6 +1,6 @@
- + @@ -10,7 +10,7 @@ - + @@ -139,9 +139,18 @@ + + + + + + + + + - + diff --git a/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.java b/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.java index 900709072dcf..c31d72505a0b 100644 --- a/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.java +++ b/platform/platform-impl/src/com/intellij/diagnostic/OutOfMemoryDialog.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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,11 +18,15 @@ package com.intellij.diagnostic; import com.intellij.diagnostic.VMOptions.MemoryKind; import com.intellij.ide.IdeBundle; import com.intellij.idea.Main; +import com.intellij.openapi.application.ApplicationNamesInfo; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.Messages; import com.intellij.ui.IdeBorderFactory; import com.intellij.ui.JBColor; import com.intellij.ui.components.JBLabel; +import com.intellij.util.MemoryDumpHelper; +import com.intellij.util.SystemProperties; +import com.intellij.util.TimeoutUtil; import org.jetbrains.annotations.NotNull; import javax.swing.*; @@ -48,8 +52,10 @@ public class OutOfMemoryDialog extends DialogWrapper { private JBLabel myCodeCacheUnitsLabel; private JBLabel myCodeCacheCurrentValueLabel; private JBLabel mySettingsFileHintLabel; + private JBLabel myDumpMessageLabel; private final Action myContinueAction; private final Action myShutdownAction; + private final Action myHeapDumpAction; public OutOfMemoryDialog(@NotNull MemoryKind memoryKind) { super(false); @@ -89,6 +95,14 @@ public class OutOfMemoryDialog extends DialogWrapper { }; myShutdownAction.putValue(DialogWrapper.DEFAULT_ACTION, true); + boolean heapDump = memoryKind == MemoryKind.HEAP && MemoryDumpHelper.memoryDumpAvailable(); + myHeapDumpAction = !heapDump ? null : new DialogWrapperAction(DiagnosticBundle.message("diagnostic.out.of.memory.dump")) { + @Override + protected void doAction(ActionEvent e) { + snapshot(); + } + }; + configControls(MemoryKind.HEAP, myHeapSizeLabel, myHeapSizeField, myHeapUnitsLabel, myHeapCurrentValueLabel); configControls(MemoryKind.PERM_GEN, myPermGenSizeLabel, myPermGenSizeField, myPermGenUnitsLabel, myPermGenCurrentValueLabel); configControls(MemoryKind.CODE_CACHE, myCodeCacheSizeLabel, myCodeCacheSizeField, myCodeCacheUnitsLabel, myCodeCacheCurrentValueLabel); @@ -137,6 +151,51 @@ public class OutOfMemoryDialog extends DialogWrapper { catch (NumberFormatException ignored) { } } + @SuppressWarnings("SSBasedInspection") + private void snapshot() { + enableControls(false); + myDumpMessageLabel.setVisible(true); + myDumpMessageLabel.setText("Dumping memory..."); + + Runnable task = new Runnable() { + @Override + public void run() { + TimeoutUtil.sleep(250); // to give UI chance to update + String message = ""; + try { + String name = ApplicationNamesInfo.getInstance().getLowercaseProductName(); + String path = SystemProperties.getUserHome() + File.separator + "heapDump-" + name + '-' + System.currentTimeMillis() + ".hprof"; + MemoryDumpHelper.captureMemoryDump(path); + message = "Dumped to " + path; + } + catch (Throwable t) { + message = "Error: " + t.getMessage(); + } + finally { + final String _message = message; + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + myDumpMessageLabel.setText(_message); + enableControls(true); + } + }); + } + } + }; + new Thread(task, "OOME Heap Dump").start(); + } + + @SuppressWarnings("Duplicates") + private void enableControls(boolean enabled) { + myHeapSizeField.setEnabled(enabled); + myPermGenSizeField.setEnabled(enabled); + myCodeCacheSizeField.setEnabled(enabled); + myShutdownAction.setEnabled(enabled); + myContinueAction.setEnabled(enabled); + myHeapDumpAction.setEnabled(enabled); + } + @Override protected JComponent createCenterPanel() { return myContentPane; @@ -145,7 +204,8 @@ public class OutOfMemoryDialog extends DialogWrapper { @NotNull @Override protected Action[] createActions() { - return new Action[]{myShutdownAction, myContinueAction}; + return myHeapDumpAction != null ? new Action[]{myShutdownAction, myContinueAction, myHeapDumpAction} + : new Action[]{myShutdownAction, myContinueAction}; } @Override diff --git a/platform/platform-impl/src/com/intellij/internal/DebugAttachDetector.java b/platform/platform-impl/src/com/intellij/internal/DebugAttachDetector.java index 52e366d81d73..140246f6c228 100644 --- a/platform/platform-impl/src/com/intellij/internal/DebugAttachDetector.java +++ b/platform/platform-impl/src/com/intellij/internal/DebugAttachDetector.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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,17 +15,18 @@ */ package com.intellij.internal; +import com.intellij.concurrency.JobScheduler; import com.intellij.notification.Notification; import com.intellij.notification.NotificationType; import com.intellij.notification.Notifications; import com.intellij.openapi.application.ex.ApplicationEx; import com.intellij.openapi.application.ex.ApplicationManagerEx; import com.intellij.openapi.diagnostic.Logger; -import com.intellij.util.Alarm; -import com.intellij.util.SingleAlarm; import com.intellij.util.net.NetUtils; import java.lang.management.ManagementFactory; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; /** * @author egor @@ -33,11 +34,11 @@ import java.lang.management.ManagementFactory; public class DebugAttachDetector { private static final Logger LOG = Logger.getInstance(DebugAttachDetector.class); - private String myHost = null; + private String myHost; private int myPort = -1; - private SingleAlarm myAlarm; + private ScheduledFuture myTask; private boolean myAttached; - private boolean myReady = false; + private boolean myReady; public DebugAttachDetector() { ApplicationEx app = ApplicationManagerEx.getApplicationEx(); @@ -74,24 +75,22 @@ public class DebugAttachDetector { if (myPort < 0) return; - myAlarm = new SingleAlarm(new Runnable() { - @Override - public void run() { - boolean attached = !NetUtils.canConnectToRemoteSocket(myHost, myPort); - if (!myReady) { - myAttached = attached; - myReady = true; + myTask = JobScheduler.getScheduler().scheduleWithFixedDelay(new Runnable() { + @Override + public void run() { + boolean attached = !NetUtils.canConnectToRemoteSocket(myHost, myPort); + if (!myReady) { + myAttached = attached; + myReady = true; + } + else if (attached != myAttached) { + myAttached = attached; + Notifications.Bus.notify(new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, + "Remote debugger", + myAttached ? "attached" : "detached", + NotificationType.WARNING)); + } } - else if (attached != myAttached) { - myAttached = attached; - Notifications.Bus.notify(new Notification(Notifications.SYSTEM_MESSAGES_GROUP_ID, - "Remote debugger", - myAttached ? "attached" : "detached", - NotificationType.WARNING)); - } - myAlarm.request(); - } - }, 5000, Alarm.ThreadToUse.POOLED_THREAD, app); - myAlarm.request(); + }, 5, 5, TimeUnit.SECONDS); } } diff --git a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java index d336b543303a..7dda120ebed4 100644 --- a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java @@ -333,8 +333,7 @@ public class NotificationsManagerImpl extends NotificationsManager { if (text.getCaret() != null) { text.setCaretPosition(0); } - JScrollPane pane = new JScrollPane(text); // do not add 1px border for viewport on UI update - pane.setBorder(BorderFactory.createEmptyBorder()); + JScrollPane pane = ScrollPaneFactory.createScrollPane(text, true); // do not add 1px border for viewport on UI update pane.setOpaque(false); pane.getViewport().setOpaque(false); content.add(pane, BorderLayout.CENTER); diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorComponentImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorComponentImpl.java index a6244dc07117..b8f1c8087650 100644 --- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorComponentImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorComponentImpl.java @@ -112,7 +112,7 @@ public class EditorComponentImpl extends JTextComponent implements Scrollable, D @Override public void paint(@NotNull Graphics g) { if (!isEnabled()) { - g = new Grayer((Graphics2D)g, EditorColorsManager.getInstance().getGlobalScheme().getDefaultBackground()); + g = new Grayer((Graphics2D)g, getBackground()); } super.paint(g); } diff --git a/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java index 8c886cca55f7..c4f2890d9ea0 100644 --- a/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java +++ b/platform/platform-impl/src/com/intellij/openapi/vcs/impl/FileStatusManagerImpl.java @@ -113,6 +113,7 @@ public class FileStatusManagerImpl extends FileStatusManager implements ProjectC DocumentAdapter documentListener = new DocumentAdapter() { @Override public void documentChanged(DocumentEvent event) { + if (event.getOldLength() == 0 && event.getNewLength() == 0) return; VirtualFile file = FileDocumentManager.getInstance().getFile(event.getDocument()); if (file != null) { refreshFileStatusFromDocument(file, event.getDocument()); diff --git a/platform/platform-impl/src/com/intellij/remote/BaseRemoteProcessHandler.java b/platform/platform-impl/src/com/intellij/remote/BaseRemoteProcessHandler.java index 942bda01f109..7f0415b58a4d 100644 --- a/platform/platform-impl/src/com/intellij/remote/BaseRemoteProcessHandler.java +++ b/platform/platform-impl/src/com/intellij/remote/BaseRemoteProcessHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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,12 +17,14 @@ package com.intellij.remote; import com.intellij.execution.CommandLineUtil; import com.intellij.execution.TaskExecutor; -import com.intellij.execution.process.*; -import com.intellij.openapi.application.Application; -import com.intellij.openapi.application.ApplicationManager; +import com.intellij.execution.process.ProcessAdapter; +import com.intellij.execution.process.ProcessEvent; +import com.intellij.execution.process.ProcessOutputTypes; +import com.intellij.execution.process.ProcessWaitFor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Consumer; +import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.io.BaseOutputReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -181,14 +183,9 @@ public class BaseRemoteProcessHandler extends AbstractR return myCharset; } - protected static Future executeOnPooledThread(Runnable task) { - final Application application = ApplicationManager.getApplication(); - - if (application != null) { - return application.executeOnPooledThread(task); - } - - return BaseOSProcessHandler.submit(task); + @NotNull + private static Future executeOnPooledThread(@NotNull Runnable task) { + return AppExecutorUtil.getAppExecutorService().submit(task); } @NotNull diff --git a/platform/platform-impl/src/com/intellij/ui/EditorTextField.java b/platform/platform-impl/src/com/intellij/ui/EditorTextField.java index b20a27e6fddf..54cf1e4f2572 100644 --- a/platform/platform-impl/src/com/intellij/ui/EditorTextField.java +++ b/platform/platform-impl/src/com/intellij/ui/EditorTextField.java @@ -479,27 +479,7 @@ public class EditorTextField extends NonOpaquePanel implements DocumentListener, editor.setHighlighter(EditorHighlighterFactory.getInstance().createEditorHighlighter(myProject, myFileType)); } - final EditorColorsScheme colorsScheme = editor.getColorsScheme(); editor.getSettings().setCaretRowShown(false); - if (!isEnabled()) { - editor.setColorsScheme(new DelegateColorScheme(colorsScheme) { - @Nullable - @Override - public Color getColor(ColorKey key) { - return super.getColor(key); - } - - @Override - public TextAttributes getAttributes(TextAttributesKey key) { - final TextAttributes attributes = super.getAttributes(key); - if (!isEnabled()) { - return new TextAttributes(UIUtil.getInactiveTextColor(), attributes.getBackgroundColor(), attributes.getEffectColor(), attributes.getEffectType(), attributes.getFontType()); - } - - return attributes; - } - }); - } editor.setOneLineMode(myOneLineMode); editor.getCaretModel().moveToOffset(myDocument.getTextLength()); diff --git a/platform/platform-impl/src/com/intellij/util/path.kt b/platform/platform-impl/src/com/intellij/util/path.kt index 4fa7049faaa8..1517c96c71a3 100644 --- a/platform/platform-impl/src/com/intellij/util/path.kt +++ b/platform/platform-impl/src/com/intellij/util/path.kt @@ -21,12 +21,8 @@ import com.intellij.openapi.vfs.VfsUtil import java.io.File import java.io.IOException import java.io.OutputStream -import java.nio.file.FileVisitResult -import java.nio.file.Files -import java.nio.file.Path -import java.nio.file.SimpleFileVisitor +import java.nio.file.* import java.nio.file.attribute.BasicFileAttributes -import java.nio.file.attribute.FileTime fun Path.exists() = Files.exists(this) @@ -74,7 +70,7 @@ fun Path.deleteRecursively(): Path = if (exists()) Files.walkFileTree(this, obje } }) else this -fun Path.getLastModifiedTime(): FileTime? = Files.getLastModifiedTime(this) +fun Path.lastModified() = Files.getLastModifiedTime(this) val Path.systemIndependentPath: String get() = toString().replace(File.separatorChar, '/') @@ -90,15 +86,33 @@ fun Path.writeChild(relativePath: String, data: ByteArray) = resolve(relativePat fun Path.writeChild(relativePath: String, data: String) = writeChild(relativePath, data.toByteArray()) -fun Path.write(data: ByteArray): Path { - parent?.createDirectories() - return Files.write(this, data) +fun Path.write(data: ByteArray, offset: Int = 0, length: Int = data.size): Path { + outputStream().use { it.write(data, offset, length) } + return this } +fun Path.size() = Files.size(this) + +fun Path.sizeOrNull(): Long { + val attributes: BasicFileAttributes + try { + attributes = Files.readAttributes(this, BasicFileAttributes::class.java) + } + catch (ignored: IOException) { + return -1 + } + + return attributes.size() +} + +fun Path.isHidden() = Files.isHidden(this) + fun Path.isDirectory() = Files.isDirectory(this) fun Path.isFile() = Files.isRegularFile(this) +fun Path.move(target: Path) = Files.move(this, target) + /** * Opposite to Java, parent directories will be created */ @@ -115,4 +129,22 @@ fun Path.refreshVfs() { VfsUtil.markDirtyAndRefresh(false, true, true, virtualFile) } } +} + +inline fun Path.directoryStreamIfExists(task: (stream: DirectoryStream) -> R): R? { + try { + Files.newDirectoryStream(this).use(task) + } + catch (ignored: NoSuchFileException) { + } + return null +} + +inline fun Path.directoryStreamIfExists(noinline filter: ((path: Path) -> Boolean), task: (stream: DirectoryStream) -> R): R? { + try { + Files.newDirectoryStream(this, { filter.invoke(it) }).use(task) + } + catch (ignored: NoSuchFileException) { + } + return null } \ No newline at end of file diff --git a/platform/platform-resources-en/src/messages/DiagnosticBundle.properties b/platform/platform-resources-en/src/messages/DiagnosticBundle.properties index 5fa39c2f9508..3f9d30574401 100644 --- a/platform/platform-resources-en/src/messages/DiagnosticBundle.properties +++ b/platform/platform-resources-en/src/messages/DiagnosticBundle.properties @@ -7,6 +7,7 @@ diagnostic.out.of.memory.title=Out of Memory diagnostic.out.of.memory.currentValue=(current value: {0}) diagnostic.out.of.memory.currentValue.unknown=Unknown diagnostic.out.of.memory.continue=Continue +diagnostic.out.of.memory.dump=Memory Dump diagnostic.error.report.send=&Send diagnostic.error.report.description=If you would like to get notified when the exceptions you submit are fixed,
please fill in your JetBrains Account login and password. diagnostic.error.report.proxy.setup=Set up HTTP proxy settings diff --git a/platform/platform-tests/testSrc/com/intellij/ide/bookmarks/BookmarkManagerTest.java b/platform/platform-tests/testSrc/com/intellij/ide/bookmarks/BookmarkManagerTest.java index 032e18010627..8f64a1116a64 100644 --- a/platform/platform-tests/testSrc/com/intellij/ide/bookmarks/BookmarkManagerTest.java +++ b/platform/platform-tests/testSrc/com/intellij/ide/bookmarks/BookmarkManagerTest.java @@ -15,12 +15,16 @@ */ package com.intellij.ide.bookmarks; +import com.intellij.openapi.application.ApplicationManager; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.impl.AbstractEditorTest; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; +import com.intellij.openapi.util.Computable; import com.intellij.openapi.vcs.changes.ChangeListManagerImpl; import com.intellij.openapi.vfs.VfsUtil; +import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.testFramework.LeakHunter; import com.intellij.testFramework.TestFileType; @@ -60,8 +64,14 @@ public class BookmarkManagerTest extends AbstractEditorTest { addBookmark(2); List bookmarksBefore = getManager().getValidBookmarks(); assertEquals(1, bookmarksBefore.size()); - - myEditor.getDocument().setText(text); + + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + myEditor.getDocument().setText(text); + } + }.execute().throwException(); + List bookmarksAfter = getManager().getValidBookmarks(); assertEquals(1, bookmarksAfter.size()); assertSame(bookmarksBefore.get(0), bookmarksAfter.get(0)); @@ -157,8 +167,14 @@ public class BookmarkManagerTest extends AbstractEditorTest { "}"; init(text, TestFileType.TEXT); addBookmark(2); - - myEditor.getDocument().setText("111\n222" + text + "333"); + + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + myEditor.getDocument().setText("111\n222" + text + "333"); + } + }.execute().throwException(); + List bookmarks = getManager().getValidBookmarks(); assertEquals(1, bookmarks.size()); Bookmark bookmark = bookmarks.get(0); @@ -171,8 +187,19 @@ public class BookmarkManagerTest extends AbstractEditorTest { "public class Test {\n" + "}"; - myVFile = getSourceRoot().createChildData(null, getTestName(false) + ".txt"); - VfsUtil.saveText(myVFile, text); + myVFile = ApplicationManager.getApplication().runWriteAction(new Computable() { + @Override + public VirtualFile compute() { + try { + VirtualFile file = getSourceRoot().createChildData(null, getTestName(false) + ".txt"); + VfsUtil.saveText(file, text); + return file; + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + }); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); Bookmark bookmark = getManager().addTextBookmark(myVFile, 1, "xxx"); @@ -183,7 +210,13 @@ public class BookmarkManagerTest extends AbstractEditorTest { assertNotNull(document); PsiDocumentManager.getInstance(getProject()).getPsiFile(document); // create psi so that PsiChangeHandler won't leak - document.insertString(0, "line 0\n"); + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + document.insertString(0, "line 0\n"); + } + }.execute().throwException(); + assertEquals(2, bookmark.getLine()); myEditor = createEditor(myVFile); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorModificationUtilTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorModificationUtilTest.java index 8c1cee450cf5..c5b086c193fb 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorModificationUtilTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/EditorModificationUtilTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2014 JetBrains s.r.o. + * Copyright 2000-2016 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,12 +15,19 @@ */ package com.intellij.openapi.editor; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.testFramework.LightPlatformCodeInsightTestCase; public class EditorModificationUtilTest extends LightPlatformCodeInsightTestCase { public void testInsertStringAtCaretNotMovingCaret() throws Exception { configureFromFileText(getTestName(false) + ".txt", "text "); - EditorModificationUtil.insertStringAtCaret(myEditor, " ", false, false); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + EditorModificationUtil.insertStringAtCaret(myEditor, " ", false, false); + } + }); + checkResultByText("text "); } } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingTest.java index b963a84fcba7..15217f2cd386 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/FoldingTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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,8 +19,7 @@ import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.ex.FoldingModelEx; import com.intellij.openapi.editor.impl.AbstractEditorTest; import com.intellij.testFramework.TestFileType; - -import static org.junit.Assert.assertArrayEquals; +import org.junit.Assert; /** * @author max @@ -157,7 +156,7 @@ public class FoldingTest extends AbstractEditorTest { addCollapsedFoldRegion(10, 12, "???"); FoldRegion[] topLevelRegions = myModel.fetchTopLevel(); - assertArrayEquals(new FoldRegion[]{region}, topLevelRegions); + Assert.assertArrayEquals(new FoldRegion[]{region}, topLevelRegions); } public void testLastCollapsedRegionBefore() { @@ -184,8 +183,14 @@ public class FoldingTest extends AbstractEditorTest { public void testModelRemainsConsistentOnTextRemoval() { addCollapsedFoldRegion(0, 10, "..."); addCollapsedFoldRegion(1, 9, "..."); - - myEditor.getDocument().deleteString(0, 1); + + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + myEditor.getDocument().deleteString(0, 1); + } + }); + addFoldRegion(20, 21, "..."); // an arbitrary action to rebuild folding caches assertTrue(myModel.isOffsetCollapsed(5)); @@ -195,8 +200,14 @@ public class FoldingTest extends AbstractEditorTest { addFoldRegion(0, 5, "..."); addFoldRegion(0, 4, "..."); assertNumberOfValidFoldRegions(2); - - myEditor.getDocument().deleteString(4, 5); + + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + myEditor.getDocument().deleteString(4, 5); + } + }); + assertNumberOfValidFoldRegions(1); } @@ -204,7 +215,13 @@ public class FoldingTest extends AbstractEditorTest { public void testTopLevelRegionRemainsTopLevelAfterMergingIdenticalRegions() { addCollapsedFoldRegion(10, 15, "..."); addCollapsedFoldRegion(10, 14, "..."); - myEditor.getDocument().deleteString(14, 15); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + myEditor.getDocument().deleteString(14, 15); + } + }); + FoldRegion region = myModel.getCollapsedRegionAtOffset(10); assertNotNull(region); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/EditorImplTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/EditorImplTest.java index d2048d78b998..8acfa6cccc5d 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/EditorImplTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/EditorImplTest.java @@ -17,6 +17,7 @@ package com.intellij.openapi.editor.impl; import com.intellij.codeInsight.folding.CodeFoldingManager; import com.intellij.openapi.actionSystem.IdeActions; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.FoldRegion; import com.intellij.openapi.editor.LogicalPosition; @@ -70,11 +71,17 @@ public class EditorImplTest extends AbstractEditorTest { assertEquals(4, EditorUtil.getTabSize(myEditor)); assertEquals("[FoldRegion +(59:64), placeholder=' { ', FoldRegion +(85:88), placeholder=' }']", myEditor.getFoldingModel().toString()); verifySoftWrapPositions(52, 85); - - Document document = myEditor.getDocument(); - for (int i = document.getLineCount() - 1; i >= 0; i--) { - document.insertString(document.getLineStartOffset(i), "//"); - } + + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + Document document = myEditor.getDocument(); + for (int i = document.getLineCount() - 1; i >= 0; i--) { + document.insertString(document.getLineStartOffset(i), "//"); + } + } + }.execute().throwException(); + verifySoftWrapPositions(58, 93); } @@ -105,13 +112,19 @@ public class EditorImplTest extends AbstractEditorTest { public void testNoExceptionDuringBulkModeDocumentUpdate() throws Exception { initText("something"); DocumentEx document = (DocumentEx)myEditor.getDocument(); - document.setInBulkUpdate(true); - try { - document.setText("something\telse"); - } - finally { - document.setInBulkUpdate(false); - } + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + document.setInBulkUpdate(true); + try { + document.setText("something\telse"); + } + finally { + document.setInBulkUpdate(false); + } + } + }.execute().throwException(); + checkResultByText("something\telse"); } @@ -147,8 +160,14 @@ public class EditorImplTest extends AbstractEditorTest { public void testNavigationInsideNonNormalizedLineTerminator() throws Exception { initText(""); ((DocumentImpl)myEditor.getDocument()).setAcceptSlashR(true); - myEditor.getDocument().insertString(0, "abc\r\ndef"); - + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + myEditor.getDocument().insertString(0, "abc\r\ndef"); + } + }.execute().throwException(); + + myEditor.getCaretModel().moveToOffset(4); assertEquals(new LogicalPosition(0, 3), myEditor.getCaretModel().getLogicalPosition()); @@ -159,26 +178,38 @@ public class EditorImplTest extends AbstractEditorTest { initText("long long line"); configureSoftWraps(12); DocumentEx document = (DocumentEx)myEditor.getDocument(); - document.setInBulkUpdate(true); - document.replaceString(4, 5, "-"); - document.setInBulkUpdate(false); + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + document.setInBulkUpdate(true); + document.replaceString(4, 5, "-"); + document.setInBulkUpdate(false); + } + }.execute().throwException(); + assertEquals(new VisualPosition(1, 5), myEditor.getCaretModel().getVisualPosition()); } public void testSuccessiveBulkModeOperations() throws Exception { initText("some text"); DocumentEx document = (DocumentEx)myEditor.getDocument(); - - document.setInBulkUpdate(true); - document.replaceString(4, 5, "-"); - document.setInBulkUpdate(false); - - myEditor.getCaretModel().moveToOffset(9); - - document.setInBulkUpdate(true); - document.replaceString(4, 5, "+"); - document.setInBulkUpdate(false); - + + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + document.setInBulkUpdate(true); + document.replaceString(4, 5, "-"); + document.setInBulkUpdate(false); + + myEditor.getCaretModel().moveToOffset(9); + + document.setInBulkUpdate(true); + document.replaceString(4, 5, "+"); + document.setInBulkUpdate(false); + } + }.execute().throwException(); + + checkResultByText("some+text"); } @@ -220,10 +251,16 @@ public class EditorImplTest extends AbstractEditorTest { public void testUpdatingCaretPositionAfterBulkMode() throws Exception { initText("abc"); - DocumentEx document = (DocumentEx)myEditor.getDocument(); - document.setInBulkUpdate(true); - document.insertString(0, "\n "); // we're changing number of visual lines, and invalidating text layout for caret line - document.setInBulkUpdate(false); + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + DocumentEx document = (DocumentEx)myEditor.getDocument(); + document.setInBulkUpdate(true); + document.insertString(0, "\n "); // we're changing number of visual lines, and invalidating text layout for caret line + document.setInBulkUpdate(false); + } + }.execute().throwException(); + checkResultByText("\n abc"); } @@ -255,7 +292,13 @@ public class EditorImplTest extends AbstractEditorTest { JViewport viewport = ((EditorEx)myEditor).getScrollPane().getViewport(); Dimension normalSize = viewport.getExtentSize(); viewport.setExtentSize(new Dimension(0, 0)); - myEditor.getDocument().deleteString(5, 14); + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + myEditor.getDocument().deleteString(5, 14); + } + }.execute().throwException(); + viewport.setExtentSize(normalSize); verifySoftWrapPositions(); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/EditorStressTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/EditorStressTest.java index 66058c954e9e..43a8e5036b04 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/EditorStressTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/EditorStressTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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.editor.impl; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.EditorEx; @@ -108,7 +109,12 @@ public class EditorStressTest extends AbstractEditorTest { public void perform(EditorEx editor, Random random) { Document document = editor.getDocument(); int offset = random.nextInt(document.getTextLength() + 1); - document.insertString(offset, myText); + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + document.insertString(offset, myText); + } + }.execute().throwException(); } } @@ -119,7 +125,12 @@ public class EditorStressTest extends AbstractEditorTest { int textLength = document.getTextLength(); if (textLength <= 0) return; int offset = random.nextInt(textLength); - document.deleteString(offset, offset + 1); + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + document.deleteString(offset, offset + 1); + } + }.execute().throwException(); } } @@ -132,7 +143,12 @@ public class EditorStressTest extends AbstractEditorTest { int offset = random.nextInt(textLength); int targetOffset = random.nextInt(textLength + 1); if (targetOffset < offset || targetOffset > offset + 1) { - ((DocumentEx)document).moveText(offset, offset + 1, targetOffset); + new WriteCommandAction.Simple(getProject()) { + @Override + protected void run() throws Throwable { + ((DocumentEx)document).moveText(offset, offset + 1, targetOffset); + } + }.execute().throwException(); } } } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/TrailingSpacesStripperTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/TrailingSpacesStripperTest.java index 269ff6b7427d..c6bc8b209999 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/TrailingSpacesStripperTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/TrailingSpacesStripperTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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.editor.Editor; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.EditorSettingsExternalizable; import com.intellij.openapi.fileEditor.FileDocumentManager; +import com.intellij.openapi.util.Computable; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.testFramework.EditorTestUtil; @@ -175,7 +176,14 @@ public class TrailingSpacesStripperTest extends LightPlatformCodeInsightTestCase Document document = configureFromFileText("x.txt", "xxx \nyyy\n\t\t\t"); // make any modification, so that Document and file content differ. Otherwise save won't be, and "on-save" actions won't be called. - document.insertString(0, " "); + WriteCommandAction.runWriteCommandAction(getProject(), + new Runnable() { + @Override + public void run() { + document.insertString(0, " "); + } + }); + FileDocumentManager.getInstance().saveAllDocuments(); checkResultByText(" xxx \nyyy\n\t\t\t\n"); @@ -218,8 +226,19 @@ public class TrailingSpacesStripperTest extends LightPlatformCodeInsightTestCase @NotNull private static Editor createHeavyEditor(@NotNull String name, @NotNull String text) throws IOException { - VirtualFile myVFile = getSourceRoot().createChildData(null, name); - VfsUtil.saveText(myVFile, text); + VirtualFile myVFile = ApplicationManager.getApplication().runWriteAction(new Computable() { + @Override + public VirtualFile compute() { + try { + VirtualFile file = getSourceRoot().createChildData(null, name); + VfsUtil.saveText(file, text); + return file; + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + }); final FileDocumentManager manager = FileDocumentManager.getInstance(); final Document document = manager.getDocument(myVFile); manager.reloadFromDisk(document); diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java index 884755c595ff..3063d45e2b97 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/softwrap/mapping/SoftWrapApplianceOnDocumentModificationTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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.openapi.editor.impl.softwrap.mapping; import com.intellij.codeInsight.folding.CodeFoldingManager; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.ex.DocumentEx; import com.intellij.openapi.editor.ex.util.EditorUtil; @@ -726,7 +727,13 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorT addCollapsedFoldRegion(foldStartOffset, foldEndOffset, "..."); // Simulate addition of the new import that modifies existing fold region. - myEditor.getDocument().insertString(foldEndOffset, "\nimport java.util.Date;\n"); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + myEditor.getDocument().insertString(foldEndOffset, "\nimport java.util.Date;\n"); + } + }); + final FoldingModel foldingModel = myEditor.getFoldingModel(); foldingModel.runBatchFoldingOperation(() -> { FoldRegion oldFoldRegion = getFoldRegion(foldStartOffset); @@ -757,7 +764,13 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorT addCollapsedFoldRegion(foldStartOffset, foldEndOffset, "..."); int modificationOffset = text.indexOf("java.util.Set"); - myEditor.getDocument().insertString(modificationOffset, "import java.util.HashSet;\n"); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + myEditor.getDocument().insertString(modificationOffset, "import java.util.HashSet;\n"); + } + }); + // Used to get StackOverflowError here, hence, no additional checking is performed. } @@ -833,8 +846,14 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorT final EditorSettings settings = getEditor().getSettings(); settings.setUseSoftWraps(false); int startOffset = text.indexOf("\t third") - 1; - getEditor().getDocument().deleteString(startOffset, text.length()); - + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + getEditor().getDocument().deleteString(startOffset, text.length()); + } + }); + + // Enable soft wraps and ensure that the cache is correctly re-built. settings.setUseSoftWraps(true); @@ -1044,7 +1063,13 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorT addCollapsedFoldRegion(4, 8, "..."); addCollapsedFoldRegion(13, 15, "..."); - myEditor.getDocument().insertString(10, "C"); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + myEditor.getDocument().insertString(10, "C"); + } + }); + // verify that cached layout data is intact after document change and position recalculation is done correctly assertEquals(new LogicalPosition(0, 0), myEditor.visualToLogicalPosition(new VisualPosition(0, 0))); @@ -1120,7 +1145,13 @@ public class SoftWrapApplianceOnDocumentModificationTest extends AbstractEditorT configureSoftWraps(100); addCollapsedFoldRegion(0, 4, "..."); - ((DocumentEx)myEditor.getDocument()).moveText(0, 4, 12); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + ((DocumentEx)myEditor.getDocument()).moveText(0, 4, 12); + } + }); + assertEquals(new LogicalPosition(2, 0), myEditor.visualToLogicalPosition(new VisualPosition(2, 1))); } diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/view/LogicalPositionCacheStressTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/view/LogicalPositionCacheStressTest.java index 29911cbdffa4..64552b13e89b 100644 --- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/view/LogicalPositionCacheStressTest.java +++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/impl/view/LogicalPositionCacheStressTest.java @@ -15,6 +15,7 @@ */ package com.intellij.openapi.editor.impl.view; +import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.ex.DocumentEx; @@ -91,7 +92,12 @@ public class LogicalPositionCacheStressTest extends AbstractEditorTest { Document document = editor.getDocument(); int offset = random.nextInt(document.getTextLength() + 1); CharSequence text = generateText(random); - document.insertString(offset, text); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + document.insertString(offset, text); + } + }); } } @@ -103,7 +109,12 @@ public class LogicalPositionCacheStressTest extends AbstractEditorTest { if (textLength <= 0) return; int from = random.nextInt(textLength + 1); int to = random.nextInt(textLength + 1); - document.deleteString(Math.min(from, to), Math.max(from, to)); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + document.deleteString(Math.min(from, to), Math.max(from, to)); + } + }); } } @@ -116,7 +127,12 @@ public class LogicalPositionCacheStressTest extends AbstractEditorTest { int from = random.nextInt(textLength + 1); int to = random.nextInt(textLength + 1); CharSequence text = generateText(random); - document.replaceString(Math.min(from, to), Math.max(from, to), text); + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + document.replaceString(Math.min(from, to), Math.max(from, to), text); + } + }); } } @@ -129,12 +145,17 @@ public class LogicalPositionCacheStressTest extends AbstractEditorTest { int[] offsets = new int[] {random.nextInt(textLength + 1), random.nextInt(textLength + 1), random.nextInt(textLength + 1)}; Arrays.sort(offsets); if (offsets[0] == offsets[1] || offsets[1] == offsets[2]) return; - if (random.nextBoolean()) { - ((DocumentEx)document).moveText(offsets[0], offsets[1], offsets[2]); - } - else { - ((DocumentEx)document).moveText(offsets[1], offsets[2], offsets[0]); - } + WriteCommandAction.runWriteCommandAction(getProject(), new Runnable() { + @Override + public void run() { + if (random.nextBoolean()) { + ((DocumentEx)document).moveText(offsets[0], offsets[1], offsets[2]); + } + else { + ((DocumentEx)document).moveText(offsets[1], offsets[2], offsets[0]); + } + } + }); } } } diff --git a/platform/platform-tests/testSrc/com/intellij/psi/impl/PsiDocumentManagerImplTest.java b/platform/platform-tests/testSrc/com/intellij/psi/impl/PsiDocumentManagerImplTest.java index bf45e594dc4a..56169b8f1dc7 100644 --- a/platform/platform-tests/testSrc/com/intellij/psi/impl/PsiDocumentManagerImplTest.java +++ b/platform/platform-tests/testSrc/com/intellij/psi/impl/PsiDocumentManagerImplTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -29,6 +29,7 @@ import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.editor.impl.TrailingSpacesStripper; import com.intellij.openapi.editor.impl.event.DocumentEventImpl; import com.intellij.openapi.fileEditor.FileDocumentManager; +import com.intellij.openapi.fileTypes.StdFileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.ui.DialogWrapper; @@ -306,6 +307,40 @@ public class PsiDocumentManagerImplTest extends PlatformTestCase { assertEquals(2, count.get()); } + public void testDocumentCommittedInBackgroundEventuallyEvenDespiteTyping() throws InterruptedException, IOException { + VirtualFile virtualFile = getVirtualFile(createTempFile("X.java", "")); + PsiFile file = findFile(virtualFile); + assertNotNull(file); + assertTrue(file.isPhysical()); + final Document document = getDocument(file); + assertNotNull(document); + + WriteCommandAction.runWriteCommandAction(null, () -> { + document.insertString(0, "class X {"+StringUtil.repeat("public int IIII = 222;\n",10000)+"}"); + }); + + while (!getPsiDocumentManager().isCommitted(document)) { + UIUtil.dispatchAllInvocationEvents(); + } + + assertEquals(StdFileTypes.JAVA.getLanguage(), file.getLanguage()); + + for (int i=0;i<300;i++) { + assertTrue("Still not committed: " + document, getPsiDocumentManager().isCommitted(document)); + WriteCommandAction.runWriteCommandAction(null, () -> { + document.insertString(0, "/**/"); + assertFalse(getPsiDocumentManager().isCommitted(document)); + }); + waitForCommit(document, i); + WriteCommandAction.runWriteCommandAction(null, () -> { + document.deleteString(0, "/**/".length()); + }); + waitTenSecondsForCommit(document); + assertTrue("Still not committed: " + document, getPsiDocumentManager().isCommitted(document)); + //System.out.println("i = " + i); + } + } + private static void waitAndPump(Semaphore semaphore, int timeout) { final long limit = System.currentTimeMillis() + timeout; while (System.currentTimeMillis() < limit) { @@ -335,8 +370,8 @@ public class PsiDocumentManagerImplTest extends PlatformTestCase { final PsiDocumentManagerImpl alienDocManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(alienProject); final Document alienDocument = alienDocManager.getDocument(alienFile); assertSame(document, alienDocument); - assertEquals(0, alienDocManager.getUncommittedDocuments().length); - assertEquals(0, getPsiDocumentManager().getUncommittedDocuments().length); + assertEmpty(alienDocManager.getUncommittedDocuments()); + assertEmpty(getPsiDocumentManager().getUncommittedDocuments()); WriteCommandAction.runWriteCommandAction(null, () -> { document.setText("xxx"); @@ -346,10 +381,7 @@ public class PsiDocumentManagerImplTest extends PlatformTestCase { assertEquals("xxx", document.getText()); assertEquals("xxx", alienDocument.getText()); - long t1 = System.currentTimeMillis() + TIMEOUT; - while (!getPsiDocumentManager().isCommitted(document) && System.currentTimeMillis() < t1) { - UIUtil.dispatchAllInvocationEvents(); - } + waitForCommit(document, TIMEOUT); assertTrue("Still not committed: " + document, getPsiDocumentManager().isCommitted(document)); long t2 = System.currentTimeMillis() + TIMEOUT; @@ -458,26 +490,17 @@ public class PsiDocumentManagerImplTest extends PlatformTestCase { }); assertNotSame(ModalityState.NON_MODAL, ApplicationManager.getApplication().getCurrentModalityState()); - long start = System.currentTimeMillis(); - while (System.currentTimeMillis() - start < 10000) { - UIUtil.dispatchAllInvocationEvents(); - // must not be committed until exit modal dialog - assertFalse(getPsiDocumentManager().isCommitted(document)); - } + // must not be committed until exit modal dialog + waitTenSecondsForCommit(document); + assertFalse(getPsiDocumentManager().isCommitted(document)); + LaterInvocator.leaveModal(dialog); assertEquals(ModalityState.NON_MODAL, ApplicationManager.getApplication().getCurrentModalityState()); - start = System.currentTimeMillis(); - - // must committ - while (System.currentTimeMillis() - start < 10000 && !getPsiDocumentManager().isCommitted(document)) { - UIUtil.dispatchAllInvocationEvents(); - } - + // must commit + waitTenSecondsForCommit(document); assertTrue(getPsiDocumentManager().isCommitted(document)); - - // check that inside modal dialog commit is possible ApplicationManager.getApplication().runWriteAction(() -> { // commit thread is paused @@ -487,15 +510,64 @@ public class PsiDocumentManagerImplTest extends PlatformTestCase { }); assertNotSame(ModalityState.NON_MODAL, ApplicationManager.getApplication().getCurrentModalityState()); - // must committ - while (System.currentTimeMillis() - start < 10000 && !getPsiDocumentManager().isCommitted(document)) { - UIUtil.dispatchAllInvocationEvents(); - } + // must commit + waitTenSecondsForCommit(document); assertTrue(getPsiDocumentManager().isCommitted(document)); LaterInvocator.leaveModal(dialog); } - + + public void testChangeDocumentThenEnterModalDialogThenCallPerformWhenAllCommittedShouldFireWhileInsideModal() throws IOException { + VirtualFile vFile = getVirtualFile(createTempFile("a.txt", "abc")); + PsiFile psiFile = findFile(vFile); + final Document document = getDocument(psiFile); + + final DialogWrapper dialog = new DialogWrapper(getProject()) { + @Nullable + @Override + protected JComponent createCenterPanel() { + return null; + } + }; + + disposeOnTearDown(() -> dialog.close(DialogWrapper.OK_EXIT_CODE)); + ApplicationManager.getApplication().runWriteAction(() -> { + // commit thread is paused + document.setText("xx"); + + LaterInvocator.enterModal(dialog); + }); + assertNotSame(ModalityState.NON_MODAL, ApplicationManager.getApplication().getCurrentModalityState()); + + + // must not commit in background by default when modality changed + waitTenSecondsForCommit(document); + assertFalse(getPsiDocumentManager().isCommitted(document)); + + // but, when performWhenAllCommitted() in modal context called, should re-add documents into queue nevertheless + boolean[] calledPerformWhenAllCommitted = new boolean[1]; + getPsiDocumentManager().performWhenAllCommitted(() -> calledPerformWhenAllCommitted[0] = true); + + // must commit now + waitTenSecondsForCommit(document); + assertTrue(getPsiDocumentManager().isCommitted(document)); + assertTrue(calledPerformWhenAllCommitted[0]); + + LaterInvocator.leaveModal(dialog); + assertEquals(ModalityState.NON_MODAL, ApplicationManager.getApplication().getCurrentModalityState()); + } + + private void waitTenSecondsForCommit(Document document) { + waitForCommit(document, 10000); + } + + private void waitForCommit(Document document, int millis) { + long start = System.currentTimeMillis(); + while (System.currentTimeMillis() - start < millis && !getPsiDocumentManager().isCommitted(document)) { + UIUtil.dispatchAllInvocationEvents(); + } + } + public void testReparseDoesNotModifyDocument() throws Exception { VirtualFile file = createTempFile("txt", null, "1\n2\n3\n", Charset.forName("UTF-8")); file.putUserData(TrailingSpacesStripper.OVERRIDE_STRIP_TRAILING_SPACES_KEY, EditorSettingsExternalizable.STRIP_TRAILING_SPACES_CHANGED); diff --git a/platform/script-debugger/protocol/protocol-model-generator/src/FileSet.kt b/platform/script-debugger/protocol/protocol-model-generator/src/FileSet.kt index a9c296f3b5ff..a79acfde0671 100644 --- a/platform/script-debugger/protocol/protocol-model-generator/src/FileSet.kt +++ b/platform/script-debugger/protocol/protocol-model-generator/src/FileSet.kt @@ -37,18 +37,16 @@ class FileSet(private val rootDir: Path) { } fun deleteOtherFiles() { - unusedFiles.forEach(object : TObjectProcedure { - override fun execute(path: Path): Boolean { - if (Files.deleteIfExists(path)) { - val parent = path.parent - Files.newDirectoryStream(parent).use { stream -> - if (!stream.iterator().hasNext()) { - Files.delete(parent) - } + unusedFiles.forEach(TObjectProcedure { it -> + if (Files.deleteIfExists(it)) { + val parent = it.parent + Files.newDirectoryStream(parent).use { stream -> + if (!stream.iterator().hasNext()) { + Files.delete(parent) } } - return true } + true }) } } diff --git a/platform/testFramework/src/com/intellij/refactoring/AbstractInplaceIntroduceTest.java b/platform/testFramework/src/com/intellij/refactoring/AbstractInplaceIntroduceTest.java index deba4c6d9612..6b4a0a853c15 100644 --- a/platform/testFramework/src/com/intellij/refactoring/AbstractInplaceIntroduceTest.java +++ b/platform/testFramework/src/com/intellij/refactoring/AbstractInplaceIntroduceTest.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2011 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -79,9 +79,4 @@ public abstract class AbstractInplaceIntroduceTest extends LightPlatformCodeInsi } protected abstract AbstractInplaceIntroducer invokeRefactoring(); - - @Override - protected boolean isRunInWriteAction() { - return false; - } } diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java index 80d55e2251f8..1a420a0289ec 100644 --- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java +++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformCodeInsightTestCase.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -103,7 +103,7 @@ public abstract class LightPlatformCodeInsightTestCase extends LightPlatformTest } protected boolean isRunInWriteAction() { - return true; + return false; } /** diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java index 7aca4080915a..a145b752cf3e 100644 --- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java +++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestUtil.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -56,10 +56,7 @@ import com.intellij.util.ui.UIUtil; import junit.framework.AssertionFailedError; import org.jdom.Element; import org.jdom.JDOMException; -import org.jetbrains.annotations.NonNls; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.TestOnly; +import org.jetbrains.annotations.*; import org.junit.Assert; import javax.swing.*; @@ -76,9 +73,6 @@ import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.jar.JarFile; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - /** * @author yole */ @@ -245,7 +239,7 @@ public class PlatformTestUtil { public static void assertTreeEqual(JTree tree, String expected, boolean checkSelected) { String treeStringPresentation = print(tree, checkSelected); - assertEquals(expected, treeStringPresentation); + Assert.assertEquals(expected, treeStringPresentation); } public static void assertTreeEqualIgnoringNodesOrder(JTree tree, String expected, boolean checkSelected) { @@ -392,12 +386,12 @@ public class PlatformTestUtil { } public static void assertTreeStructureEquals(final AbstractTreeStructure treeStructure, final String expected) { - assertEquals(expected, print(treeStructure, treeStructure.getRootElement(), 0, null, -1, ' ', null).toString()); + Assert.assertEquals(expected, print(treeStructure, treeStructure.getRootElement(), 0, null, -1, ' ', null).toString()); } public static void invokeNamedAction(final String actionId) { final AnAction action = ActionManager.getInstance().getAction(actionId); - assertNotNull(action); + Assert.assertNotNull(action); final Presentation presentation = new Presentation(); @SuppressWarnings("deprecation") final DataContext context = DataManager.getInstance().getDataContext(); final AnActionEvent event = AnActionEvent.createFromAnAction(action, null, "", context); @@ -442,6 +436,7 @@ public class PlatformTestUtil { /** * example usage: startPerformanceTest("calculating pi",100, testRunnable).cpuBound().assertTiming(); */ + @Contract(pure = true) // to warn about not calling .assertTiming() in the end public static TestInfo startPerformanceTest(@NonNls @NotNull String message, int expectedMs, @NotNull ThrowableRunnable test) { return new TestInfo(test, expectedMs,message); } @@ -468,7 +463,7 @@ public class PlatformTestUtil { public static void assertPathsEqual(@Nullable String expected, @Nullable String actual) { if (expected != null) expected = FileUtil.toSystemIndependentName(expected); if (actual != null) actual = FileUtil.toSystemIndependentName(actual); - assertEquals(expected, actual); + Assert.assertEquals(expected, actual); } @NotNull @@ -498,7 +493,7 @@ public class PlatformTestUtil { private final String message; // to print on fail private boolean adjustForIO = true; // true if test uses IO, timings need to be re-calibrated according to this agent disk performance private boolean adjustForCPU = true; // true if test uses CPU, timings need to be re-calibrated according to this agent CPU speed - private boolean useLegacyScaling = false; + private boolean useLegacyScaling; private TestInfo(@NotNull ThrowableRunnable test, int expectedMs, String message) { this.test = test; @@ -507,16 +502,22 @@ public class PlatformTestUtil { this.message = message; } + @Contract(pure = true) // to warn about not calling .assertTiming() in the end public TestInfo setup(@NotNull ThrowableRunnable setup) { assert this.setup==null; this.setup = setup; return this; } + @Contract(pure = true) // to warn about not calling .assertTiming() in the end public TestInfo usesAllCPUCores() { assert adjustForCPU : "This test configured to be io-bound, it cannot use all cores"; usesAllCPUCores = true; return this; } + @Contract(pure = true) // to warn about not calling .assertTiming() in the end public TestInfo cpuBound() { adjustForIO = false; adjustForCPU = true; return this; } + @Contract(pure = true) // to warn about not calling .assertTiming() in the end public TestInfo ioBound() { adjustForIO = true; adjustForCPU = false; return this; } + @Contract(pure = true) // to warn about not calling .assertTiming() in the end public TestInfo attempts(int attempts) { this.attempts = attempts; return this; } /** * @deprecated Enables procedure for nonlinear scaling of results between different machines. This was historically enabled, but doesn't * seem to be meaningful, and is known to make results worse in some cases. Consider migration off this setting, recalibrating * expected execution time accordingly. */ + @Contract(pure = true) // to warn about not calling .assertTiming() in the end public TestInfo useLegacyScaling() { useLegacyScaling = true; return this; } public void assertTiming() { @@ -693,7 +694,7 @@ public class PlatformTestUtil { Set keySetAfter = mapAfter.keySet(); Set keySetBefore = mapBefore.keySet(); - assertEquals(dirAfter.getPath(), keySetAfter, keySetBefore); + Assert.assertEquals(dirAfter.getPath(), keySetAfter, keySetBefore); for (String name : keySetAfter) { VirtualFile fileAfter = mapAfter.get(name); @@ -720,7 +721,7 @@ public class PlatformTestUtil { } } - assertEquals(sortAndJoin(vfsPaths), sortAndJoin(ioPaths)); + Assert.assertEquals(sortAndJoin(vfsPaths), sortAndJoin(ioPaths)); } private static String sortAndJoin(List strings) { @@ -757,7 +758,7 @@ public class PlatformTestUtil { : LoadTextUtil.getTextByBinaryPresentation(fileAfter.contentsToByteArray(false), fileAfter).toString(); if (textA != null && textB != null) { - assertEquals(fileAfter.getPath(), textA, textB); + Assert.assertEquals(fileAfter.getPath(), textA, textB); } else { Assert.assertArrayEquals(fileAfter.getPath(), fileAfter.contentsToByteArray(), fileBefore.contentsToByteArray()); @@ -787,9 +788,9 @@ public class PlatformTestUtil { } final VirtualFile dirAfter = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory1); - assertNotNull(tempDirectory1.toString(), dirAfter); + Assert.assertNotNull(tempDirectory1.toString(), dirAfter); final VirtualFile dirBefore = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempDirectory2); - assertNotNull(tempDirectory2.toString(), dirBefore); + Assert.assertNotNull(tempDirectory2.toString(), dirBefore); ApplicationManager.getApplication().runWriteAction(new Runnable() { @Override public void run() { @@ -802,7 +803,7 @@ public class PlatformTestUtil { public static void assertElementsEqual(final Element expected, final Element actual) throws IOException { if (!JDOMUtil.areElementsEqual(expected, actual)) { - assertEquals(printElement(expected), printElement(actual)); + Assert.assertEquals(printElement(expected), printElement(actual)); } } @@ -810,10 +811,7 @@ public class PlatformTestUtil { try { assertElementsEqual(JDOMUtil.loadDocument(expected).getRootElement(), actual); } - catch (IOException e) { - throw new AssertionError(e); - } - catch (JDOMException e) { + catch (IOException | JDOMException e) { throw new AssertionError(e); } } @@ -850,7 +848,7 @@ public class PlatformTestUtil { @NotNull public static T notNull(@Nullable T t) { - assertNotNull(t); + Assert.assertNotNull(t); return t; } @@ -913,7 +911,7 @@ public class PlatformTestUtil { public static void assertSuccessful(@NotNull GeneralCommandLine command) { try { ProcessOutput output = ExecUtil.execAndGetOutput(command.withRedirectErrorStream(true)); - assertEquals(output.getStdout(), 0, output.getExitCode()); + Assert.assertEquals(output.getStdout(), 0, output.getExitCode()); } catch (ExecutionException e) { throw new RuntimeException(e); diff --git a/platform/testFramework/src/com/intellij/testFramework/TemporaryDirectory.kt b/platform/testFramework/src/com/intellij/testFramework/TemporaryDirectory.kt index 7db92ae40f8a..c653d106a51c 100644 --- a/platform/testFramework/src/com/intellij/testFramework/TemporaryDirectory.kt +++ b/platform/testFramework/src/com/intellij/testFramework/TemporaryDirectory.kt @@ -25,7 +25,6 @@ import com.intellij.util.lang.CompoundRuntimeException import org.junit.rules.ExternalResource import org.junit.runner.Description import org.junit.runners.model.Statement -import java.io.File import java.io.IOException import java.nio.file.Path import java.nio.file.Paths @@ -55,12 +54,7 @@ class TemporaryDirectory : ExternalResource() { paths.clear() } - /** - * Directory is not created. - */ - fun newDirectory(directoryName: String? = null): File = generatePath(directoryName).toFile() - - fun newPath(directoryName: String? = null, refreshVfs: Boolean = true): Path { + fun newPath(directoryName: String? = null, refreshVfs: Boolean = false): Path { val path = generatePath(directoryName) if (refreshVfs) { path.refreshVfs() diff --git a/platform/testFramework/src/com/intellij/testFramework/ThreadTracker.java b/platform/testFramework/src/com/intellij/testFramework/ThreadTracker.java index cd9eb1753fa1..b2844e603a32 100644 --- a/platform/testFramework/src/com/intellij/testFramework/ThreadTracker.java +++ b/platform/testFramework/src/com/intellij/testFramework/ThreadTracker.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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,7 +15,6 @@ */ package com.intellij.testFramework; -import com.intellij.execution.process.BaseOSProcessHandler; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.ProjectManager; @@ -116,7 +115,6 @@ public class ThreadTracker { @TestOnly public void checkLeak() throws AssertionError { - BaseOSProcessHandler.awaitQuiescence(100, TimeUnit.SECONDS); NettyUtil.awaitQuiescenceOfGlobalEventExecutor(100, TimeUnit.SECONDS); try { if (myDefaultProjectInitialized != ((ProjectManagerImpl)ProjectManager.getInstance()).isDefaultProjectInitialized()) return; diff --git a/platform/util/src/com/intellij/Patches.java b/platform/util/src/com/intellij/Patches.java index 3faee9ba41d5..5d8321543b11 100644 --- a/platform/util/src/com/intellij/Patches.java +++ b/platform/util/src/com/intellij/Patches.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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. @@ -75,14 +75,7 @@ public class Patches { * https://bugs.openjdk.java.net/browse/JDK-8020443 */ public static final boolean SUN_BUG_ID_8020443 = - SystemInfo.isXWindow && SystemInfo.isJavaVersionAtLeast("1.7") && !SystemInfo.isJavaVersionAtLeast("1.9"); - - /** - * XToolkit.getScreenInsets() may be very slow. - * See https://bugs.openjdk.java.net/browse/JDK-8004103. - */ - public static final boolean JDK_BUG_ID_8004103 = - SystemInfo.isXWindow && !GraphicsEnvironment.isHeadless() && SystemInfo.isJavaVersionAtLeast("1.7"); + SystemInfo.isXWindow && SystemInfo.isJavaVersionAtLeast("1.7") && !SystemInfo.isJavaVersionAtLeast("1.8.0_60"); /** * On some WMs modal dialogs may show behind full screen window. @@ -110,13 +103,13 @@ public class Patches { * Marker field to find all usages of the reflective access to JDK 7-specific methods * which need to be changed when migrated to JDK 7 */ - public static final boolean USE_REFLECTION_TO_ACCESS_JDK7 = true; + public static final boolean USE_REFLECTION_TO_ACCESS_JDK7 = Boolean.valueOf(true); /** * Marker field to find all usages of the reflective access to JDK 7-specific methods * which need to be changed when migrated to JDK 8 */ - public static final boolean USE_REFLECTION_TO_ACCESS_JDK8 = true; + public static final boolean USE_REFLECTION_TO_ACCESS_JDK8 = Boolean.valueOf(true); /** * AtomicIntegerFieldUpdater does not work when SecurityManager is installed @@ -147,4 +140,12 @@ public class Patches { * On Mac OS font ligatures are not supported for natively loaded fonts, font needs to be loaded explicitly by JDK. */ public static final boolean JDK_BUG_ID_7162125 = SystemInfo.isMac && !SystemInfo.isJavaVersionAtLeast("1.9"); + + /** + * XToolkit.getScreenInsets() may be very slow. + * See https://bugs.openjdk.java.net/browse/JDK-8004103. + */ + public static boolean isJdkBugId8004103() { + return SystemInfo.isXWindow && !GraphicsEnvironment.isHeadless() && SystemInfo.isJavaVersionAtLeast("1.7"); + } } diff --git a/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java b/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java index 0c0f421e09d3..5b54be54fef9 100644 --- a/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java +++ b/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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,14 +21,13 @@ import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.registry.Registry; import com.intellij.openapi.util.text.StringUtil; -import com.intellij.util.ConcurrencyUtil; import com.intellij.util.Consumer; +import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.io.BaseDataReader; import com.intellij.util.io.BaseInputStreamReader; import com.intellij.util.io.BaseOutputReader; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jetbrains.annotations.TestOnly; import java.io.IOException; import java.io.InputStream; @@ -36,11 +35,6 @@ import java.io.OutputStream; import java.io.Reader; import java.nio.charset.Charset; import java.util.concurrent.Future; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import static com.intellij.util.io.BaseDataReader.AdaptiveSleepingPolicy; public class BaseOSProcessHandler extends ProcessHandler implements TaskExecutor { private static final Logger LOG = Logger.getInstance(BaseOSProcessHandler.class); @@ -72,7 +66,7 @@ public class BaseOSProcessHandler extends ProcessHandler implements TaskExecutor */ @NotNull protected Future executeOnPooledThread(@NotNull Runnable task) { - return ExecutorServiceHolder.ourThreadExecutorsService.submit(task); + return AppExecutorUtil.getAppExecutorService().submit(task); } @Override @@ -148,7 +142,7 @@ public class BaseOSProcessHandler extends ProcessHandler implements TaskExecutor @NotNull private BaseDataReader.SleepingPolicy getPolicy() { if (useNonBlockingRead()) { - return useAdaptiveSleepingPolicyWhenReadingOutput() ? new AdaptiveSleepingPolicy() : BaseDataReader.SleepingPolicy.SIMPLE; + return useAdaptiveSleepingPolicyWhenReadingOutput() ? new BaseDataReader.AdaptiveSleepingPolicy() : BaseDataReader.SleepingPolicy.SIMPLE; } else { //use blocking read policy @@ -255,28 +249,14 @@ public class BaseOSProcessHandler extends ProcessHandler implements TaskExecutor } public static class ExecutorServiceHolder { - private static final ThreadPoolExecutor ourThreadExecutorsService = - new ThreadPoolExecutor(0, Integer.MAX_VALUE, 1, TimeUnit.SECONDS, new SynchronousQueue(), - ConcurrencyUtil.newNamedThreadFactory("OSProcessHandler pooled thread")); - - /** @deprecated use {@link BaseOSProcessHandler#submit(Runnable)} instead (to be removed in IDEA 16) */ + /** @deprecated use {@link BaseOSProcessHandler#executeTask(Runnable)} instead (to be removed in IDEA 16) */ @Deprecated public static Future submit(@NotNull Runnable task) { - return BaseOSProcessHandler.submit(task); + LOG.warn("Deprecated method. Please use com.intellij.execution.process.BaseOSProcessHandler.executeTask() instead", new Throwable()); + return AppExecutorUtil.getAppExecutorService().submit(task); } } - @NotNull - public static Future submit(@NotNull Runnable task) { - return ExecutorServiceHolder.ourThreadExecutorsService.submit(task); - } - - @TestOnly - public static void awaitQuiescence(long timeout, @NotNull TimeUnit unit) { - ThreadPoolExecutor executor = ExecutorServiceHolder.ourThreadExecutorsService; - ConcurrencyUtil.awaitQuiescence(executor, timeout, unit); - } - private class SimpleOutputReader extends BaseOutputReader { private final Key myProcessOutputType; @@ -302,4 +282,16 @@ public class BaseOSProcessHandler extends ProcessHandler implements TaskExecutor public String toString() { return myCommandLine; } + + @Override + public boolean waitFor() { + boolean result = super.waitFor(); + try { + myWaitFor.waitFor(); + } + catch (InterruptedException e) { + throw new RuntimeException(e); + } + return result; + } } \ No newline at end of file diff --git a/platform/util/src/com/intellij/execution/process/ProcessWaitFor.java b/platform/util/src/com/intellij/execution/process/ProcessWaitFor.java index 623424111054..45388765f22e 100644 --- a/platform/util/src/com/intellij/execution/process/ProcessWaitFor.java +++ b/platform/util/src/com/intellij/execution/process/ProcessWaitFor.java @@ -21,9 +21,7 @@ import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.Consumer; import org.jetbrains.annotations.NotNull; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.Future; +import java.util.concurrent.*; public class ProcessWaitFor { private static final Logger LOG = Logger.getInstance("#com.intellij.execution.process.ProcessWaitFor"); @@ -79,4 +77,15 @@ public class ProcessWaitFor { public void setTerminationCallback(@NotNull Consumer r) { myTerminationCallback.offer(r); } + + public void waitFor() throws InterruptedException { + try { + myWaitForThreadFuture.get(); + } + catch (ExecutionException e) { + LOG.error(e); + } + catch (CancellationException ignored) { + } + } } \ No newline at end of file diff --git a/platform/util/src/com/intellij/icons/AllIcons.java b/platform/util/src/com/intellij/icons/AllIcons.java index 85956b1c1936..d071d0f7244c 100644 --- a/platform/util/src/com/intellij/icons/AllIcons.java +++ b/platform/util/src/com/intellij/icons/AllIcons.java @@ -558,7 +558,7 @@ public class AllIcons { public static final Icon Colors = IconLoader.getIcon("/gutter/colors.png"); // 12x12 public static final Icon ExtAnnotation = IconLoader.getIcon("/gutter/extAnnotation.png"); // 12x12 public static final Icon ImplementedMethod = IconLoader.getIcon("/gutter/implementedMethod.png"); // 12x12 - public static final Icon ImplementingFunctional = IconLoader.getIcon("/gutter/implementingFunctional.png"); // 12x12 + public static final Icon ImplementingFunctionalInterface = IconLoader.getIcon("/gutter/implementingFunctionalInterface.png"); // 12x12 public static final Icon ImplementingMethod = IconLoader.getIcon("/gutter/implementingMethod.png"); // 12x12 public static final Icon OverridenMethod = IconLoader.getIcon("/gutter/overridenMethod.png"); // 12x12 public static final Icon OverridingMethod = IconLoader.getIcon("/gutter/overridingMethod.png"); // 12x12 diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/annotate/AnnotationsPreloader.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/annotate/AnnotationsPreloader.java index bbc61acbd545..ffaee96c347a 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/annotate/AnnotationsPreloader.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/annotate/AnnotationsPreloader.java @@ -22,9 +22,7 @@ import com.intellij.openapi.fileEditor.FileEditorManagerEvent; import com.intellij.openapi.fileEditor.FileEditorManagerListener; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.registry.Registry; -import com.intellij.openapi.vcs.AbstractVcs; -import com.intellij.openapi.vcs.ProjectLevelVcsManager; -import com.intellij.openapi.vcs.VcsException; +import com.intellij.openapi.vcs.*; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.ui.update.MergingUpdateQueue; import com.intellij.util.ui.update.Update; @@ -59,6 +57,13 @@ public class AnnotationsPreloader { } private void schedulePreloading(@NotNull final VirtualFile file) { + if (myProject.isDisposed() || file.getFileType().isBinary()) return; + + FileStatus fileStatus = FileStatusManager.getInstance(myProject).getStatus(file); + if (fileStatus == FileStatus.UNKNOWN || fileStatus == FileStatus.ADDED || fileStatus == FileStatus.IGNORED) { + return; + } + AbstractVcs vcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(file); if (vcs == null || !(vcs.getAnnotationProvider() instanceof VcsCacheableAnnotationProvider)) return; diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/UnversionedViewDialog.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/UnversionedViewDialog.java index a800e70aeaed..59c1963ff729 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/UnversionedViewDialog.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/UnversionedViewDialog.java @@ -152,8 +152,7 @@ public class UnversionedViewDialog extends DialogWrapper { } // special shortcut for deleting a file - AnAction deleteAction = ActionManager.getInstance().getAction("ChangesView.DeleteUnversioned.From.Dialog"); - deleteAction.registerCustomShortcutSet(CommonShortcuts.getDelete(), myView); + EmptyAction.registerWithShortcutSet("ChangesView.DeleteUnversioned.From.Dialog", CommonShortcuts.getDelete(), myView); } private void refreshViewAfterActionPerformed(@NotNull final ActionGroup opActionGroup) { diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/MultipleChangeListBrowser.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/MultipleChangeListBrowser.java index ec2f90bd78e1..89696425a51b 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/MultipleChangeListBrowser.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/MultipleChangeListBrowser.java @@ -217,10 +217,8 @@ public class MultipleChangeListBrowser extends ChangesBrowser { protected void buildToolBar(final DefaultActionGroup toolBarGroup) { super.buildToolBar(toolBarGroup); - ActionManager actionManager = ActionManager.getInstance(); - final AnAction moveAction = actionManager.getAction(IdeActions.MOVE_TO_ANOTHER_CHANGE_LIST); - moveAction.registerCustomShortcutSet(CommonShortcuts.getMove(), myViewer); - toolBarGroup.add(moveAction); + EmptyAction.registerWithShortcutSet(IdeActions.MOVE_TO_ANOTHER_CHANGE_LIST, CommonShortcuts.getMove(), myViewer); + toolBarGroup.add(ActionManager.getInstance().getAction(IdeActions.MOVE_TO_ANOTHER_CHANGE_LIST)); } @Override diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java index d40546df0d85..6d33c46ab480 100644 --- a/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java +++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/ex/LineStatusTracker.java @@ -156,6 +156,10 @@ public class LineStatusTracker { for (final Range range : myRanges) { createHighlighter(range); } + + if (myRanges.isEmpty()) { + markFileUnchanged(); + } } catch (FilesTooBigForDiffException e) { installAnathema(); diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/InspectionGadgetsBundle.properties b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/InspectionGadgetsBundle.properties index 2fec25829262..f765cb5ed21b 100644 --- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/InspectionGadgetsBundle.properties +++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/InspectionGadgetsBundle.properties @@ -1148,7 +1148,7 @@ standard.variable.names.ignore.override.option=Ignore for parameter names identi static.variable.naming.convention.mutable.option=Check 'static final' fields with a mutable type boolean.method.name.must.start.with.question.table.column.name=Boolean method name prefix conditional.expression.with.identical.branches.collapse.quickfix=Collapse conditional expression -conditional.expression.with.identical.branches.collapse.quickfix.family=\u0421onditional expression can be simplified +conditional.expression.with.identical.branches.collapse.quickfix.family=Conditional expression can be simplified confusing.else.unwrap.quickfix=Remove redundant 'else' constant.conditional.expression.problem.descriptor=#ref can be simplified to ''{0}'' #loc constant.conditional.expression.simplify.quickfix=Simplify diff --git a/plugins/InspectionGadgets/src/com/intellij/codeInspection/TrivialFunctionalExpressionUsageInspection.java b/plugins/InspectionGadgets/src/com/intellij/codeInspection/TrivialFunctionalExpressionUsageInspection.java index c75e1a464b8a..65b52c1f7fa5 100644 --- a/plugins/InspectionGadgets/src/com/intellij/codeInspection/TrivialFunctionalExpressionUsageInspection.java +++ b/plugins/InspectionGadgets/src/com/intellij/codeInspection/TrivialFunctionalExpressionUsageInspection.java @@ -15,6 +15,7 @@ */ package com.intellij.codeInspection; +import com.intellij.codeInsight.FileModificationService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; import com.intellij.psi.*; @@ -155,7 +156,9 @@ public class TrivialFunctionalExpressionUsageInspection extends BaseJavaBatchLoc @Override public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { - final PsiMethodCallExpression callExpression = PsiTreeUtil.getParentOfType(descriptor.getPsiElement(), PsiMethodCallExpression.class); + final PsiElement psiElement = descriptor.getPsiElement(); + if (!FileModificationService.getInstance().preparePsiElementForWrite(psiElement)) return; + final PsiMethodCallExpression callExpression = PsiTreeUtil.getParentOfType(psiElement, PsiMethodCallExpression.class); if (callExpression != null) { final PsiExpression qualifierExpression = PsiUtil.skipParenthesizedExprDown(callExpression.getMethodExpression().getQualifierExpression()); if (qualifierExpression instanceof PsiTypeCastExpression) { diff --git a/plugins/devkit/src/inspections/internal/HighlightVisitorInternalInspection.java b/plugins/devkit/src/inspections/internal/HighlightVisitorInternalInspection.java index 4af68a9905ea..57616bdb5fae 100644 --- a/plugins/devkit/src/inspections/internal/HighlightVisitorInternalInspection.java +++ b/plugins/devkit/src/inspections/internal/HighlightVisitorInternalInspection.java @@ -22,11 +22,16 @@ import com.intellij.codeInsight.daemon.impl.analysis.HighlightInfoHolder; import com.intellij.codeInsight.daemon.impl.analysis.HighlightVisitorImpl; import com.intellij.codeInspection.BaseJavaBatchLocalInspectionTool; import com.intellij.codeInspection.ProblemsHolder; +import com.intellij.compiler.CompilerConfiguration; import com.intellij.lang.annotation.HighlightSeverity; import com.intellij.lang.injection.InjectedLanguageManager; import com.intellij.openapi.diagnostic.Logger; +import com.intellij.openapi.fileTypes.StdFileTypes; +import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil; +import com.intellij.psi.util.PsiUtil; +import com.intellij.psi.util.PsiUtilCore; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @@ -69,6 +74,12 @@ public class HighlightVisitorInternalInspection extends BaseJavaBatchLocalInspec if (InjectedLanguageManager.getInstance(file.getProject()).isInjectedFragment(file)) { return PsiElementVisitor.EMPTY_VISITOR; } + final VirtualFile virtualFile = PsiUtilCore.getVirtualFile(file); + if (virtualFile == null || + virtualFile.getFileType() != StdFileTypes.JAVA || + CompilerConfiguration.getInstance(holder.getProject()).isExcludedFromCompilation(virtualFile)) { + return PsiElementVisitor.EMPTY_VISITOR; + } return new HighlightVisitorImpl(JavaPsiFacade.getInstance(holder.getProject()).getResolveHelper()) { { prepareToRunAsInspection(new HighlightInfoHolder(file) { diff --git a/plugins/devkit/src/run/JUnitDevKitPatcher.java b/plugins/devkit/src/run/JUnitDevKitPatcher.java index f391b81a9bff..40b090e20a84 100644 --- a/plugins/devkit/src/run/JUnitDevKitPatcher.java +++ b/plugins/devkit/src/run/JUnitDevKitPatcher.java @@ -47,7 +47,7 @@ public class JUnitDevKitPatcher extends JUnitPatcher { @Override public void patchJavaParameters(@Nullable final Module module, JavaParameters javaParameters) { - if (module != null && PsiUtil.isIdeaProject(module.getProject()) && !javaParameters.getVMParametersList().hasParameter(SYSTEM_CL_PROPERTY)) { + if (module != null && PsiUtil.isIdeaProject(module.getProject()) && !javaParameters.getVMParametersList().hasProperty(SYSTEM_CL_PROPERTY)) { final JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(module.getProject()); final String qualifiedName = UrlClassLoader.class.getName(); final PsiClass urlLoaderClass = ApplicationManager.getApplication().runReadAction(new Computable() { diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRerunFailedTestsAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRerunFailedTestsAction.java new file mode 100644 index 000000000000..d1c894d73b04 --- /dev/null +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/action/GradleRerunFailedTestsAction.java @@ -0,0 +1,118 @@ +/* + * Copyright 2000-2016 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.action; + +import com.intellij.execution.ExecutionException; +import com.intellij.execution.Executor; +import com.intellij.execution.actions.JavaRerunFailedTestsAction; +import com.intellij.execution.configurations.RunProfileState; +import com.intellij.execution.runners.ExecutionEnvironment; +import com.intellij.execution.testframework.AbstractTestProxy; +import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration; +import com.intellij.openapi.module.Module; +import com.intellij.openapi.project.Project; +import com.intellij.openapi.roots.ProjectFileIndex; +import com.intellij.openapi.util.text.StringUtil; +import com.intellij.psi.JavaPsiFacade; +import com.intellij.psi.PsiClass; +import com.intellij.psi.PsiFile; +import com.intellij.psi.search.GlobalSearchScope; +import com.intellij.util.containers.ContainerUtil; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.jetbrains.plugins.gradle.execution.test.runner.GradleSMTestProxy; +import org.jetbrains.plugins.gradle.execution.test.runner.GradleTestRunConfigurationProducer; +import org.jetbrains.plugins.gradle.execution.test.runner.GradleTestsExecutionConsole; +import org.jetbrains.plugins.gradle.execution.test.runner.TestMethodGradleConfigurationProducer; + +import java.util.List; +import java.util.Set; + +/** + * @author Vladislav.Soroka + * @since 2/10/2016 + */ +public class GradleRerunFailedTestsAction extends JavaRerunFailedTestsAction { + public GradleRerunFailedTestsAction(GradleTestsExecutionConsole consoleView) { + super(consoleView.getConsole(), consoleView.getProperties()); + } + + @Nullable + @Override + protected MyRunProfile getRunProfile(@NotNull ExecutionEnvironment environment) { + ExternalSystemRunConfiguration configuration = (ExternalSystemRunConfiguration)myConsoleProperties.getConfiguration(); + final List failedTests = getFailedTests(configuration.getProject()); + return new MyRunProfile(configuration) { + @NotNull + @Override + public Module[] getModules() { + return new Module[0]; + } + + @Nullable + @Override + public RunProfileState getState(@NotNull Executor executor, @NotNull ExecutionEnvironment environment) + throws ExecutionException { + ExternalSystemRunConfiguration runProfile = ((ExternalSystemRunConfiguration)getPeer()).clone(); + Project project = runProfile.getProject(); + + Set scriptParameters = ContainerUtil.newLinkedHashSet(); + Set tasksToRun = ContainerUtil.newLinkedHashSet(); + boolean useResolvedTasks = true; + for (AbstractTestProxy test : failedTests) { + if (test instanceof GradleSMTestProxy) { + String testName = test.getName(); + String className = ((GradleSMTestProxy)test).getClassName(); + scriptParameters.add(TestMethodGradleConfigurationProducer.createTestFilter(className, testName)); + + if(!useResolvedTasks) continue; + + if(className == null) { + useResolvedTasks = false; + continue; + } + + final PsiClass psiClass = + JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.projectScope(project)); + + if (psiClass == null) { + useResolvedTasks = false; + continue; + } + final PsiFile psiFile = psiClass.getContainingFile(); + if (psiFile == null) { + useResolvedTasks = false; + continue; + } + + final Module moduleForFile = ProjectFileIndex.SERVICE.getInstance(project).getModuleForFile(psiFile.getVirtualFile()); + if(moduleForFile == null){ + useResolvedTasks = false; + continue; + } + ContainerUtil.addAllNotNull(tasksToRun, GradleTestRunConfigurationProducer.getTasksToRun(moduleForFile)); + } + } + runProfile.getSettings().setScriptParameters(StringUtil.join(scriptParameters, " ")); + + if(useResolvedTasks && !tasksToRun.isEmpty()) { + runProfile.getSettings().setTaskNames(ContainerUtil.newArrayList(tasksToRun)); + } + return runProfile.getState(executor, environment); + } + }; + } +} diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleSMTestProxy.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleSMTestProxy.java index 8f37b19729d4..978610068c01 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleSMTestProxy.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleSMTestProxy.java @@ -88,6 +88,11 @@ public class GradleSMTestProxy extends SMTestProxy { myParentId = parentId; } + @Nullable + public String getClassName() { + return myClassName; + } + private void setStacktraceIfNotSet(@Nullable String stacktrace) { if (myStacktrace == null) myStacktrace = stacktrace; } diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleTestRunConfigurationProducer.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleTestRunConfigurationProducer.java index d9158c602218..0afa3e077218 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleTestRunConfigurationProducer.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleTestRunConfigurationProducer.java @@ -130,7 +130,7 @@ public abstract class GradleTestRunConfigurationProducer extends RunConfiguratio } @NotNull - static List getTasksToRun(@NotNull Module module) { + public static List getTasksToRun(@NotNull Module module) { for (GradleTestTasksProvider provider : GradleTestTasksProvider.EP_NAME.getExtensions()) { final List tasks = provider.getTasks(module); if(!ContainerUtil.isEmpty(tasks)) { diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleTestsExecutionConsoleManager.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleTestsExecutionConsoleManager.java index 234e43848250..267cc65790ac 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleTestsExecutionConsoleManager.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/execution/test/runner/GradleTestsExecutionConsoleManager.java @@ -17,8 +17,10 @@ package org.jetbrains.plugins.gradle.execution.test.runner; import com.intellij.execution.ExecutionException; import com.intellij.execution.Executor; +import com.intellij.execution.actions.JavaRerunFailedTestsAction; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.runners.ExecutionEnvironment; +import com.intellij.execution.testframework.TestFrameworkRunningModel; import com.intellij.execution.testframework.TestTreeView; import com.intellij.execution.testframework.sm.SMTestRunnerConnectionUtil; import com.intellij.execution.testframework.sm.runner.SMTestProxy; @@ -40,12 +42,14 @@ import com.intellij.openapi.externalSystem.service.internal.ExternalSystemExecut import com.intellij.openapi.externalSystem.util.ExternalSystemUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Condition; +import com.intellij.openapi.util.Getter; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.SimpleTextAttributes; import com.intellij.util.ObjectUtils; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; +import org.jetbrains.plugins.gradle.action.GradleRerunFailedTestsAction; import org.jetbrains.plugins.gradle.execution.test.runner.events.*; import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil; import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames; @@ -207,7 +211,15 @@ public class GradleTestsExecutionConsoleManager } @Override - public AnAction[] getRestartActions() { - return new AnAction[0]; + public AnAction[] getRestartActions(@NotNull final GradleTestsExecutionConsole consoleView) { + JavaRerunFailedTestsAction rerunFailedTestsAction = + new GradleRerunFailedTestsAction(consoleView); + rerunFailedTestsAction.setModelProvider(new Getter() { + @Override + public TestFrameworkRunningModel get() { + return consoleView.getResultsViewer(); + } + }); + return new AnAction[]{rerunFailedTestsAction}; } } diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java index 2a7f6b2eb6c2..4d048250f202 100644 --- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java +++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java @@ -234,8 +234,8 @@ public class BaseGradleProjectResolverExtension implements GradleProjectResolver } @NotNull - public String getInternalModuleName(@NotNull IdeaModule gradleModule, @NotNull String sourceSetName) { - return gradleModule.getName() + "_" + sourceSetName; + private static String getInternalModuleName(@NotNull IdeaModule gradleModule, @NotNull String sourceSetName) { + return PathUtilRt.suggestFileName(gradleModule.getName() + "_" + sourceSetName, true, false); } @Override diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleDependenciesImportingTest.java b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleDependenciesImportingTest.java index b310e13801f0..b44bfe8f11fd 100644 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleDependenciesImportingTest.java +++ b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleDependenciesImportingTest.java @@ -269,11 +269,11 @@ public class GradleDependenciesImportingTest extends GradleImportingTestCase { "}\n" ); - assertModules("project", "project1", "project1_main", "project1_test", "project2", "project2_main", "project2_test", "project-tests", "project_tests_main", "project_tests_test"); + assertModules("project", "project1", "project1_main", "project1_test", "project2", "project2_main", "project2_test", "project-tests", "project-tests_main", "project-tests_test"); - assertModuleModuleDepScope("project_tests_main", "project1_main", DependencyScope.COMPILE); - assertModuleModuleDepScope("project_tests_main", "project2_main", DependencyScope.RUNTIME); - assertModuleLibDepScope("project_tests_main", "Gradle: org.apache.geronimo.specs:geronimo-jms_1.1_spec:1.0", DependencyScope.COMPILE); - assertModuleLibDepScope("project_tests_main", "Gradle: org.apache.geronimo.specs:geronimo-jms_1.1_spec:1.1.1", DependencyScope.RUNTIME); + assertModuleModuleDepScope("project-tests_main", "project1_main", DependencyScope.COMPILE); + assertModuleModuleDepScope("project-tests_main", "project2_main", DependencyScope.RUNTIME); + assertModuleLibDepScope("project-tests_main", "Gradle: org.apache.geronimo.specs:geronimo-jms_1.1_spec:1.0", DependencyScope.COMPILE); + assertModuleLibDepScope("project-tests_main", "Gradle: org.apache.geronimo.specs:geronimo-jms_1.1_spec:1.1.1", DependencyScope.RUNTIME); } } diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java index c28a1745846c..6fb88e2b4e74 100644 --- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java +++ b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/importing/GradleMiscImportingTest.java @@ -59,6 +59,20 @@ public class GradleMiscImportingTest extends GradleImportingTestCase { assertSame(productionModule, testModuleProperties.getProductionModule()); } + @Test + public void testTestModulePropertiesForModuleWithHyphenInName() throws Exception { + createSettingsFile("rootProject.name='my-project'"); + importProject( + "apply plugin: 'java'" + ); + + assertModules("my-project", "my-project_main", "my-project_test"); + + final Module testModule = getModule("my-project_test"); + TestModuleProperties testModuleProperties = TestModuleProperties.getInstance(testModule); + assertEquals("my-project_main", testModuleProperties.getProductionModuleName()); + } + @Test public void testInheritProjectJdkForModules() throws Exception { importProject( diff --git a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/GroovyChangeUtilSupport.java b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/GroovyChangeUtilSupport.java index 000461c94ffa..4f27f4d9f11b 100644 --- a/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/GroovyChangeUtilSupport.java +++ b/plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/GroovyChangeUtilSupport.java @@ -73,7 +73,7 @@ public class GroovyChangeUtilSupport implements TreeCopyHandler { if (original.getElementType() == GroovyElementTypes.REFERENCE_ELEMENT || original.getElementType() == GroovyElementTypes.REFERENCE_EXPRESSION) { PsiElement psi = original.getPsi(); - if (!PsiUtil.isThisOrSuperRef(psi)) { + if (!PsiUtil.isThisOrSuperRef(psi) && psi.getProject().isInitialized()) { final GroovyResolveResult result = ((GrReferenceElement)psi).advancedResolve(); if (result != null) { final PsiElement target = result.getElement(); diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/inspections/JavaFxUnresolvedFxIdReferenceInspection.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/inspections/JavaFxUnresolvedFxIdReferenceInspection.java index 13f113d540b6..72f115b4a41f 100644 --- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/inspections/JavaFxUnresolvedFxIdReferenceInspection.java +++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/codeInsight/inspections/JavaFxUnresolvedFxIdReferenceInspection.java @@ -36,6 +36,7 @@ import com.intellij.util.VisibilityUtil; import com.intellij.xml.XmlElementDescriptor; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.javaFX.fxml.FxmlConstants; +import org.jetbrains.plugins.javaFX.fxml.JavaFxCommonClassNames; import org.jetbrains.plugins.javaFX.fxml.JavaFxFileTypeFactory; import org.jetbrains.plugins.javaFX.fxml.JavaFxPsiUtil; import org.jetbrains.plugins.javaFX.fxml.descriptors.JavaFxClassBackedElementDescriptor; @@ -146,7 +147,11 @@ public class JavaFxUnresolvedFxIdReferenceInspection extends XmlSuppressableInsp } final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); PsiField field = factory.createField(reference.getCanonicalText(), PsiType.INT); - VisibilityUtil.setVisibility(field.getModifierList(), PsiModifier.PUBLIC); + PsiModifierList modifierList = field.getModifierList(); + if (modifierList != null) { + VisibilityUtil.setVisibility(modifierList, PsiModifier.PRIVATE); + modifierList.addAnnotation(JavaFxCommonClassNames.JAVAFX_FXML_ANNOTATION); + } field = CreateFieldFromUsageHelper.insertField(targetClass, field, psiElement); diff --git a/plugins/javaFX/testData/inspections/unresolvedFxId/Controller_after.java b/plugins/javaFX/testData/inspections/unresolvedFxId/Controller_after.java index 17cf32880e93..2df78c0a6567 100644 --- a/plugins/javaFX/testData/inspections/unresolvedFxId/Controller_after.java +++ b/plugins/javaFX/testData/inspections/unresolvedFxId/Controller_after.java @@ -1,5 +1,7 @@ +import javafx.fxml.FXML; import javafx.scene.control.TextField; public class Controller { - public TextField unknown; + @FXML + private TextField unknown; } \ No newline at end of file diff --git a/plugins/javaFX/testData/inspections/unresolvedFxId/MyController_after.java b/plugins/javaFX/testData/inspections/unresolvedFxId/MyController_after.java index 06643d1b4382..273aef0b2e6f 100644 --- a/plugins/javaFX/testData/inspections/unresolvedFxId/MyController_after.java +++ b/plugins/javaFX/testData/inspections/unresolvedFxId/MyController_after.java @@ -1,5 +1,7 @@ +import javafx.fxml.FXML; import javafx.scene.control.Button; public class MyController { - public Button unknown; + @FXML + private Button unknown; } \ No newline at end of file diff --git a/plugins/javaFX/testData/quickfix/CreateField_after.java b/plugins/javaFX/testData/quickfix/CreateField_after.java index a247a27be877..ae28760ba2d8 100644 --- a/plugins/javaFX/testData/quickfix/CreateField_after.java +++ b/plugins/javaFX/testData/quickfix/CreateField_after.java @@ -1,5 +1,7 @@ +import javafx.fxml.FXML; import javafx.scene.control.Button; public class CreateControllerMethod { - public Button btn; + @FXML + private Button btn; } \ No newline at end of file diff --git a/plugins/settings-repository/src/BaseRepositoryManager.kt b/plugins/settings-repository/src/BaseRepositoryManager.kt index af0b3adec660..8d8ca968ebe0 100644 --- a/plugins/settings-repository/src/BaseRepositoryManager.kt +++ b/plugins/settings-repository/src/BaseRepositoryManager.kt @@ -19,62 +19,53 @@ import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.application.invokeAndWaitIfNeed import com.intellij.openapi.diagnostic.debug import com.intellij.openapi.fileTypes.StdFileTypes -import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vcs.merge.MergeDialogCustomizer import com.intellij.openapi.vcs.merge.MergeProvider2 import com.intellij.openapi.vcs.merge.MultipleFileMergeDialog import com.intellij.openapi.vfs.CharsetToolkit import com.intellij.openapi.vfs.VirtualFile import com.intellij.testFramework.LightVirtualFile -import com.intellij.util.PathUtilRt -import java.io.File -import java.io.FileInputStream +import com.intellij.util.* import java.io.InputStream import java.io.OutputStream +import java.nio.file.Path import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write -abstract class BaseRepositoryManager(protected val dir: File) : RepositoryManager { +abstract class BaseRepositoryManager(protected val dir: Path) : RepositoryManager { protected val lock: ReentrantReadWriteLock = ReentrantReadWriteLock() override fun processChildren(path: String, filter: (name: String) -> Boolean, processor: (name: String, inputStream: InputStream) -> Boolean) { - var files: Array? = null - lock.read { - files = File(dir, path).listFiles({ file, name -> filter(name) }) - } - - if (files == null || files!!.isEmpty()) { - return - } - - for (file in files!!) { - if (file.isDirectory || file.isHidden) { - continue; - } - - // we ignore empty files as well - delete if corrupted - if (file.length() == 0L) { - if (file.exists()) { - try { - LOG.warn("File $path is empty (length 0), will be removed") - delete(file, path) - } - catch (e: Exception) { - LOG.error(e) - } + dir.resolve(path).directoryStreamIfExists { + for (file in it) { + if (file.isDirectory() || file.isHidden()) { + continue; } - continue; - } - if (!processor(file.name, file.inputStream())) { - break; + // we ignore empty files as well - delete if corrupted + if (file.size() == 0L) { + if (file.exists()) { + try { + LOG.warn("File $path is empty (length 0), will be removed") + delete(file, path) + } + catch (e: Exception) { + LOG.error(e) + } + } + continue; + } + + if (!processor(file.fileName.toString(), file.inputStream())) { + break; + } } } } override fun deleteRepository() { - FileUtil.delete(dir) + dir.deleteRecursively() } protected open fun isPathIgnored(path: String): Boolean = false @@ -85,21 +76,22 @@ abstract class BaseRepositoryManager(protected val dir: File) : RepositoryManage return null } - var fileToDelete: File? = null + var fileToDelete: Path? = null lock.read { - val file = File(dir, path) - // we ignore empty files as well - delete if corrupted - if (file.length() == 0L) { - fileToDelete = file - } - else { - return FileInputStream(file) + val file = dir.resolve(path) + when (file.sizeOrNull()) { + -1L -> return null + 0L -> { + // we ignore empty files as well - delete if corrupted + fileToDelete = file + } + else -> return file.inputStream() } } try { lock.write { - if (fileToDelete!!.exists() && fileToDelete!!.length() == 0L) { + if (fileToDelete!!.sizeOrNull() == 0L) { LOG.warn("File $path is empty (length 0), will be removed") delete(fileToDelete!!, path) } @@ -121,9 +113,8 @@ abstract class BaseRepositoryManager(protected val dir: File) : RepositoryManage try { lock.write { - val file = File(dir, path) - FileUtil.writeToFile(file, content, 0, size) - + val file = dir.resolve(path) + file.write(content, 0, size) addToIndex(file, path, content, size) } } @@ -137,13 +128,13 @@ abstract class BaseRepositoryManager(protected val dir: File) : RepositoryManage /** * path relative to repository root */ - protected abstract fun addToIndex(file: File, path: String, content: ByteArray, size: Int) + protected abstract fun addToIndex(file: Path, path: String, content: ByteArray, size: Int) override fun delete(path: String) { LOG.debug { "Remove $path"} lock.write { - val file = File(dir, path) + val file = dir.resolve(path) // delete could be called for non-existent file if (file.exists()) { delete(file, path) @@ -151,25 +142,26 @@ abstract class BaseRepositoryManager(protected val dir: File) : RepositoryManage } } - private fun delete(file: File, path: String) { - val isFile = file.isFile + private fun delete(file: Path, path: String) { + val isFile = file.isFile() file.removeWithParentsIfEmpty(dir, isFile) deleteFromIndex(path, isFile) } protected abstract fun deleteFromIndex(path: String, isFile: Boolean) - override fun has(path: String) = lock.read { File(dir, path).exists() } + override fun has(path: String) = lock.read { dir.resolve(path).exists() } } -fun File.removeWithParentsIfEmpty(root: File, isFile: Boolean = true) { - FileUtil.delete(this) +fun Path.removeWithParentsIfEmpty(root: Path, isFile: Boolean = true) { + delete() if (isFile) { // remove empty directories - var parent = this.parentFile - while (parent != null && parent != root && parent.delete()) { - parent = parent.parentFile + var parent = this.parent + while (parent != null && parent != root) { + parent.delete() + parent = parent.parent } } } diff --git a/plugins/settings-repository/src/IcsManager.kt b/plugins/settings-repository/src/IcsManager.kt index 69208c6bfbe2..baf0837b34c7 100644 --- a/plugins/settings-repository/src/IcsManager.kt +++ b/plugins/settings-repository/src/IcsManager.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,6 +33,8 @@ import com.intellij.openapi.util.AtomicNotNullLazyValue import com.intellij.openapi.util.io.FileUtil import com.intellij.util.SingleAlarm import com.intellij.util.SystemProperties +import com.intellij.util.exists +import com.intellij.util.move import org.jetbrains.keychain.CredentialsStore import org.jetbrains.keychain.FileCredentialsStore import org.jetbrains.keychain.OsXCredentialsStore @@ -40,11 +42,12 @@ import org.jetbrains.keychain.isOSXCredentialsStoreSupported import org.jetbrains.settingsRepository.git.GitRepositoryManager import org.jetbrains.settingsRepository.git.GitRepositoryService import org.jetbrains.settingsRepository.git.processChildren -import java.io.File import java.io.InputStream +import java.nio.file.Path +import java.nio.file.Paths import kotlin.properties.Delegates -val PLUGIN_NAME: String = "Settings Repository" +internal const val PLUGIN_NAME: String = "Settings Repository" internal val LOG: Logger = Logger.getInstance(IcsManager::class.java) @@ -52,7 +55,7 @@ val icsManager by lazy(LazyThreadSafetyMode.NONE) { ApplicationLoadListener.EP_NAME.findExtension(IcsApplicationLoadListener::class.java).icsManager } -class IcsManager(dir: File) { +class IcsManager(dir: Path) { val credentialsStore = object : AtomicNotNullLazyValue() { override fun compute(): CredentialsStore { if (isOSXCredentialsStoreSupported && SystemProperties.getBooleanProperty("ics.use.osx.keychain", true)) { @@ -63,14 +66,14 @@ class IcsManager(dir: File) { LOG.error(e) } } - return FileCredentialsStore(File(dir, ".git_auth")) + return FileCredentialsStore(dir.resolve(".git_auth")) } } - val settingsFile = File(dir, "config.json") + val settingsFile = dir.resolve("config.json") val settings: IcsSettings - val repositoryManager: RepositoryManager = GitRepositoryManager(credentialsStore, File(dir, "repository")) + val repositoryManager: RepositoryManager = GitRepositoryManager(credentialsStore, dir.resolve("repository")) init { try { @@ -226,14 +229,14 @@ class IcsApplicationLoadListener : ApplicationLoadListener { } val customPath = System.getProperty("ics.settingsRepository") - val pluginSystemDir = if (customPath == null) File(configPath, "settingsRepository") else File(FileUtil.expandUserHome(customPath)) + val pluginSystemDir = if (customPath == null) Paths.get(configPath, "settingsRepository") else Paths.get(FileUtil.expandUserHome(customPath)) icsManager = IcsManager(pluginSystemDir) if (!pluginSystemDir.exists()) { try { - val oldPluginDir = File(PathManager.getSystemPath(), "settingsRepository") + val oldPluginDir = Paths.get(PathManager.getSystemPath(), "settingsRepository") if (oldPluginDir.exists()) { - FileUtil.rename(oldPluginDir, pluginSystemDir) + oldPluginDir.move(pluginSystemDir) } } catch (e: Throwable) { diff --git a/plugins/settings-repository/src/ReadOnlySourcesManager.kt b/plugins/settings-repository/src/ReadOnlySourcesManager.kt index 2d7da366baf5..e0590395b714 100644 --- a/plugins/settings-repository/src/ReadOnlySourcesManager.kt +++ b/plugins/settings-repository/src/ReadOnlySourcesManager.kt @@ -16,12 +16,13 @@ package org.jetbrains.settingsRepository import com.intellij.util.SmartList +import com.intellij.util.exists import org.eclipse.jgit.lib.Repository import org.eclipse.jgit.storage.file.FileRepositoryBuilder import org.jetbrains.annotations.TestOnly -import java.io.File +import java.nio.file.Path -class ReadOnlySourcesManager(private val settings: IcsSettings, val rootDir: File) { +class ReadOnlySourcesManager(private val settings: IcsSettings, val rootDir: Path) { private var _repositories: List? = null val repositories: List @@ -36,9 +37,9 @@ class ReadOnlySourcesManager(private val settings: IcsSettings, val rootDir: Fil for (source in settings.readOnlySources) { try { val path = source.path ?: continue - val dir = File(rootDir, path) + val dir = rootDir.resolve(path) if (dir.exists()) { - r.add(FileRepositoryBuilder().setBare().setGitDir(dir).build()) + r.add(FileRepositoryBuilder().setBare().setGitDir(dir.toFile()).build()) } else { LOG.warn("Skip read-only source ${source.url} because dir doesn't exists") @@ -59,5 +60,5 @@ class ReadOnlySourcesManager(private val settings: IcsSettings, val rootDir: Fil _repositories = null } - @TestOnly fun sourceToDir(source: ReadonlySource) = File(rootDir, source.path!!) + @TestOnly fun sourceToDir(source: ReadonlySource) = rootDir.resolve(source.path!!) } \ No newline at end of file diff --git a/plugins/settings-repository/src/RepositoryService.kt b/plugins/settings-repository/src/RepositoryService.kt index 9dcbf7150bfc..17ab3f6f2be1 100644 --- a/plugins/settings-repository/src/RepositoryService.kt +++ b/plugins/settings-repository/src/RepositoryService.kt @@ -16,13 +16,16 @@ package org.jetbrains.settingsRepository import com.intellij.openapi.ui.Messages +import com.intellij.util.exists import com.intellij.util.io.URLUtil +import com.intellij.util.isDirectory import org.eclipse.jgit.lib.Constants import org.eclipse.jgit.transport.URIish import org.jetbrains.settingsRepository.git.createBareRepository import java.awt.Container -import java.io.File import java.io.IOException +import java.nio.file.Path +import java.nio.file.Paths interface RepositoryService { fun checkUrl(uriString: String, messageParent: Container? = null): Boolean { @@ -43,9 +46,9 @@ interface RepositoryService { fun checkFileRepo(url: String, messageParent: Container): Boolean { val suffix = "/${Constants.DOT_GIT}" - val file = File(if (url.endsWith(suffix)) url.substring(0, url.length - suffix.length) else url) + val file = Paths.get(if (url.endsWith(suffix)) url.substring(0, url.length - suffix.length) else url) if (file.exists()) { - if (!file.isDirectory) { + if (!file.isDirectory()) { //noinspection DialogTitleCapitalization Messages.showErrorDialog(messageParent, "Specified path is not a directory", "Specified Path is Invalid") return false @@ -75,5 +78,5 @@ interface RepositoryService { } // must be protected, kotlin bug - fun isValidRepository(file: File): Boolean + fun isValidRepository(file: Path): Boolean } \ No newline at end of file diff --git a/plugins/settings-repository/src/copyAppSettingsToRepository.kt b/plugins/settings-repository/src/copyAppSettingsToRepository.kt index 3791aafc381c..021d763a7079 100644 --- a/plugins/settings-repository/src/copyAppSettingsToRepository.kt +++ b/plugins/settings-repository/src/copyAppSettingsToRepository.kt @@ -23,6 +23,7 @@ import com.intellij.ide.actions.getExportableComponentsMap import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.RoamingType import com.intellij.openapi.components.stateStore +import com.intellij.util.directoryStreamIfExists import com.intellij.util.isFile import com.intellij.util.systemIndependentPath import java.nio.file.Files @@ -55,19 +56,16 @@ fun copyLocalConfig(storageManager: StateStorageManagerImpl = ApplicationManager } private fun saveDirectory(parent: Path, parentFileSpec: String, roamingType: RoamingType, streamProvider: IcsManager.IcsStreamProvider) { - if (!Files.isDirectory(parent)) { - return - } - - - for (file in Files.newDirectoryStream(parent)) { - val childFileSpec = "$parentFileSpec/${file.fileName}" - if (file.isFile()) { - val fileBytes = Files.readAllBytes(file) - streamProvider.doSave(childFileSpec, fileBytes, fileBytes.size, roamingType) - } - else { - saveDirectory(file, childFileSpec, roamingType, streamProvider) + parent.directoryStreamIfExists { + for (file in it) { + val childFileSpec = "$parentFileSpec/${file.fileName}" + if (file.isFile()) { + val fileBytes = Files.readAllBytes(file) + streamProvider.doSave(childFileSpec, fileBytes, fileBytes.size, roamingType) + } + else { + saveDirectory(file, childFileSpec, roamingType, streamProvider) + } } } } diff --git a/plugins/settings-repository/src/git/GitEx.kt b/plugins/settings-repository/src/git/GitEx.kt index 05a69f8860e1..1cf2be1881da 100644 --- a/plugins/settings-repository/src/git/GitEx.kt +++ b/plugins/settings-repository/src/git/GitEx.kt @@ -39,8 +39,8 @@ import org.eclipse.jgit.treewalk.filter.TreeFilter import org.jetbrains.keychain.CredentialsStore import org.jetbrains.settingsRepository.AuthenticationException import org.jetbrains.settingsRepository.LOG -import java.io.File import java.io.InputStream +import java.nio.file.Path fun wrapIfNeedAndReThrow(e: TransportException) { if (e is org.eclipse.jgit.errors.NoRemoteRepositoryException || e.status == TransportException.Status.CANNOT_RESOLVE_REPO) { @@ -91,14 +91,14 @@ fun Repository.disableAutoCrLf(): Repository { return this } -fun createBareRepository(dir: File): Repository { - val repository = FileRepositoryBuilder().setBare().setGitDir(dir).build() +fun createBareRepository(dir: Path): Repository { + val repository = FileRepositoryBuilder().setBare().setGitDir(dir.toFile()).build() repository.create(true) return repository } -fun createRepository(dir: File): Repository { - val repository = FileRepositoryBuilder().setWorkTree(dir).build() +fun createRepository(dir: Path): Repository { + val repository = FileRepositoryBuilder().setWorkTree(dir.toFile()).build() repository.create() return repository } @@ -165,7 +165,7 @@ fun Repository.computeIndexDiff(): IndexDiff { } } -fun cloneBare(uri: String, dir: File, credentialsStore: NotNullLazyValue? = null, progressMonitor: ProgressMonitor = NullProgressMonitor.INSTANCE): Repository { +fun cloneBare(uri: String, dir: Path, credentialsStore: NotNullLazyValue? = null, progressMonitor: ProgressMonitor = NullProgressMonitor.INSTANCE): Repository { val repository = createBareRepository(dir) val config = repository.setUpstream(uri) val remoteConfig = RemoteConfig(config, Constants.DEFAULT_REMOTE_NAME) diff --git a/plugins/settings-repository/src/git/GitRepositoryManager.kt b/plugins/settings-repository/src/git/GitRepositoryManager.kt index e76ab13f894b..978462fe4a5d 100644 --- a/plugins/settings-repository/src/git/GitRepositoryManager.kt +++ b/plugins/settings-repository/src/git/GitRepositoryManager.kt @@ -20,9 +20,8 @@ import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.util.NotNullLazyValue import com.intellij.openapi.util.ShutDownTracker -import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil -import com.intellij.util.SmartList +import com.intellij.util.* import org.eclipse.jgit.api.AddCommand import org.eclipse.jgit.api.errors.NoHeadException import org.eclipse.jgit.api.errors.UnmergedPathsException @@ -41,16 +40,17 @@ import org.jetbrains.jgit.dirCache.edit import org.jetbrains.keychain.CredentialsStore import org.jetbrains.settingsRepository.* import org.jetbrains.settingsRepository.RepositoryManager.Updater -import java.io.File import java.io.IOException +import java.nio.file.Files +import java.nio.file.Path import kotlin.concurrent.write -class GitRepositoryManager(private val credentialsStore: NotNullLazyValue, dir: File) : BaseRepositoryManager(dir) { +class GitRepositoryManager(private val credentialsStore: NotNullLazyValue, dir: Path) : BaseRepositoryManager(dir) { val repository: Repository get() { var r = _repository if (r == null) { - r = FileRepositoryBuilder().setWorkTree(dir).build() + r = FileRepositoryBuilder().setWorkTree(dir.toFile()).build() _repository = r if (ApplicationManager.getApplication()?.isUnitTestMode != true) { ShutDownTracker.getInstance().registerShutdownTask { _repository?.close() } @@ -103,7 +103,7 @@ class GitRepositoryManager(private val credentialsStore: NotNullLazyValue() for ((oldPath, newPath) in pairs) { - val old = File(dir, oldPath) + val old = dir.resolve(oldPath) if (!old.exists()) { continue } LOG.info("Rename $oldPath to $newPath") - - val files = old.listFiles() - if (files != null) { - val new = if (newPath == null) dir else File(dir, newPath) - for (file in files) { + old.directoryStreamIfExists { + val new = if (newPath == null) dir else dir.resolve(newPath) + for (file in it) { try { - if (file.isHidden) { - FileUtil.delete(file) + if (file.isHidden()) { + file.delete() } else { - file.renameTo(File(new, file.name)) + Files.move(file, new.resolve(file.fileName)) if (addCommand == null) { addCommand = AddCommand(repository) } - addCommand.addFilepattern(if (newPath == null) file.name else "$newPath/${file.name}") + addCommand!!.addFilepattern(if (newPath == null) file.fileName.toString() else "$newPath/${file.fileName}") } } catch (e: Throwable) { @@ -270,7 +268,7 @@ class GitRepositoryManager(private val credentialsStore: NotNullLazyValue(MyPrettyPrinter()).writeValueAsBytes(settings) if (serialized.size <= 2) { - FileUtil.delete(settingsFile) + settingsFile.delete() } else { - FileUtil.writeToFile(settingsFile, serialized) + settingsFile.write(serialized) } } -fun loadSettings(settingsFile: File): IcsSettings { +fun loadSettings(settingsFile: Path): IcsSettings { if (!settingsFile.exists()) { return IcsSettings() } - val settings = ObjectMapper().readValue(settingsFile, IcsSettings::class.java) + val settings = ObjectMapper().readValue(settingsFile.toFile(), IcsSettings::class.java) if (settings.commitDelay <= 0) { settings.commitDelay = DEFAULT_COMMIT_DELAY } diff --git a/plugins/settings-repository/src/settings/readOnlySourcesEditor.kt b/plugins/settings-repository/src/settings/readOnlySourcesEditor.kt index a340523b1f5a..875108a4f17d 100644 --- a/plugins/settings-repository/src/settings/readOnlySourcesEditor.kt +++ b/plugins/settings-repository/src/settings/readOnlySourcesEditor.kt @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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,17 +23,17 @@ import com.intellij.openapi.progress.Task import com.intellij.openapi.ui.DialogBuilder import com.intellij.openapi.ui.TextBrowseFolderListener import com.intellij.openapi.ui.TextFieldWithBrowseButton -import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.StringUtil import com.intellij.ui.DocumentAdapter import com.intellij.util.Function import com.intellij.util.containers.ContainerUtil +import com.intellij.util.deleteRecursively +import com.intellij.util.exists import com.intellij.util.ui.FormBuilder import com.intellij.util.ui.table.TableModelEditor import gnu.trove.THashSet import org.jetbrains.settingsRepository.git.asProgressMonitor import org.jetbrains.settingsRepository.git.cloneBare -import java.io.File import javax.swing.JTextField import javax.swing.event.DocumentEvent @@ -130,7 +130,7 @@ internal fun createReadOnlySourcesEditor(): ConfigurableUi { indicator.checkCanceled() try { indicator.text2 = path - FileUtil.delete(File(root, path)) + root.resolve(path).deleteRecursively() } catch (e: Exception) { LOG.error(e) @@ -143,9 +143,9 @@ internal fun createReadOnlySourcesEditor(): ConfigurableUi { indicator.checkCanceled() try { indicator.text = "Cloning ${StringUtil.trimMiddle(source.url!!, 255)}" - val dir = File(root, source.path!!) + val dir = root.resolve(source.path!!) if (dir.exists()) { - FileUtil.delete(dir) + dir.deleteRecursively() } cloneBare(source.url!!, dir, icsManager.credentialsStore, indicator.asProgressMonitor()).close() } diff --git a/plugins/settings-repository/testSrc/BareGitTest.kt b/plugins/settings-repository/testSrc/BareGitTest.kt index 18aa6fc8e1cb..3d938cc2c14e 100644 --- a/plugins/settings-repository/testSrc/BareGitTest.kt +++ b/plugins/settings-repository/testSrc/BareGitTest.kt @@ -31,7 +31,7 @@ internal class BareGitTest { @Rule fun getTemporaryFolder() = tempDirManager @Test fun `remote doesn't have commits`() { - val repository = cloneBare(tempDirManager.createRepository("remote").workTree.absolutePath, tempDirManager.newDirectory("local")) + val repository = cloneBare(tempDirManager.createRepository("remote").workTree.absolutePath, tempDirManager.newPath("local")) assertThat(repository.read("\$ROOT_CONFIG$/keymaps/Mac OS X from RubyMine.xml")).isNull() } @@ -41,7 +41,7 @@ internal class BareGitTest { remoteRepository.add(filePath, SAMPLE_FILE_CONTENT) remoteRepository.commit("") - val repository = cloneBare(remoteRepository.workTree.absolutePath, tempDirManager.newDirectory()) + val repository = cloneBare(remoteRepository.workTree.absolutePath, tempDirManager.newPath()) assertThat(FileUtil.loadTextAndClose(repository.read(filePath)!!)).isEqualTo(SAMPLE_FILE_CONTENT) } @@ -52,7 +52,7 @@ internal class BareGitTest { remoteRepository.add(filePath, SAMPLE_FILE_CONTENT) remoteRepository.commit("") - val repository = cloneBare(remoteRepository.workTree.absolutePath, tempDirManager.newDirectory()) + val repository = cloneBare(remoteRepository.workTree.absolutePath, tempDirManager.newPath()) val data = THashMap() repository.processChildren("keymaps") {name, input -> diff --git a/plugins/settings-repository/testSrc/CredentialsTest.kt b/plugins/settings-repository/testSrc/CredentialsTest.kt index 194456ee0e9a..3b7041b8cd8a 100644 --- a/plugins/settings-repository/testSrc/CredentialsTest.kt +++ b/plugins/settings-repository/testSrc/CredentialsTest.kt @@ -18,12 +18,11 @@ class CredentialsTest { private var storeFile: File? = null private fun createProvider(credentialsStore: CredentialsStore): JGitCredentialsProvider { - return JGitCredentialsProvider(NotNullLazyValue.createConstantValue(credentialsStore), FileRepositoryBuilder().setBare().setGitDir(File("/tmp/fake")).build()) + return JGitCredentialsProvider(NotNullLazyValue.createConstantValue(credentialsStore), FileRepositoryBuilder().setBare().setGitDir(File("/tmp/fake")).build()) } private fun createFileStore(): FileCredentialsStore { - storeFile = FileUtil.generateRandomTemporaryPath() - return FileCredentialsStore(storeFile!!) + return FileCredentialsStore(FileUtil.generateRandomTemporaryPath().toPath()) } @After fun tearDown() { diff --git a/plugins/settings-repository/testSrc/GitTest.kt b/plugins/settings-repository/testSrc/GitTest.kt index 4dc4ab396f2d..a6f25f194b66 100644 --- a/plugins/settings-repository/testSrc/GitTest.kt +++ b/plugins/settings-repository/testSrc/GitTest.kt @@ -322,7 +322,7 @@ internal class GitTest : GitTestCase() { repositoryManager.setUpstream(remoteRepository.workTree.absolutePath) val store = ApplicationStoreImpl(ApplicationManager.getApplication()!!) - val localConfigPath = tempDirManager.newPath("local_config") + val localConfigPath = tempDirManager.newPath("local_config", refreshVfs = true) val lafData = """ diff --git a/plugins/settings-repository/testSrc/IcsTestCase.kt b/plugins/settings-repository/testSrc/IcsTestCase.kt index 34a83e419cb1..ef614ec565b8 100644 --- a/plugins/settings-repository/testSrc/IcsTestCase.kt +++ b/plugins/settings-repository/testSrc/IcsTestCase.kt @@ -53,7 +53,7 @@ abstract class IcsTestCase { get() = fsRule.fs val icsManager by lazy(LazyThreadSafetyMode.NONE) { - val icsManager = IcsManager(tempDirManager.newDirectory()) + val icsManager = IcsManager(tempDirManager.newPath()) icsManager.repositoryManager.createRepositoryIfNeed() icsManager.repositoryActive = true icsManager @@ -62,4 +62,4 @@ abstract class IcsTestCase { val provider by lazy(LazyThreadSafetyMode.NONE) { icsManager.ApplicationLevelProvider() } } -fun TemporaryDirectory.createRepository(directoryName: String? = null) = createGitRepository(newDirectory(directoryName)) +fun TemporaryDirectory.createRepository(directoryName: String? = null) = createGitRepository(newPath(directoryName)) diff --git a/plugins/settings-repository/testSrc/LoadTest.kt b/plugins/settings-repository/testSrc/LoadTest.kt index 85ebccd8c230..dee73511a9b0 100644 --- a/plugins/settings-repository/testSrc/LoadTest.kt +++ b/plugins/settings-repository/testSrc/LoadTest.kt @@ -28,7 +28,6 @@ import org.jetbrains.settingsRepository.git.cloneBare import org.jetbrains.settingsRepository.git.commit import org.junit.ClassRule import org.junit.Test -import java.io.File class LoadTest : IcsTestCase() { companion object { @@ -38,7 +37,7 @@ class LoadTest : IcsTestCase() { private val dirPath = "\$ROOT_CONFIG$/keymaps" - private fun createSchemeManager(dirPath: String) = SchemeManagerImpl(dirPath, TestSchemesProcessor(), provider, tempDirManager.newDirectory("schemes")) + private fun createSchemeManager(dirPath: String) = SchemeManagerImpl(dirPath, TestSchemesProcessor(), provider, tempDirManager.newPath("schemes")) @Test fun `load scheme`() { val localScheme = TestScheme("local") @@ -112,7 +111,7 @@ class LoadTest : IcsTestCase() { fun Repository.createAndRegisterReadOnlySource(): ReadonlySource { val source = ReadonlySource(workTree.absolutePath) - assertThat(cloneBare(source.url!!, File(icsManager.readOnlySourcesManager.rootDir, source.path!!)).objectDatabase.exists()).isTrue() + assertThat(cloneBare(source.url!!, icsManager.readOnlySourcesManager.rootDir.resolve(source.path!!)).objectDatabase.exists()).isTrue() icsManager.readOnlySourcesManager.setSources(listOf(source)) return source } diff --git a/plugins/settings-repository/testSrc/OverwriteRemoteTest.kt b/plugins/settings-repository/testSrc/OverwriteRemoteTest.kt index 94db204796d1..eb1f3bd200b2 100644 --- a/plugins/settings-repository/testSrc/OverwriteRemoteTest.kt +++ b/plugins/settings-repository/testSrc/OverwriteRemoteTest.kt @@ -1,11 +1,10 @@ package org.jetbrains.settingsRepository.test import com.intellij.testFramework.file -import com.intellij.util.isDirectory +import com.intellij.util.directoryStreamIfExists import com.intellij.util.readBytes import org.jetbrains.settingsRepository.SyncType import org.junit.Test -import java.nio.file.Files // empty means "no files, no HEAD, no commits" internal class OverwriteRemote : GitTestCase() { @@ -37,8 +36,8 @@ internal class OverwriteRemote : GitTestCase() { configureLocalRepository() val root = fs.getPath("/") - if (root.isDirectory()) { - for (path in Files.newDirectoryStream(root)) { + root.directoryStreamIfExists { + for (path in it) { provider.write(path.toString().substring(1), path.readBytes()) } repositoryManager.commit() diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java index 36a869f7e9d6..4215721c18af 100644 --- a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java +++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2015 JetBrains s.r.o. + * Copyright 2000-2016 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,9 +17,10 @@ package org.jetbrains.plugins.terminal; import com.intellij.execution.TaskExecutor; import com.intellij.execution.configurations.EncodingEnvironmentUtil; -import com.intellij.execution.process.*; -import com.intellij.openapi.application.Application; -import com.intellij.openapi.application.ApplicationManager; +import com.intellij.execution.process.ProcessAdapter; +import com.intellij.execution.process.ProcessEvent; +import com.intellij.execution.process.ProcessHandler; +import com.intellij.execution.process.ProcessWaitFor; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectRootManager; @@ -27,6 +28,7 @@ import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.vfs.CharsetToolkit; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.Consumer; +import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.HashMap; import com.jediterm.pty.PtyProcessTtyConnector; import com.jediterm.terminal.TtyConnector; @@ -216,17 +218,7 @@ public class LocalTerminalDirectRunner extends AbstractTerminalRunner executeTask(@NotNull Runnable task) { - return executeOnPooledThread(task); - } - - protected static Future executeOnPooledThread(Runnable task) { - final Application application = ApplicationManager.getApplication(); - - if (application != null) { - return application.executeOnPooledThread(task); - } - - return BaseOSProcessHandler.submit(task); + return AppExecutorUtil.getAppExecutorService().submit(task); } } } diff --git a/python/educational-core/student/resources/code-mirror/codemirror-darcula.css b/python/educational-core/student/resources/code-mirror/codemirror-darcula.css index 3e66be66285d..07a9b001ba41 100644 --- a/python/educational-core/student/resources/code-mirror/codemirror-darcula.css +++ b/python/educational-core/student/resources/code-mirror/codemirror-darcula.css @@ -20,7 +20,7 @@ body { } code { - font-family: Courier, monospace; + font-family: "Source Code Pro", monospace; } /* BASICS */ diff --git a/python/educational-core/student/resources/code-mirror/codemirror.css b/python/educational-core/student/resources/code-mirror/codemirror.css index 02a90171af55..c54eb33f7efa 100644 --- a/python/educational-core/student/resources/code-mirror/codemirror.css +++ b/python/educational-core/student/resources/code-mirror/codemirror.css @@ -5,7 +5,7 @@ body { } code { - font-family: "Source Code Pro", fantasy; + font-family: "Source Code Pro", monospace; } /* BASICS */ .task-help pre code { diff --git a/python/ipnb/src/org/jetbrains/plugins/ipnb/editor/panels/code/IpnbImagePanel.java b/python/ipnb/src/org/jetbrains/plugins/ipnb/editor/panels/code/IpnbImagePanel.java index fe3e73141b99..c57528359fa8 100644 --- a/python/ipnb/src/org/jetbrains/plugins/ipnb/editor/panels/code/IpnbImagePanel.java +++ b/python/ipnb/src/org/jetbrains/plugins/ipnb/editor/panels/code/IpnbImagePanel.java @@ -12,7 +12,6 @@ import javax.imageio.ImageIO; import javax.swing.*; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; -import java.io.IOException; public class IpnbImagePanel extends IpnbCodeOutputPanel { private static final Logger LOG = Logger.getInstance(IpnbImagePanel.class); @@ -32,7 +31,7 @@ public class IpnbImagePanel extends IpnbCodeOutputPanel { BufferedImage image = ImageIO.read(new ByteArrayInputStream(btDataFile)); label.setIcon(new ImageIcon(image)); } - catch (IOException e) { + catch (Exception e) { LOG.error("Couldn't parse image. " + e.getMessage()); } } @@ -42,4 +41,4 @@ public class IpnbImagePanel extends IpnbCodeOutputPanel { return label; } -} +} \ No newline at end of file diff --git a/python/src/META-INF/python-core-common.xml b/python/src/META-INF/python-core-common.xml index 73499939e3de..0fd613ce7bc0 100644 --- a/python/src/META-INF/python-core-common.xml +++ b/python/src/META-INF/python-core-common.xml @@ -149,7 +149,6 @@ - @@ -388,6 +387,7 @@ + { * For modules and packages it should be qualified name of their parental package * (empty for modules and packages located at source roots). * - * @see PythonReferenceImporter#proposeImportFix */ public ImportCandidateHolder(@NotNull PsiElement importable, @NotNull PsiFileSystemItem file, @Nullable PyImportElement importElement, @Nullable QualifiedName path, @Nullable String asName) { diff --git a/python/src/com/jetbrains/python/codeInsight/imports/PythonReferenceImporter.java b/python/src/com/jetbrains/python/codeInsight/imports/PythonImportUtils.java similarity index 86% rename from python/src/com/jetbrains/python/codeInsight/imports/PythonReferenceImporter.java rename to python/src/com/jetbrains/python/codeInsight/imports/PythonImportUtils.java index e9e18d57ef8d..d5f49fd7255a 100644 --- a/python/src/com/jetbrains/python/codeInsight/imports/PythonReferenceImporter.java +++ b/python/src/com/jetbrains/python/codeInsight/imports/PythonImportUtils.java @@ -56,57 +56,9 @@ import java.util.*; import static com.jetbrains.python.psi.PyUtil.as; -public class PythonReferenceImporter implements ReferenceImporter { - @Override - public boolean autoImportReferenceAtCursor(@NotNull final Editor editor, @NotNull final PsiFile file) { - if (!(file instanceof PyFile)) { - return false; - } - int caretOffset = editor.getCaretModel().getOffset(); - Document document = editor.getDocument(); - int lineNumber = document.getLineNumber(caretOffset); - int startOffset = document.getLineStartOffset(lineNumber); - int endOffset = document.getLineEndOffset(lineNumber); +public final class PythonImportUtils { + private PythonImportUtils() { - List elements = CollectHighlightsUtil.getElementsInRange(file, startOffset, endOffset); - for (PsiElement element : elements) { - if (element instanceof PyReferenceExpression && isImportable(element)) { - final PyReferenceExpression refExpr = (PyReferenceExpression)element; - if (!refExpr.isQualified()) { - final PsiPolyVariantReference reference = refExpr.getReference(); - if (reference.resolve() == null) { - AutoImportQuickFix fix = proposeImportFix(refExpr, reference); - if (fix != null && fix.getCandidatesCount() == 1) { - fix.invoke(file); - } - return true; - } - } - } - } - return false; - } - - @Override - public boolean autoImportReferenceAt(@NotNull Editor editor, @NotNull PsiFile file, int offset) { - if (!(file instanceof PyFile)) { - return false; - } - PsiReference element = file.findReferenceAt(offset); - if (element instanceof PyReferenceExpression && isImportable((PsiElement)element)) { - final PyReferenceExpression refExpr = (PyReferenceExpression)element; - if (!refExpr.isQualified()) { - final PsiPolyVariantReference reference = refExpr.getReference(); - if (reference.resolve() == null) { - AutoImportQuickFix fix = proposeImportFix(refExpr, reference); - if (fix != null && fix.getCandidatesCount() == 1) { - fix.invoke(file); - } - return true; - } - } - } - return false; } @Nullable diff --git a/python/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesInspection.java b/python/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesInspection.java index 5411e5f99d6c..be33d6f0eeb9 100644 --- a/python/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesInspection.java +++ b/python/src/com/jetbrains/python/inspections/unresolvedReference/PyUnresolvedReferencesInspection.java @@ -47,7 +47,7 @@ import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil; import com.jetbrains.python.codeInsight.imports.AutoImportHintAction; import com.jetbrains.python.codeInsight.imports.AutoImportQuickFix; import com.jetbrains.python.codeInsight.imports.OptimizeImportsQuickFix; -import com.jetbrains.python.codeInsight.imports.PythonReferenceImporter; +import com.jetbrains.python.codeInsight.imports.PythonImportUtils; import com.jetbrains.python.console.PydevConsoleRunner; import com.jetbrains.python.documentation.docstrings.DocStringParameterReference; import com.jetbrains.python.documentation.docstrings.DocStringTypeReference; @@ -593,7 +593,7 @@ public class PyUnresolvedReferencesInspection extends PyInspection { description = PyBundle.message("INSP.unresolved.ref.$0", refText); // look in other imported modules for this whole name - if (PythonReferenceImporter.isImportable(element)) { + if (PythonImportUtils.isImportable(element)) { addAutoImportFix(node, reference, actions); } @@ -918,7 +918,7 @@ public class PyUnresolvedReferencesInspection extends PyInspection { private static void addAutoImportFix(PyElement node, PsiReference reference, List actions) { final PsiFile file = InjectedLanguageManager.getInstance(node.getProject()).getTopLevelFile(node); if (!(file instanceof PyFile)) return; - AutoImportQuickFix importFix = PythonReferenceImporter.proposeImportFix(node, reference); + AutoImportQuickFix importFix = PythonImportUtils.proposeImportFix(node, reference); if (importFix != null) { if (!suppressHintForAutoImport(node, importFix) && PyCodeInsightSettings.getInstance().SHOW_IMPORT_POPUP) { final AutoImportHintAction autoImportHintAction = new AutoImportHintAction(importFix); diff --git a/python/src/com/jetbrains/python/psi/impl/PyGotoDeclarationHandler.java b/python/src/com/jetbrains/python/psi/impl/PyGotoDeclarationHandler.java new file mode 100644 index 000000000000..b85f15212731 --- /dev/null +++ b/python/src/com/jetbrains/python/psi/impl/PyGotoDeclarationHandler.java @@ -0,0 +1,62 @@ +/* + * Copyright 2000-2016 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.jetbrains.python.psi.impl; + +import com.intellij.codeInsight.navigation.actions.GotoDeclarationHandlerBase; +import com.intellij.openapi.editor.Editor; +import com.intellij.psi.PsiElement; +import com.jetbrains.python.psi.PyReferenceOwner; +import com.jetbrains.python.psi.resolve.PyResolveContext; +import com.jetbrains.python.psi.types.TypeEvalContext; +import org.jetbrains.annotations.Nullable; + +/** + * {@link com.intellij.codeInsight.navigation.actions.GotoDeclarationAction} uses {@link PsiElement#findReferenceAt(int)}. + * This method knows nothing about execution context and {@link PyBaseElementImpl} injects loose {@link TypeEvalContext}. + * While regular methods are indexed, {@link com.jetbrains.python.codeInsight.PyCustomMember} are not. + * As result, "go to declaration" failed to resolve reference pointing to another files which leads to bugs like PY-18089. + *

+ * "Go to declaration" is always user-initiated action, so we resolve it manually using best conext + * + * @author Ilya.Kazakevich + */ +public final class PyGotoDeclarationHandler extends GotoDeclarationHandlerBase { + @Nullable + @Override + public PsiElement getGotoDeclarationTarget(@Nullable final PsiElement sourceElement, final Editor editor) { + if (sourceElement == null) { + return null; + } + PyReferenceOwner referenceOwner = null; + if (sourceElement instanceof PyReferenceOwner) { + referenceOwner = (PyReferenceOwner)sourceElement; + } + else if (sourceElement.getParent() instanceof PyReferenceOwner) { + referenceOwner = (PyReferenceOwner)sourceElement.getParent(); //Reference expression may be parent of IDENTIFIER + } + if (referenceOwner == null) { + return null; + } + + final PyResolveContext context = PyResolveContext.noImplicits() + .withTypeEvalContext(TypeEvalContext.userInitiated(sourceElement.getProject(), sourceElement.getContainingFile())); + final PsiElement psiElement = referenceOwner.getReference(context).resolve(); + if (psiElement == null) { + return null; + } + return psiElement; + } +} diff --git a/resources-en/src/inspectionDescriptions/BlockMarkerComments.html b/resources-en/src/inspectionDescriptions/BlockMarkerComments.html index a101cf2e3a06..8fc8aaef9378 100644 --- a/resources-en/src/inspectionDescriptions/BlockMarkerComments.html +++ b/resources-en/src/inspectionDescriptions/BlockMarkerComments.html @@ -1,18 +1,3 @@ - This inspection reports comments which are code block markers diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/html/HtmlFileImpl.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/html/HtmlFileImpl.java index 82429fe43b54..bf03ac07a2a2 100644 --- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/html/HtmlFileImpl.java +++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/html/HtmlFileImpl.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2009 JetBrains s.r.o. + * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,6 +31,9 @@ import com.intellij.psi.xml.XmlElementType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Collection; +import java.util.Collections; + /** * @author maxim */ @@ -91,4 +94,9 @@ public class HtmlFileImpl extends XmlFileImpl implements FileReferenceResolver { return getManager().findFile(childFile); } } + + @Override + public Collection getVariants(@NotNull FileReference reference) { + return Collections.emptyList(); + } }